From ae09dd1471f8bd0545f630ca0b8b76890b292471 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:28:32 +0000 Subject: [PATCH 1/5] fix(server): only a founder settles a thread in their inbox Agent settles (MCP organize on any thread, settle-after-run, peer MCP) and server auto-settles are refused at dispatch for a thread in a founder or shared inbox. thread.settle carries a server-stamped actor, persisted on the event; the WS stamps it from the authenticated session. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/auth/settleActor.test.ts | 22 +++ apps/server/src/auth/settleActor.ts | 11 ++ apps/server/src/mcp/toolkits/core.test.ts | 49 +++++ .../src/mcp/toolkits/thread/handlers.ts | 13 +- .../Orchestrator.control-reads.test.ts | 9 + .../src/orchestration-v2/Orchestrator.ts | 15 ++ .../ThreadManagementService.ts | 30 ++- .../ThreadSettlementService.ts | 7 +- .../src/orchestration-v2/runtimeLayer.test.ts | 186 +++++++++++++++++- .../persistence/OrchestrationEventStore.ts | 2 + apps/server/src/ws.ts | 12 ++ packages/contracts/src/orchestrationV2.ts | 16 ++ packages/contracts/src/threadInbox.ts | 17 ++ 13 files changed, 379 insertions(+), 10 deletions(-) create mode 100644 apps/server/src/auth/settleActor.test.ts create mode 100644 apps/server/src/auth/settleActor.ts diff --git a/apps/server/src/auth/settleActor.test.ts b/apps/server/src/auth/settleActor.test.ts new file mode 100644 index 0000000000000..af69e70635a23 --- /dev/null +++ b/apps/server/src/auth/settleActor.test.ts @@ -0,0 +1,22 @@ +import { AuthSessionId } from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; + +import { settleActorOf } from "./settleActor.ts"; + +const sessionId = AuthSessionId.make("settle-actor-session"); + +describe("settleActorOf", () => { + it("names a person's client session as its founder", () => { + expect( + settleActorOf({ sessionId, device: "Laptop", deviceType: "desktop", founder: "kameron" }), + ).toEqual({ kind: "founder", founder: "kameron", sessionId, client: "Laptop" }); + }); + + it("names a bot's session as an agent, so a founder's inbox refuses its settle", () => { + expect(settleActorOf({ sessionId, device: "", deviceType: "bot", founder: null })).toEqual({ + kind: "agent", + founder: null, + sessionId, + }); + }); +}); diff --git a/apps/server/src/auth/settleActor.ts b/apps/server/src/auth/settleActor.ts new file mode 100644 index 0000000000000..3fe9da49aed87 --- /dev/null +++ b/apps/server/src/auth/settleActor.ts @@ -0,0 +1,11 @@ +import type { OrchestrationV2CommandActor, OrchestrationV2MessageSentBy } from "@t3tools/contracts"; + +/** A person's client session settles as a founder; a bot's session settles as an agent. */ +export const settleActorOf = ( + sentBy: OrchestrationV2MessageSentBy, +): OrchestrationV2CommandActor => ({ + kind: sentBy.deviceType === "bot" ? "agent" : "founder", + founder: sentBy.founder, + sessionId: sentBy.sessionId, + ...(sentBy.device === "" ? {} : { client: sentBy.device }), +}); diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 099f0f15abf4a..9c3d82a98b891 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -701,6 +701,55 @@ it.effect("rejects an unknown organize target instead of archiving the calling t ); }); +it.effect("settles through organize as an agent, on its own thread or another", () => { + const settles: Array< + Parameters[0] + > = []; + return Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const settle = (invocation: McpInvocationContext.McpInvocationScope, target?: string) => + server + .callTool({ + name: "t3_thread_organize", + arguments: { action: "settle", ...(target === undefined ? {} : { threadId: target }) }, + }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), + Effect.provideService(McpSchema.McpServerClient, client), + ); + expect((yield* settle(scope)).isError).toBe(false); + expect((yield* settle(clientScope("full-access"), "other-thread")).isError).toBe(false); + expect(settles).toMatchObject([ + { threadId, byOwnAgent: true, actor: { kind: "agent", agentThreadId: threadId } }, + { + threadId: "other-thread", + byOwnAgent: false, + actor: { kind: "agent", client: "Claude Code" }, + }, + ]); + }).pipe( + Effect.provide( + layerThreadToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provide(NodeCrypto.layer), + Layer.provide( + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: (id) => Effect.succeed(McpToolAccessTestkit.liveThreadShell(id)), + getProjectThreadRecords: ({ threadId: id }) => + Effect.succeed( + McpToolAccessTestkit.idleThreadProjection(McpToolAccessTestkit.liveThreadShell(id)), + ), + settleThread: (input) => { + settles.push(input); + return Effect.succeed({ sequence: 1 }); + }, + }), + ), + ), + ), + ); +}); + it.effect("keeps unexpected handler defects private through the production registration", () => Effect.gen(function* () { const server = yield* McpServer.McpServer; diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index fced6484e2bee..10743a48c7bf6 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -413,11 +413,20 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { ), t3_thread_organize: writesThread((input) => Effect.gen(function* () { - const { threads, projection, caller } = yield* readThread(input.threadId); + const { threads, projection, caller, scope } = yield* readThread(input.threadId); const common = { commandId: yield* newCommandId(), threadId: projection.thread.id }; if (input.action === "settle") { + // Every MCP caller is an agent, a linked environment's included. return yield* threads - .settleThread({ ...common, byOwnAgent: caller?.id === projection.thread.id }) + .settleThread({ + ...common, + byOwnAgent: caller?.id === projection.thread.id, + actor: { + kind: "agent", + ...(caller === undefined ? {} : { agentThreadId: caller.id }), + ...(scope.client === undefined ? {} : { client: scope.client.label }), + }, + }) .pipe(Effect.mapError(dispatchFailure)); } let command: OrchestrationV2Command; diff --git a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts index 29063a75ddb61..055108f38e30b 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts @@ -24,6 +24,7 @@ import { RuntimeRequestId, ThreadId, TurnItemId, + makeThreadInbox, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; @@ -2511,6 +2512,7 @@ it.effect.each(["thread.settle", "thread.auto-settle"] as const)( payload: { ...before, id: childId, + inbox: makeThreadInbox({ actor: null }), lineage: { parentThreadId: threadId, rootThreadId: threadId, @@ -2534,6 +2536,13 @@ it.effect.each(["thread.settle", "thread.auto-settle"] as const)( threadId, standing: null, }); + // A persona files the thread for the founders; only once it is back in Agents may it settle. + yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("standing-root:to-agents"), + threadId, + inboxRouting: { owner: null, assignee: null, audience: "agent-only" }, + }); const retired = yield* projections.getThread(threadId); yield* orchestrator.dispatch({ type, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index aa2babc0b6341..067505187ece4 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -9,6 +9,8 @@ import type { } from "@t3tools/contracts"; import { inboxAfterStandingSet, + founderInboxHolder, + founderInboxSettleRefusal, isStandingThreadRoot, makeThreadInbox, nextFounderSeenMessage, @@ -5622,6 +5624,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio "Standing role threads cannot be settled. Clear its standing persona before settling.", }); } + // Every settle path reaches here, a deferred settle-after-run included, so it re-checks now. + const inboxHolder = founderInboxHolder(thread.inbox); + if (inboxHolder !== null && command.actor?.kind !== "founder") { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: founderInboxSettleRefusal(inboxHolder), + }); + } const projection = yield* loadProjectionForCommand( command, ["runs", "runtimeRequests", "providerThreads", "turnItems"], @@ -6678,6 +6689,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio providerInstanceId: updatedThread.providerInstanceId, occurredAt: now, payload: updatedThread, + ...(command.type === "thread.settle" && command.actor !== undefined + ? { actor: command.actor } + : {}), }); // Archiving ends the guest share, so its waiting files go too. yield* releaseGuestAttachments(command, thread.guestShare, updatedThread.guestShare, effects); @@ -17676,6 +17690,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio type: "thread.settle", commandId: command.commandId, threadId: command.threadId, + actor: { kind: "server" }, ...(command.settledAt === undefined ? {} : { settledAt: command.settledAt }), }, events, diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 2365a74894ff3..95e8112a266b2 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1,7 +1,10 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; import { BACKGROUND_WAIT_STALE_MINUTES, + founderInboxHolder, + founderInboxSettleRefusal, isStandingThreadRoot, + type OrchestrationV2CommandActor, ThreadRedirectError, } from "@t3tools/contracts"; import { staleTimeoutMs } from "./waitStaleness.ts"; @@ -590,11 +593,15 @@ export interface ThreadManagementServiceShape { readonly projectId: ProjectId; readonly threadId: ThreadId; readonly runId: RunId; + /** Who asked; absent means the server. A founder inbox refuses any but a founder. */ + readonly actor?: OrchestrationV2CommandActor; }) => Effect.Effect; + /** Refuses at once when a founder's inbox holds the thread and `actor` is not a founder. */ readonly settleThread: (input: { readonly threadId: ThreadId; readonly commandId: CommandId; readonly byOwnAgent: boolean; + readonly actor: OrchestrationV2CommandActor; }) => Effect.Effect< { readonly sequence: number } | { readonly settlesWhenTurnEnds: true }, Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError @@ -1473,6 +1480,8 @@ const make = Effect.gen(function* () { ) ) return true; + // A founder's inbox took the thread while the turn ran; the dispatch would refuse it. + if (founderInboxHolder(records.thread.inbox) !== null) return true; const later = records.runs.filter((candidate) => candidate.ordinal > run.ordinal); const cancelledMessageIds = later .filter((candidate) => candidate.status === "cancelled") @@ -1536,6 +1545,7 @@ const make = Effect.gen(function* () { commandId: CommandId.make(`server:settle-after-run:${input.runId}:${sequence}`), threadId: input.threadId, expectedLatestRunId: latest.id, + actor: input.actor ?? { kind: "server" }, }).pipe( Effect.as(true), // A notification can start between the projection read and the guarded dispatch. @@ -1564,12 +1574,27 @@ const make = Effect.gen(function* () { const settleThread: ThreadManagementServiceShape["settleThread"] = Effect.fn( "orchestrationV2.threadManagement.settleThread", )(function* (input) { - const shell = input.byOwnAgent ? yield* orchestrator.getThreadShell(input.threadId) : null; - if (shell != null && shell.activeRunId !== null && !isStandingThreadRoot(shell)) { + const shell = yield* orchestrator.getThreadShell(input.threadId); + const inboxHolder = founderInboxHolder(shell?.inbox); + // Refuse before deferring, so an agent learns now instead of at a settle that never lands. + if (inboxHolder !== null && input.actor.kind !== "founder") { + return yield* new Orchestrator.OrchestratorDispatchError({ + commandId: input.commandId, + commandType: "thread.settle", + cause: founderInboxSettleRefusal(inboxHolder), + }); + } + if ( + input.byOwnAgent && + shell != null && + shell.activeRunId !== null && + !isStandingThreadRoot(shell) + ) { yield* settleAfterRun({ projectId: shell.projectId, threadId: shell.id, runId: shell.activeRunId, + actor: input.actor, }).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(layerScope)); return { settlesWhenTurnEnds: true } as const; } @@ -1577,6 +1602,7 @@ const make = Effect.gen(function* () { type: "thread.settle", commandId: input.commandId, threadId: input.threadId, + actor: input.actor, }); return { sequence: result.sequence }; }); diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index d86583515ddad..554cad09c3d44 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -9,6 +9,7 @@ import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import { CommandId, isDelegatedAppThread, + founderInboxHolder, isStandingThreadRoot, isOrchestrationV2WorkActive, type ThreadId, @@ -202,17 +203,13 @@ export function settlesFinishedAgentWork( return !agentBackgroundWorkPending(thread); } -const HUMAN_INBOX_AUDIENCES = new Set(["kameron", "jeff", "shared"]); - export function isAutoSettlementCandidate( thread: Omit, nowMs: number, ): boolean { if (thread.archivedAt !== null || thread.settledOverride !== null) return false; if (thread.pinnedAt != null || thread.autoSettleDisabledAt != null) return false; - if (thread.inbox?.audience !== undefined && HUMAN_INBOX_AUDIENCES.has(thread.inbox.audience)) { - return false; - } + if (founderInboxHolder(thread.inbox) !== null) return false; if (thread.inbox?.audience === "agent-only" && thread.status === "failed") return false; if (isStandingThreadRoot(thread)) return false; if (thread.pendingRuntimeRequest !== null) return false; diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 1484008ecbe2f..6eb35e9357ecb 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -30,6 +30,7 @@ import { CommandId, ContextTransferId, EnvironmentId, + AuthSessionId, EventId, IssueTrackerKind, MessageId, @@ -3909,6 +3910,12 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { standing: null, }); assert.isUndefined(shellOf(yield* orchestrator.getShellSnapshot()).standing ?? undefined); + yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("runtime-layer-lifecycle-to-agents"), + threadId, + inboxRouting: { owner: null, assignee: null, audience: "agent-only" }, + }); const preAutoProjection = yield* orchestrator.getThreadProjection(threadId); const staleAutoSettle = yield* orchestrator @@ -9372,6 +9379,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { threadId, commandId: CommandId.make("runtime-layer-settle-after-run-settle"), byOwnAgent: true, + actor: { kind: "agent", agentThreadId: threadId }, }); assert.deepEqual(result, { settlesWhenTurnEnds: true }); assert.isNull((yield* orchestrator.getThreadProjection(threadId)).thread.settledOverride); @@ -9389,10 +9397,186 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }, ], }); - yield* Fiber.join(settled); + const settledEvent = yield* Fiber.join(settled); const projection = yield* orchestrator.getThreadProjection(threadId); assert.equal(projection.thread.settledOverride, "settled"); + assert.deepEqual(Option.getOrThrow(settledEvent).event.actor, { + kind: "agent", + agentThreadId: threadId, + }); + }), + ); + + const startFounderInboxRun = Effect.fn(function* (name: string) { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projectId = ProjectId.make(`runtime-layer-${name}-project`); + const threadId = ThreadId.make(`runtime-layer-${name}-thread`); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`runtime-layer-${name}-create`), + threadId, + projectId, + title: "Founder inbox settle", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: `/tmp/runtime-layer-${name}`, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`runtime-layer-${name}-message`), + threadId, + messageId: MessageId.make(`runtime-layer-${name}-message`), + text: "Work through this with me.", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + const fileForKameron = orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make(`runtime-layer-${name}-inbox`), + threadId, + inboxRouting: { audience: "kameron", reason: "conversation" }, + }); + const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]; + if (run === undefined) return yield* Effect.die(new Error("Run missing.")); + const completeRun = Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + yield* eventSink.write({ + commandId: CommandId.make(`runtime-layer-${name}-completed`), + events: [ + { + id: EventId.make(`runtime-layer-${name}-completed`), + type: "run.updated", + threadId, + runId: run.id, + occurredAt: now, + payload: { ...run, status: "completed", startedAt: now, completedAt: now }, + }, + ], + }); + }); + return { projectId, threadId, run, fileForKameron, completeRun }; + }); + + it.effect("refuses an agent settling its own thread in a founder's inbox", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadManagement = yield* ThreadManagementService.ThreadManagementService; + const { threadId, fileForKameron } = yield* startFounderInboxRun("founder-self-settle"); + yield* fileForKameron; + + const refused = yield* threadManagement + .settleThread({ + threadId, + commandId: CommandId.make("mcp:runtime-layer-founder-self-settle"), + byOwnAgent: true, + actor: { kind: "agent", agentThreadId: threadId }, + }) + .pipe(Effect.flip); + assert.equal(refused._tag, "OrchestratorDispatchError"); + assert.equal( + refused._tag === "OrchestratorDispatchError" ? refused.cause : undefined, + "Thread is in kameron's inbox; only the founder settles it.", + ); + assert.isNull((yield* orchestrator.getThreadProjection(threadId)).thread.settledOverride); + }), + ); + + it.effect("refuses an agent settling another thread in a founder's inbox", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadManagement = yield* ThreadManagementService.ThreadManagementService; + const { threadId, fileForKameron, completeRun } = + yield* startFounderInboxRun("founder-cross-settle"); + yield* fileForKameron; + yield* completeRun; + + const refused = yield* threadManagement + .settleThread({ + threadId, + commandId: CommandId.make("mcp:runtime-layer-founder-cross-settle"), + byOwnAgent: false, + actor: { kind: "agent", agentThreadId: ThreadId.make("some-other-agent-thread") }, + }) + .pipe(Effect.flip); + assert.equal(refused._tag, "OrchestratorDispatchError"); + assert.isNull((yield* orchestrator.getThreadProjection(threadId)).thread.settledOverride); + }), + ); + + it.effect("drops a settle-after-run once a founder's inbox holds the thread", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadManagement = yield* ThreadManagementService.ThreadManagementService; + const { projectId, threadId, run, fileForKameron, completeRun } = yield* startFounderInboxRun( + "founder-settle-after-run", + ); + + // Requested while the thread was still in Agents, then filed for Kameron mid-turn. + const deferred = yield* threadManagement + .settleAfterRun({ + projectId, + threadId, + runId: run.id, + actor: { kind: "agent", agentThreadId: threadId }, + }) + .pipe(Effect.forkChild); + yield* fileForKameron; + yield* completeRun; + yield* Fiber.join(deferred); + assert.isNull((yield* orchestrator.getThreadProjection(threadId)).thread.settledOverride); + + // The dispatch guard holds even when the deferred settle reaches it. + const refused = yield* orchestrator + .dispatch({ + type: "thread.settle", + commandId: CommandId.make(`server:settle-after-run:${run.id}:1`), + threadId, + expectedLatestRunId: run.id, + actor: { kind: "agent", agentThreadId: threadId }, + }) + .pipe(Effect.flip); + assert.equal(refused._tag, "OrchestratorDispatchError"); + assert.isNull((yield* orchestrator.getThreadProjection(threadId)).thread.settledOverride); + }), + ); + + it.effect("lets a founder's client settle a thread in their inbox and records who did", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const { threadId, fileForKameron, completeRun } = + yield* startFounderInboxRun("founder-ui-settle"); + yield* fileForKameron; + yield* completeRun; + const actor = { + kind: "founder", + founder: "kameron", + sessionId: AuthSessionId.make("runtime-layer-founder-ui-session"), + client: "Kameron's laptop", + } as const; + + yield* orchestrator.dispatch({ + type: "thread.settle", + commandId: CommandId.make("runtime-layer-founder-ui-settle"), + threadId, + actor, + }); + assert.equal( + (yield* orchestrator.getThreadProjection(threadId)).thread.settledOverride, + "settled", + ); + const stored = yield* orchestrator + .streamStoredEventsFrom({ threadId, afterSequence: 0, eventType: "thread.settled" }) + .pipe(Stream.runHead); + assert.deepEqual(Option.getOrThrow(stored).event.actor, actor); }), ); diff --git a/apps/server/src/persistence/OrchestrationEventStore.ts b/apps/server/src/persistence/OrchestrationEventStore.ts index 69b1b7be06322..11e5e9b785925 100644 --- a/apps/server/src/persistence/OrchestrationEventStore.ts +++ b/apps/server/src/persistence/OrchestrationEventStore.ts @@ -207,6 +207,7 @@ function metadataForV2Event(event: OrchestrationV2DomainEvent): Record => + command.type === "thread.settle" + ? messageSender.pipe( + Effect.map((sentBy) => ({ ...command, actor: settleActorOf(sentBy) })), + ) + : Effect.succeed(command); + const handlers = ServerWsRpcGroup.of({ [WS_METHODS.issuesList]: (input) => issues.list(input), [WS_METHODS.issuesDetail]: (input) => issues.detail(input), @@ -2224,6 +2235,7 @@ export const layerWsRpc = ( ).pipe( Effect.flatMap((sentBy) => fileUnderCreator(command).pipe( + Effect.flatMap(stampSettleActor), Effect.map((filed) => ({ filed, sentBy })), ), ), diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 6bf4ac46fa144..35182de25b9d4 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -193,6 +193,19 @@ export const OrchestrationV2MessageSentBy = Schema.Struct({ founder: Schema.NullOr(Founder), }); export type OrchestrationV2MessageSentBy = typeof OrchestrationV2MessageSentBy.Type; +/** + * Who issued a command, stamped by the server from the authenticated session or calling agent. + * A client never supplies it. Recorded on the event so a settle can be attributed later. + */ +export const OrchestrationV2CommandActor = Schema.Struct({ + kind: Schema.Literals(["founder", "agent", "server"]), + founder: Schema.optionalKey(Schema.NullOr(Founder)), + sessionId: Schema.optionalKey(AuthSessionId), + client: Schema.optionalKey(Schema.String), + /** The thread whose agent issued it. */ + agentThreadId: Schema.optionalKey(ThreadId), +}); +export type OrchestrationV2CommandActor = typeof OrchestrationV2CommandActor.Type; /** * The workflow run a thread is an agent step of, with the step's name. `environmentId` is where * the run lives, which is another environment for a step that runs through a link. @@ -2525,6 +2538,7 @@ const OrchestrationV2EventBase = Schema.Struct({ providerInstanceId: Schema.optional(ProviderInstanceId), rawEventId: Schema.optional(RawEventId), occurredAt: Schema.DateTimeUtc, + actor: Schema.optional(OrchestrationV2CommandActor), }); export const OrchestrationV2DomainEvent = Schema.Union([ @@ -3813,6 +3827,8 @@ export const OrchestrationV2Command = Schema.Union([ threadId: ThreadId, expectedLatestRunId: Schema.optional(RunId), settledAt: Schema.optional(Schema.DateTimeUtc), + /** Server-stamped; a client's value is replaced. A founder inbox refuses any but a founder. */ + actor: Schema.optional(OrchestrationV2CommandActor), }), /** Rejects changes since snapshotAt or any explicit settled override to preserve user actions. */ Schema.Struct({ diff --git a/packages/contracts/src/threadInbox.ts b/packages/contracts/src/threadInbox.ts index 69d3035140b42..52610135c5b32 100644 --- a/packages/contracts/src/threadInbox.ts +++ b/packages/contracts/src/threadInbox.ts @@ -94,6 +94,23 @@ export const ThreadInbox = Schema.Struct({ executorEnvironmentId: Schema.NullOr(EnvironmentId), }); export type ThreadInbox = typeof ThreadInbox.Type; +/** + * Whose inbox holds the thread: the founder it is filed for or assigned to, "shared", or null + * for Agents. Only a founder settles a thread a founder's inbox holds. + */ +export function founderInboxHolder( + inbox: Pick | null | undefined, +): Founder | "shared" | null { + if (inbox == null) return null; + if (inbox.audience !== "agent-only") return inbox.audience; + return inbox.assignee?.kind === "human" ? inbox.assignee.id : null; +} + +export function founderInboxSettleRefusal(holder: Founder | "shared"): string { + return holder === "shared" + ? "Thread is in the founders' shared inbox; only a founder settles it." + : `Thread is in ${holder}'s inbox; only the founder settles it.`; +} export const InboxView = Schema.Literals(["kameron", "jeff", "shared", "agents", "all"]); export type InboxView = typeof InboxView.Type; /** An inbox a thread can be filed into: every view except All. */ From eb003e804063333a8920b9d6baadb9d7d5c49e00 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:47:49 +0000 Subject: [PATCH 2/5] fix(server): settle as a founder only with positive evidence of a person An unknown or failed sender read, or an unassigned paired session, now settles as an agent; a person device needs an assigned founder or the desktop bootstrap session. Organize's description says founder-inbox threads refuse settle. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/auth/settleActor.test.ts | 45 ++++++++++++++++--- apps/server/src/auth/settleActor.ts | 15 ++++++- apps/server/src/mcp/toolkits/thread/tools.ts | 2 +- .../src/provider/agentContextBudget.json | 2 +- apps/server/src/ws.ts | 5 ++- 5 files changed, 57 insertions(+), 12 deletions(-) diff --git a/apps/server/src/auth/settleActor.test.ts b/apps/server/src/auth/settleActor.test.ts index af69e70635a23..b8598a5524f4e 100644 --- a/apps/server/src/auth/settleActor.test.ts +++ b/apps/server/src/auth/settleActor.test.ts @@ -6,17 +6,48 @@ import { settleActorOf } from "./settleActor.ts"; const sessionId = AuthSessionId.make("settle-actor-session"); describe("settleActorOf", () => { - it("names a person's client session as its founder", () => { + it("names a person's assigned client session as its founder", () => { expect( - settleActorOf({ sessionId, device: "Laptop", deviceType: "desktop", founder: "kameron" }), + settleActorOf( + { sessionId, device: "Laptop", deviceType: "desktop", founder: "kameron" }, + "paired-client", + ), ).toEqual({ kind: "founder", founder: "kameron", sessionId, client: "Laptop" }); }); + it("names the desktop app's own bootstrap session a founder before an owner is set", () => { + expect( + settleActorOf( + { sessionId, device: "", deviceType: "desktop", founder: null }, + "desktop-bootstrap", + ).kind, + ).toBe("founder"); + }); + it("names a bot's session as an agent, so a founder's inbox refuses its settle", () => { - expect(settleActorOf({ sessionId, device: "", deviceType: "bot", founder: null })).toEqual({ - kind: "agent", - founder: null, - sessionId, - }); + expect( + settleActorOf({ sessionId, device: "", deviceType: "bot", founder: null }, "bot"), + ).toEqual({ kind: "agent", founder: null, sessionId }); + }); + + it("names an unknown or failed sender read an agent", () => { + expect( + settleActorOf({ sessionId, device: "", deviceType: "unknown", founder: null }, "x").kind, + ).toBe("agent"); + expect( + settleActorOf( + { sessionId, device: "", deviceType: "unknown", founder: "kameron" }, + "desktop-bootstrap", + ).kind, + ).toBe("agent"); + }); + + it("names an unassigned paired browser session an agent", () => { + expect( + settleActorOf( + { sessionId, device: "Chrome", deviceType: "desktop", founder: null }, + "paired-client", + ).kind, + ).toBe("agent"); }); }); diff --git a/apps/server/src/auth/settleActor.ts b/apps/server/src/auth/settleActor.ts index 3fe9da49aed87..a9991088e8cfe 100644 --- a/apps/server/src/auth/settleActor.ts +++ b/apps/server/src/auth/settleActor.ts @@ -1,10 +1,21 @@ import type { OrchestrationV2CommandActor, OrchestrationV2MessageSentBy } from "@t3tools/contracts"; -/** A person's client session settles as a founder; a bot's session settles as an agent. */ +const PERSON_DEVICES = new Set(["desktop", "mobile", "tablet"]); + +/** + * Settles as a founder only with positive evidence of a person: a person's device type and either + * an assigned founder or the desktop app's own bootstrap session. Anything else, an unknown or + * failed sender read included, settles as an agent, so a founder's inbox refuses it. + */ export const settleActorOf = ( sentBy: OrchestrationV2MessageSentBy, + sessionSubject: string, ): OrchestrationV2CommandActor => ({ - kind: sentBy.deviceType === "bot" ? "agent" : "founder", + kind: + PERSON_DEVICES.has(sentBy.deviceType) && + (sentBy.founder !== null || sessionSubject === "desktop-bootstrap") + ? "founder" + : "agent", founder: sentBy.founder, sessionId: sentBy.sessionId, ...(sentBy.device === "" ? {} : { client: sentBy.device }), diff --git a/apps/server/src/mcp/toolkits/thread/tools.ts b/apps/server/src/mcp/toolkits/thread/tools.ts index b71a922a95a8a..b0117b7df562d 100644 --- a/apps/server/src/mcp/toolkits/thread/tools.ts +++ b/apps/server/src/mcp/toolkits/thread/tools.ts @@ -33,7 +33,7 @@ import * as McpInvocationContext from "../../McpInvocationContext.ts"; const ThreadOrganizeTool = Tool.make("t3_thread_organize", { description: - "Organize this thread by default. `snooze` needs `snoozedUntil`. Self-settle waits for turn end; failure or a queued message keeps it active.", + "Organize this thread by default. `snooze` needs `snoozedUntil`. Self-settle waits for turn end; failure or a queued message keeps it active. A thread in a founder or Shared inbox refuses settle: leave it for the founder.", parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, threadId: Schema.optional(ThreadId), diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 67009a34b2a2d..55904a6258432 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 75656 + "mcpToolListJsonBytes": 75736 } diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index d30b750254870..40a70f260fcc7 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2174,7 +2174,10 @@ export const layerWsRpc = ( ): Effect.Effect => command.type === "thread.settle" ? messageSender.pipe( - Effect.map((sentBy) => ({ ...command, actor: settleActorOf(sentBy) })), + Effect.map((sentBy) => ({ + ...command, + actor: settleActorOf(sentBy, currentSession.subject), + })), ) : Effect.succeed(command); From ea71c9bdafbfa5ad8a5aa0a317810c2c8af726c4 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:11:12 +0000 Subject: [PATCH 3/5] fix(server): require settle enrolment only under requireFounderIdentity Founders' paired desktop apps on hosts without founder enrolment (R720 today) were refused. A person device settles as a founder unless the server requires founder identity, the same rule messages follow; an unknown or failed sender read stays an agent. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/auth/settleActor.test.ts | 26 +++++++++++++++--------- apps/server/src/auth/settleActor.ts | 9 ++++---- apps/server/src/ws.ts | 16 ++++++++++----- 3 files changed, 32 insertions(+), 19 deletions(-) diff --git a/apps/server/src/auth/settleActor.test.ts b/apps/server/src/auth/settleActor.test.ts index b8598a5524f4e..250cba96ae064 100644 --- a/apps/server/src/auth/settleActor.test.ts +++ b/apps/server/src/auth/settleActor.test.ts @@ -4,13 +4,20 @@ import { describe, expect, it } from "@effect/vitest"; import { settleActorOf } from "./settleActor.ts"; const sessionId = AuthSessionId.make("settle-actor-session"); +const pairedBrowser = { + sessionId, + device: "Chrome", + deviceType: "desktop", + founder: null, +} as const; describe("settleActorOf", () => { it("names a person's assigned client session as its founder", () => { expect( settleActorOf( { sessionId, device: "Laptop", deviceType: "desktop", founder: "kameron" }, - "paired-client", + "one-time-token", + true, ), ).toEqual({ kind: "founder", founder: "kameron", sessionId, client: "Laptop" }); }); @@ -20,34 +27,33 @@ describe("settleActorOf", () => { settleActorOf( { sessionId, device: "", deviceType: "desktop", founder: null }, "desktop-bootstrap", + true, ).kind, ).toBe("founder"); }); it("names a bot's session as an agent, so a founder's inbox refuses its settle", () => { expect( - settleActorOf({ sessionId, device: "", deviceType: "bot", founder: null }, "bot"), + settleActorOf({ sessionId, device: "", deviceType: "bot", founder: null }, "bot", false), ).toEqual({ kind: "agent", founder: null, sessionId }); }); it("names an unknown or failed sender read an agent", () => { expect( - settleActorOf({ sessionId, device: "", deviceType: "unknown", founder: null }, "x").kind, + settleActorOf({ sessionId, device: "", deviceType: "unknown", founder: null }, "x", false) + .kind, ).toBe("agent"); expect( settleActorOf( { sessionId, device: "", deviceType: "unknown", founder: "kameron" }, "desktop-bootstrap", + false, ).kind, ).toBe("agent"); }); - it("names an unassigned paired browser session an agent", () => { - expect( - settleActorOf( - { sessionId, device: "Chrome", deviceType: "desktop", founder: null }, - "paired-client", - ).kind, - ).toBe("agent"); + it("names an unassigned paired person session a founder unless founder identity is required", () => { + expect(settleActorOf(pairedBrowser, "one-time-token", false).kind).toBe("founder"); + expect(settleActorOf(pairedBrowser, "one-time-token", true).kind).toBe("agent"); }); }); diff --git a/apps/server/src/auth/settleActor.ts b/apps/server/src/auth/settleActor.ts index a9991088e8cfe..1a97a94eddd69 100644 --- a/apps/server/src/auth/settleActor.ts +++ b/apps/server/src/auth/settleActor.ts @@ -3,17 +3,18 @@ import type { OrchestrationV2CommandActor, OrchestrationV2MessageSentBy } from " const PERSON_DEVICES = new Set(["desktop", "mobile", "tablet"]); /** - * Settles as a founder only with positive evidence of a person: a person's device type and either - * an assigned founder or the desktop app's own bootstrap session. Anything else, an unknown or - * failed sender read included, settles as an agent, so a founder's inbox refuses it. + * Settles as a founder only from a person's device type; an unknown or failed sender read settles + * as an agent, so a founder's inbox refuses it. Under `requireFounderIdentity` the session must + * also be enrolled: an assigned founder or the desktop app's own bootstrap session. */ export const settleActorOf = ( sentBy: OrchestrationV2MessageSentBy, sessionSubject: string, + requireFounderIdentity: boolean, ): OrchestrationV2CommandActor => ({ kind: PERSON_DEVICES.has(sentBy.deviceType) && - (sentBy.founder !== null || sessionSubject === "desktop-bootstrap") + (!requireFounderIdentity || sentBy.founder !== null || sessionSubject === "desktop-bootstrap") ? "founder" : "agent", founder: sentBy.founder, diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 40a70f260fcc7..6de73765bb085 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2173,11 +2173,17 @@ export const layerWsRpc = ( command: OrchestrationV2Command, ): Effect.Effect => command.type === "thread.settle" - ? messageSender.pipe( - Effect.map((sentBy) => ({ - ...command, - actor: settleActorOf(sentBy, currentSession.subject), - })), + ? serverSettings.getSettings.pipe( + Effect.map((settings) => settings.requireFounderIdentity), + Effect.orElseSucceed(() => true), + Effect.flatMap((requireFounderIdentity) => + messageSender.pipe( + Effect.map((sentBy) => ({ + ...command, + actor: settleActorOf(sentBy, currentSession.subject, requireFounderIdentity), + })), + ), + ), ) : Effect.succeed(command); From b006d9de838ffb9499888859e963e50a0f73c02b Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:08:14 +0000 Subject: [PATCH 4/5] fix(server): block non-founder settle on open decisionRequest (review F-01..F-03) - Extend founderInboxHolder to treat an open decisionRequest (single-founder or unsigned joint sign-off) as held by that founder or shared (F-01). - In Orchestrator.ts thread.settle, read the projected shell inbox when a stored decisionRequest is present so answered single-founder asks don't linger (F-01). - Check input.actor?.kind !== 'founder' in settleAfterRun (F-02) and preserve standing-root error precedence in ThreadManagementService.settleThread (F-03). Model: gemini-4-neon Task: fix Agent: Antigravity (gemini-4-neon) Harness: t3/antigravity Model-family: Gemini Model-generation: 4 Neon Skills-SHA: unknown --- .../src/orchestration-v2/Orchestrator.ts | 7 +++++- .../ThreadManagementService.ts | 6 +++-- packages/contracts/src/threadInbox.ts | 25 ++++++++++++++++--- 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 067505187ece4..8e958e4c47a92 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -5625,7 +5625,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } // Every settle path reaches here, a deferred settle-after-run included, so it re-checks now. - const inboxHolder = founderInboxHolder(thread.inbox); + // Project decisionRequest through the shell when present so answered asks don't linger. + const projectedShell = + thread.inbox?.decisionRequest !== undefined + ? yield* projectionStore.getThreadShell(command.threadId).pipe(mapDispatchError(command)) + : null; + const inboxHolder = founderInboxHolder(projectedShell?.inbox ?? thread.inbox); if (inboxHolder !== null && command.actor?.kind !== "founder") { return yield* new OrchestratorDispatchError({ commandId: command.commandId, diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 95e8112a266b2..2d004ba645dc3 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1481,7 +1481,8 @@ const make = Effect.gen(function* () { ) return true; // A founder's inbox took the thread while the turn ran; the dispatch would refuse it. - if (founderInboxHolder(records.thread.inbox) !== null) return true; + if (founderInboxHolder(records.thread.inbox) !== null && input.actor?.kind !== "founder") + return true; const later = records.runs.filter((candidate) => candidate.ordinal > run.ordinal); const cancelledMessageIds = later .filter((candidate) => candidate.status === "cancelled") @@ -1575,7 +1576,8 @@ const make = Effect.gen(function* () { "orchestrationV2.threadManagement.settleThread", )(function* (input) { const shell = yield* orchestrator.getThreadShell(input.threadId); - const inboxHolder = founderInboxHolder(shell?.inbox); + const inboxHolder = + shell != null && isStandingThreadRoot(shell) ? null : founderInboxHolder(shell?.inbox); // Refuse before deferring, so an agent learns now instead of at a settle that never lands. if (inboxHolder !== null && input.actor.kind !== "founder") { return yield* new Orchestrator.OrchestratorDispatchError({ diff --git a/packages/contracts/src/threadInbox.ts b/packages/contracts/src/threadInbox.ts index 52610135c5b32..d30fb53548525 100644 --- a/packages/contracts/src/threadInbox.ts +++ b/packages/contracts/src/threadInbox.ts @@ -95,15 +95,32 @@ export const ThreadInbox = Schema.Struct({ }); export type ThreadInbox = typeof ThreadInbox.Type; /** - * Whose inbox holds the thread: the founder it is filed for or assigned to, "shared", or null - * for Agents. Only a founder settles a thread a founder's inbox holds. + * Whose inbox holds the thread: the founder it is filed for, assigned to, or waiting on via an + * open decision request, "shared", or null for Agents. Only a founder settles a thread a founder's + * inbox holds. */ export function founderInboxHolder( - inbox: Pick | null | undefined, + inbox: + | (Pick & { + readonly decisionRequest?: ThreadDecisionRequest | undefined; + }) + | null + | undefined, ): Founder | "shared" | null { if (inbox == null) return null; if (inbox.audience !== "agent-only") return inbox.audience; - return inbox.assignee?.kind === "human" ? inbox.assignee.id : null; + if (inbox.assignee?.kind === "human") return inbox.assignee.id; + if (inbox.decisionRequest !== undefined) { + const joint = jointSignOff(inbox.decisionRequest.signOff); + if (joint !== null) { + const unsigned = joint.filter((entry) => !entry.signed); + if (unsigned.length > 1) return "shared"; + if (unsigned.length === 1) return unsigned[0]!.founder; + } else { + return inbox.decisionRequest.founder; + } + } + return null; } export function founderInboxSettleRefusal(holder: Founder | "shared"): string { From cebc083e3d1e1ccf948464e27f890b7c3a3b4990 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:11:24 +0000 Subject: [PATCH 5/5] fix(server): project decisionRequest in settleAfterRun before aborting settleAfterRun read unprojected records.thread.inbox; for an answered single-founder decisionRequest, project through orchestrator.getThreadShell(input.threadId) so deferred settlement is not silently aborted after the founder already replied. Model: gemini-4-neon Task: fix Agent: Antigravity (gemini-4-neon) Harness: t3/antigravity Model-family: Gemini Model-generation: 4 Neon Skills-SHA: unknown --- .../src/orchestration-v2/ThreadManagementService.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 2d004ba645dc3..aa5473a9cbbe8 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1481,7 +1481,14 @@ const make = Effect.gen(function* () { ) return true; // A founder's inbox took the thread while the turn ran; the dispatch would refuse it. - if (founderInboxHolder(records.thread.inbox) !== null && input.actor?.kind !== "founder") + const projectedInbox = + records.thread.inbox?.decisionRequest !== undefined + ? (yield* orchestrator.getThreadShell(input.threadId))?.inbox + : undefined; + if ( + founderInboxHolder(projectedInbox ?? records.thread.inbox) !== null && + input.actor?.kind !== "founder" + ) return true; const later = records.runs.filter((candidate) => candidate.ordinal > run.ordinal); const cancelledMessageIds = later