diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index c68725151..a7d21312f 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -10041,6 +10041,186 @@ describe("ProviderCommandReactor", () => { ).toBe(false); }); + it("drops the old providerThreadId on handoff and rebinds a drifted projection when reusing a live runtime", async () => { + const harness = await createHarness(); + const now = "2026-01-01T00:00:00.000Z"; + + // Start with a Codex session carrying a Codex providerThreadId. + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make("cmd-session-codex-initial"), + threadId: ThreadId.make("thread-1"), + session: { + threadId: ThreadId.make("thread-1"), + status: "ready", + providerName: "codex", + providerInstanceId: ProviderInstanceId.make("codex"), + providerThreadId: "codex-native-thread-id", + runtimeMode: "approval-required", + activeTurnId: null, + lastError: null, + updatedAt: now, + }, + createdAt: now, + }), + ); + + // Hand off to Claude. The new session has no providerThreadId yet, so the + // old Codex providerThreadId must not leak onto the Claude slot. + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-turn-start-handoff-claude"), + threadId: ThreadId.make("thread-1"), + message: { + messageId: asMessageId("user-message-handoff-claude"), + role: "user", + text: "switch to claude", + attachments: [], + }, + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-opus-4-6", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: "2026-01-01T00:00:01.000Z", + }), + ); + await waitFor( + async () => + harness.sendTurn.mock.calls.length === 1 && + (await projectedSession(harness))?.status === "running", + ); + await harness.drain(); + + const afterHandoff = (await harness.readModel()).threads.find( + (entry) => entry.id === ThreadId.make("thread-1"), + ); + expect(afterHandoff?.session?.providerName).toBe("claudeAgent"); + expect(afterHandoff?.session?.providerInstanceId).toBe(ProviderInstanceId.make("claudeAgent")); + expect(afterHandoff?.session?.providerThreadId).toBeNull(); + + // Simulate a drifted projection (still naming codex) while the live + // runtime is claudeAgent. Sending another turn to claudeAgent must rebind + // the slot without restarting the session. + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make("cmd-session-drifted-codex"), + threadId: ThreadId.make("thread-1"), + session: { + threadId: ThreadId.make("thread-1"), + status: "ready", + providerName: "codex", + providerInstanceId: ProviderInstanceId.make("codex"), + providerThreadId: "codex-native-thread-id", + runtimeMode: "approval-required", + activeTurnId: null, + lastError: null, + updatedAt: "2026-01-01T00:00:02.000Z", + }, + createdAt: "2026-01-01T00:00:02.000Z", + }), + ); + + const startCountBeforeReuse = harness.startSession.mock.calls.length; + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-turn-start-reuse-rebind"), + threadId: ThreadId.make("thread-1"), + message: { + messageId: asMessageId("user-message-reuse-rebind"), + role: "user", + text: "follow up on claude", + attachments: [], + }, + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-opus-4-6", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: "2026-01-01T00:00:03.000Z", + }), + ); + await waitFor( + async () => + harness.sendTurn.mock.calls.length === 2 && + (await projectedSession(harness))?.status === "running", + ); + await harness.drain(); + + expect(harness.startSession.mock.calls.length).toBe(startCountBeforeReuse); + const afterReuse = (await harness.readModel()).threads.find( + (entry) => entry.id === ThreadId.make("thread-1"), + ); + expect(afterReuse?.session?.providerName).toBe("claudeAgent"); + expect(afterReuse?.session?.providerInstanceId).toBe(ProviderInstanceId.make("claudeAgent")); + expect(afterReuse?.session?.providerThreadId).toBeNull(); + expect(afterReuse?.session?.status).toBe("running"); + + // Rebinding a drifted `ready` session that still carries an activeTurnId + // (for example on a goal update) must heal the provider without clearing + // the active turn id or leaking the old providerThreadId. + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.meta.update", + commandId: CommandId.make("cmd-meta-select-claude"), + threadId: ThreadId.make("thread-1"), + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-opus-4-6", + }, + }), + ); + const liveTurnId = asTurnId("turn-in-flight-on-claude"); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make("cmd-session-drifted-ready-with-active-turn"), + threadId: ThreadId.make("thread-1"), + session: { + threadId: ThreadId.make("thread-1"), + status: "ready", + providerName: "codex", + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + providerThreadId: "codex-stale-thread-id", + runtimeMode: "approval-required", + activeTurnId: liveTurnId, + lastError: null, + updatedAt: "2026-01-01T00:00:04.000Z", + }, + createdAt: "2026-01-01T00:00:04.000Z", + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.goal.set", + commandId: CommandId.make("cmd-goal-set-triggers-rebind"), + threadId: ThreadId.make("thread-1"), + objective: "verify rebind keeps activeTurnId", + createdAt: "2026-01-01T00:00:05.000Z", + }), + ); + await waitFor(() => harness.setThreadGoal.mock.calls.length === 1); + await harness.drain(); + + expect(harness.startSession.mock.calls.length).toBe(startCountBeforeReuse); + const afterGoalRebind = (await harness.readModel()).threads.find( + (entry) => entry.id === ThreadId.make("thread-1"), + ); + expect(afterGoalRebind?.session?.providerName).toBe("claudeAgent"); + expect(afterGoalRebind?.session?.providerInstanceId).toBe( + ProviderInstanceId.make("claudeAgent"), + ); + expect(afterGoalRebind?.session?.providerThreadId).toBeNull(); + expect(afterGoalRebind?.session?.activeTurnId).toBe(liveTurnId); + }); + it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => { const harness = await createHarness(); const now = "2026-01-01T00:00:00.000Z"; diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index ada3aec45..ae11efcbe 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -1121,15 +1121,21 @@ const make = Effect.gen(function* () { readonly participantId: ThreadParticipantId | null; readonly providerInstanceId: ProviderInstanceId; readonly launch: SessionLaunch; + /** A cross-provider handoff on a ready thread (e.g. goal change) still needs the launch mark to block the outgoing provider's exit event. */ + readonly allowReadyHandoff?: boolean; }) => Effect.gen(function* () { if (input.launch.providerInstanceId === input.providerInstanceId) { return; } const session = (yield* resolveThread(input.threadId))?.session; + const canMarkReadyHandoff = + input.allowReadyHandoff === true && + session?.status === "ready" && + session.providerInstanceId !== input.providerInstanceId; if ( !session || - session.status !== "starting" || + (session.status !== "starting" && !canMarkReadyHandoff) || sessionSlotParticipantId(session) !== input.participantId ) { return; @@ -1826,6 +1832,7 @@ const make = Effect.gen(function* () { participantId, providerInstanceId: desiredInstanceId, launch, + allowReadyHandoff: startKind === "handoff", }).pipe( Effect.andThen( providerService.startSession(sessionKey, sessionStartInput(input)).pipe( @@ -1886,9 +1893,11 @@ const make = Effect.gen(function* () { // `adopting`: the session was started early, so the slot still describes // an older runtime, and a turn waiting on it must keep its "starting". + // `preserveActiveTurn`: rebinding a drifted projection to the live runtime + // must keep an already-running turn id intact. const bindSessionToThread = ( session: ProviderSession, - bindOptions?: { readonly adopting?: boolean }, + bindOptions?: { readonly adopting?: boolean; readonly preserveActiveTurn?: boolean }, ) => Effect.gen(function* () { if (session.providerInstanceId === undefined) { @@ -1916,40 +1925,55 @@ const make = Effect.gen(function* () { (options?.preservePendingTurnStartup === true || bindOptions?.adopting === true) && latestSession?.status === "starting" && mappedStatus === "ready"; + const shouldPreserveActiveTurn = + bindOptions?.preserveActiveTurn === true && + latestSession !== null && + latestSession.activeTurnId !== null && + latestSession.status !== "stopped" && + latestSession.status !== "interrupted"; + const shouldPreserveRunningStatus = + shouldPreserveActiveTurn && latestSession.status === "running"; // Provider-side identifiers can arrive through runtime ingestion or // directly on the started session. Prefer the durable projection, but // let the runtime heal an older missing value. Projected identifiers - // only survive while the same provider instance remains selected. + // only survive while the same provider instance and driver remain selected. const continuesSameInstance = - latestSession?.providerInstanceId === session.providerInstanceId; + latestSession?.providerInstanceId === session.providerInstanceId && + (latestSession.providerName === null || latestSession.providerName === session.provider); yield* setThreadSession({ threadId, session: { threadId, participantId, - status: shouldPreservePendingTurnStartup ? "starting" : mappedStatus, + status: shouldPreserveRunningStatus + ? "running" + : shouldPreservePendingTurnStartup + ? "starting" + : mappedStatus, providerName: session.provider, providerInstanceId: session.providerInstanceId, providerSessionId: continuesSameInstance ? (latestSession?.providerSessionId ?? null) : null, - providerThreadId: - continuesSameInstance && bindOptions?.adopting !== true - ? (latestSession?.providerThreadId ?? session.providerThreadId ?? null) - : (session.providerThreadId ?? latestSession?.providerThreadId ?? null), + providerThreadId: continuesSameInstance + ? bindOptions?.adopting === true + ? (session.providerThreadId ?? latestSession?.providerThreadId ?? null) + : (latestSession?.providerThreadId ?? session.providerThreadId ?? null) + : (session.providerThreadId ?? null), runtimeMode: desiredRuntimeMode, // Checkout the runtime actually started in. The next turn compares // it against the thread's target checkout to decide whether the // session has to be cycled into a different worktree. checkoutCwd: session.cwd ?? effectiveCwd ?? null, // Provider turn ids are not orchestration turn ids. - activeTurnId: null, + activeTurnId: shouldPreserveActiveTurn ? latestSession.activeTurnId : null, // The program has started: the launch, if this was one, is over. startup: null, lastError: session.lastError ?? null, - updatedAt: shouldPreservePendingTurnStartup - ? (latestSession?.updatedAt ?? session.updatedAt) - : session.updatedAt, + updatedAt: + shouldPreserveActiveTurn || shouldPreservePendingTurnStartup + ? (latestSession?.updatedAt ?? session.updatedAt) + : session.updatedAt, }, createdAt, }); @@ -2083,13 +2107,20 @@ const make = Effect.gen(function* () { // A handover blanks the slot's provider ids and checkout (the decider // can not know them); an agent resuming a runtime that is still alive - // restores them from it. Only right after a handover: at any other time - // the slot is current, and rebinding would clear a running turn. + // restores them from it. Also heal a slot whose projected provider + // drifted from the live runtime, so runtime ingestion does not drop the + // reused session's events as stale. const slotBlankedByHandover = projectedSession !== null && projectedSession.status === "starting" && (projectedSession.providerThreadId ?? null) === null && (projectedSession.checkoutCwd ?? null) === null; + const projectedSessionDisagreesWithRuntime = + activeSession !== undefined && + (thread.session === null || + (projectedSession !== null && + (projectedSession.providerName !== activeSession.provider || + projectedSession.providerInstanceId !== activeSession.providerInstanceId))); // An adopted early runtime is bound now, as a fresh start would have // been, with whatever its start owes the next turn. const rebindAfterHandover = @@ -2099,7 +2130,9 @@ const make = Effect.gen(function* () { ) : inRoom && activeSession !== undefined && slotBlankedByHandover ? bindSessionToThread(activeSession) - : Effect.void; + : projectedSessionDisagreesWithRuntime && activeSession !== undefined + ? bindSessionToThread(activeSession, { preserveActiveTurn: true }) + : Effect.void; // A runtime started before its thread became a room, or before invites // were turned on, or behind a fence that has lifted since, has no room diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 24a309f3d..b6e202751 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -2969,6 +2969,113 @@ describe("ProviderRuntimeIngestion", () => { expect(thread?.session?.updatedAt).toBe(reboundAt); }); + it("ignores outgoing provider session.exited while another provider instance is launching", async () => { + const harness = await createHarness(); + const launchingAt = "2026-01-01T00:00:03.000Z"; + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make("cmd-session-set-launching-handoff"), + threadId: ThreadId.make("thread-1"), + session: { + threadId: ThreadId.make("thread-1"), + status: "starting", + providerName: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + startup: { + phase: "launching", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + runtimeMode: "approval-required", + activeTurnId: null, + updatedAt: launchingAt, + lastError: null, + }, + createdAt: launchingAt, + }), + ); + + harness.emit({ + type: "session.exited", + eventId: asEventId("evt-outgoing-claude-exited-during-launch"), + provider: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + threadId: asThreadId("thread-1"), + createdAt: "2026-01-01T00:00:04.000Z", + payload: { + reason: "stale provider stopped during handoff", + exitKind: "graceful", + }, + }); + await harness.drain(); + + const thread = (await harness.readModel()).threads.find( + (entry) => entry.id === asThreadId("thread-1"), + ); + expect(thread?.session?.status).toBe("starting"); + expect(thread?.session?.startup).toEqual({ + phase: "launching", + providerInstanceId: ProviderInstanceId.make("codex"), + }); + expect(thread?.session?.updatedAt).toBe(launchingAt); + }); + + it("rejects stale guarded thread.session.set updates after the slot moved to another provider", async () => { + const harness = await createHarness(); + const reboundAt = "2026-01-01T00:00:03.000Z"; + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make("cmd-session-set-rebound-codex"), + threadId: ThreadId.make("thread-1"), + session: { + threadId: ThreadId.make("thread-1"), + status: "starting", + providerName: ProviderDriverKind.make("codex"), + providerInstanceId: ProviderInstanceId.make("codex"), + runtimeMode: "approval-required", + activeTurnId: null, + updatedAt: reboundAt, + lastError: null, + }, + createdAt: reboundAt, + }), + ); + + const exit = await Effect.runPromise( + Effect.exit( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make("cmd-stale-claude-session-set"), + threadId: ThreadId.make("thread-1"), + requireCurrentSession: true, + session: { + threadId: ThreadId.make("thread-1"), + participantId: null, + status: "stopped", + providerName: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + runtimeMode: "approval-required", + activeTurnId: null, + updatedAt: "2026-01-01T00:00:04.000Z", + lastError: null, + }, + createdAt: "2026-01-01T00:00:04.000Z", + }), + ), + ); + expect(exit._tag).toBe("Failure"); + + const thread = (await harness.readModel()).threads.find( + (entry) => entry.id === asThreadId("thread-1"), + ); + expect(thread?.session?.providerName).toBe("codex"); + expect(thread?.session?.providerInstanceId).toBe("codex"); + expect(thread?.session?.status).toBe("starting"); + }); + /** Sets the thread's session: the provider instance holding it now and its conversation. */ const holdThreadWith = ( harness: Awaited>, diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index f1265006d..102ea2430 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -6,6 +6,7 @@ import { SECRET_HIDDEN_WARNING_KIND, } from "../../secrets/secretScrubberCore.ts"; import { + type OrchestrationCommand, type OrchestrationSessionUsageLimit, CHECKPOINT_FILES_ACTIVITY_ID_PREFIX, type AssistantDeliveryMode, @@ -224,6 +225,15 @@ function runtimeEventMatchesThreadSession( if (!session || session.providerName === null) { return true; } + const launchingInstanceId = + session.startup?.phase === "launching" ? session.startup.providerInstanceId : undefined; + if ( + launchingInstanceId !== undefined && + event.providerInstanceId !== undefined && + !sameId(launchingInstanceId, event.providerInstanceId) + ) { + return false; + } if (session.providerInstanceId !== undefined && event.providerInstanceId !== undefined) { return sameId(session.providerInstanceId, event.providerInstanceId); } @@ -500,6 +510,9 @@ function sessionUpdateChangesNothing( if (key === "updatedAt") { return true; } + if (key === "participantId") { + return (current.participantId ?? null) === (value ?? null); + } const held: unknown = current[key as keyof OrchestrationSession]; return ( held === value || @@ -3067,6 +3080,31 @@ const make = Effect.gen(function* () { } }); + const dispatchRuntimeSessionSet = ( + command: Omit< + Extract, + "type" | "requireCurrentSession" + >, + ) => + orchestrationEngine + .dispatch({ + ...command, + type: "thread.session.set", + requireCurrentSession: true, + }) + .pipe( + Effect.as(true), + Effect.catchTag("OrchestrationCommandInvariantError", (error) => + Effect.logDebug("provider runtime ingestion skipped stale session update", { + commandId: command.commandId, + threadId: command.threadId, + providerName: command.session.providerName, + providerInstanceId: command.session.providerInstanceId, + detail: error.detail, + }).pipe(Effect.as(false)), + ), + ); + const processRuntimeEvent = (event: ProviderRuntimeEvent) => Effect.gen(function* () { // Realtime audio/item traffic is intentionally in-memory only. Keep this @@ -3714,6 +3752,7 @@ const make = Effect.gen(function* () { const session = { threadId: thread.id, + participantId: event.participantId ?? null, status, providerName: event.provider, ...(event.providerInstanceId !== undefined @@ -3747,8 +3786,7 @@ const make = Effect.gen(function* () { new Map(reports).set(thread.id, sessionUpdatedAt), ); } else { - yield* orchestrationEngine.dispatch({ - type: "thread.session.set", + const applied = yield* dispatchRuntimeSessionSet({ commandId: providerCommandId(event, "thread-session-set"), threadId: thread.id, session, @@ -3756,12 +3794,14 @@ const make = Effect.gen(function* () { ...turnStartFields(nextActiveTurnId), createdAt: now, }); - yield* Ref.update(unstoredSessionReportAt, (reports) => { - if (!reports.has(thread.id)) return reports; - const next = new Map(reports); - next.delete(thread.id); - return next; - }); + if (applied) { + yield* Ref.update(unstoredSessionReportAt, (reports) => { + if (!reports.has(thread.id)) return reports; + const next = new Map(reports); + next.delete(thread.id); + return next; + }); + } } } } @@ -3786,12 +3826,12 @@ const make = Effect.gen(function* () { thread.session.activeTurnId !== null && event.createdAt >= (yield* latestSessionReportAt(thread.session)) ) { - yield* orchestrationEngine.dispatch({ - type: "thread.session.set", + yield* dispatchRuntimeSessionSet({ commandId: providerCommandId(event, "thread-idle-session-set"), threadId: thread.id, session: { ...withoutLaunchMark(thread.session), + participantId: event.participantId ?? null, status: "ready", activeTurnId: null, lastError: null, @@ -3825,12 +3865,12 @@ const make = Effect.gen(function* () { nextAwaitedTasks.length !== thread.session.awaitedBackgroundTaskCount || !sameAwaitedBackgroundTasks(nextAwaitedTasks, thread.session.awaitedBackgroundTasks ?? []) ) { - yield* orchestrationEngine.dispatch({ - type: "thread.session.set", + yield* dispatchRuntimeSessionSet({ commandId: providerCommandId(event, "task-snapshot-session-set"), threadId: thread.id, session: { ...withoutLaunchMark(thread.session), + participantId: event.participantId ?? null, pendingBackgroundTaskCount: nextPendingCount, awaitedBackgroundTaskCount: nextAwaitedTasks.length, awaitedBackgroundTasks: nextAwaitedTasks, @@ -3866,12 +3906,12 @@ const make = Effect.gen(function* () { ? currentPendingCount + 1 : Math.max(0, currentPendingCount - 1); if (nextPendingCount !== currentPendingCount) { - yield* orchestrationEngine.dispatch({ - type: "thread.session.set", + yield* dispatchRuntimeSessionSet({ commandId: providerCommandId(event, "task-pending-session-set"), threadId: thread.id, session: { ...withoutLaunchMark(thread.session), + participantId: event.participantId ?? null, pendingBackgroundTaskCount: nextPendingCount, // Edges carry no intent, so every task is awaited, and no list: // with nothing describing them, the wait stays unspecific. @@ -4386,14 +4426,24 @@ const make = Effect.gen(function* () { detail: String(cause), }); const latest = (yield* resolveThreadShell(thread.id))?.session; - if (!latest || latest.status === "running" || latest.status === "starting") { + if ( + !latest || + latest.status === "running" || + latest.status === "starting" || + (event.participantId ?? null) !== sessionSlotParticipantId(latest) || + !runtimeEventMatchesThreadSession(event, latest) + ) { return; } - yield* orchestrationEngine.dispatch({ - type: "thread.session.set", + yield* dispatchRuntimeSessionSet({ commandId: providerCommandId(event, "turn-resend-refused"), threadId: thread.id, - session: { ...withoutLaunchMark(latest), lastError: error, updatedAt: now }, + session: { + ...withoutLaunchMark(latest), + participantId: event.participantId ?? null, + lastError: error, + updatedAt: now, + }, createdAt: now, }); }), @@ -4409,12 +4459,12 @@ const make = Effect.gen(function* () { : activeTurnId === null || eventTurnId === undefined || sameId(activeTurnId, eventTurnId); if (shouldApplyRuntimeError) { - yield* orchestrationEngine.dispatch({ - type: "thread.session.set", + yield* dispatchRuntimeSessionSet({ commandId: providerCommandId(event, "runtime-error-session-set"), threadId: thread.id, session: { threadId: thread.id, + participantId: event.participantId ?? null, status: "error", providerName: event.provider, ...(event.providerInstanceId !== undefined diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index e29c0093e..0750bb614 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -711,6 +711,46 @@ function refuseSkippedSetup( ); } +/** + * Checks whether a runtime-originated `thread.session.set` still belongs to + * the thread's current session slot. Rejects stale lifecycle events after a + * provider handoff, during an in-flight launch of another provider, or after a + * room handover. + */ +function runtimeSessionUpdateMatchesSlot( + current: OrchestrationSession | null, + incoming: OrchestrationSession, +): boolean { + if (current === null) { + return true; + } + if ( + incoming.participantId !== undefined && + (current.participantId ?? null) !== (incoming.participantId ?? null) + ) { + return false; + } + const launchingInstanceId = + current.startup?.phase === "launching" ? current.startup.providerInstanceId : undefined; + if ( + launchingInstanceId !== undefined && + incoming.providerInstanceId !== undefined && + launchingInstanceId !== incoming.providerInstanceId + ) { + return false; + } + if (current.providerName === null) { + return true; + } + if (current.providerInstanceId !== undefined && incoming.providerInstanceId !== undefined) { + return current.providerInstanceId === incoming.providerInstanceId; + } + if (current.providerInstanceId !== undefined && incoming.providerInstanceId === undefined) { + return incoming.providerName === current.providerName; + } + return true; +} + /** * Stamps which failure a session update holds (`lastErrorAt`) and whether the * user closed its notice (`lastErrorDismissedAt`). A different error is a new @@ -5628,6 +5668,15 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" command, threadId: command.threadId, }); + if ( + command.requireCurrentSession === true && + !runtimeSessionUpdateMatchesSlot(thread.session, command.session) + ) { + return yield* new OrchestrationCommandInvariantError({ + commandType: command.type, + detail: "Thread session has already moved to another provider or participant.", + }); + } const project = yield* requireProject({ readModel, command, diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index dc307fff1..e7d2c457c 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -2411,6 +2411,167 @@ routing.layer("ProviderServiceLive routing", (it) => { }), ); + it.effect("listSessions does not die while a replacement provider start is in flight", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const threadId = asThreadId("thread-provider-replacement-in-flight"); + + yield* provider.startSession(threadId, { + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, + threadId, + cwd: "/tmp/project-provider-replacement-in-flight", + runtimeMode: "full-access", + }); + + const registered = yield* Deferred.make(); + const releaseStart = yield* Deferred.make(); + const startClaudeNormally = routing.claude.startSession.getMockImplementation()!; + routing.claude.startSession.mockImplementationOnce((input) => + Effect.gen(function* () { + const started = yield* startClaudeNormally(input); + yield* Deferred.succeed(registered, undefined); + yield* Deferred.await(releaseStart); + return started; + }), + ); + + const replacementFiber = yield* Effect.forkChild( + provider.startSession(threadId, { + provider: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: claudeAgentInstanceId, + threadId, + cwd: "/tmp/project-provider-replacement-in-flight", + runtimeMode: "full-access", + }), + ); + + yield* Deferred.await(registered); + const midHandoffSessions = yield* provider.listSessions(); + assert.deepEqual( + midHandoffSessions + .filter((session) => session.threadId === threadId) + .map((session) => session.provider), + ["codex"], + ); + + yield* Deferred.succeed(releaseStart, undefined); + yield* Fiber.join(replacementFiber); + + const finalSessions = yield* provider.listSessions(); + assert.deepEqual( + finalSessions + .filter((session) => session.threadId === threadId) + .map((session) => session.provider), + ["claudeAgent"], + ); + }), + ); + + it.effect( + "listSessions does not die when a replacement handoff finishes between adapter snapshot and binding read", + () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const threadId = asThreadId("thread-provider-replacement-completed-mid-list"); + + yield* provider.startSession(threadId, { + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, + threadId, + cwd: "/tmp/project-provider-replacement-completed-mid-list", + runtimeMode: "full-access", + }); + + const codexSnapshotted = yield* Deferred.make(); + const releaseListing = yield* Deferred.make(); + const listClaudeNormally = routing.claude.listSessions.getMockImplementation()!; + routing.claude.listSessions.mockImplementationOnce(() => + Effect.gen(function* () { + yield* Deferred.succeed(codexSnapshotted, undefined); + yield* Deferred.await(releaseListing); + return yield* listClaudeNormally(); + }), + ); + + const listFiber = yield* Effect.forkChild(provider.listSessions()); + yield* Deferred.await(codexSnapshotted); + + // Complete the full handoff to Claude (including clearing the in-flight marker) + // before `listSessions()` reads the persisted bindings. + yield* provider.startSession(threadId, { + provider: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: claudeAgentInstanceId, + threadId, + cwd: "/tmp/project-provider-replacement-completed-mid-list", + runtimeMode: "full-access", + }); + + yield* Deferred.succeed(releaseListing, undefined); + const sessions = yield* Fiber.join(listFiber); + assert.deepEqual( + sessions + .filter((session) => session.threadId === threadId) + .map((session) => session.provider), + ["claudeAgent"], + ); + }), + ); + + it.effect( + "listSessions still dies on unrelated binding corruption while another provider start is in flight", + () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const directory = yield* ProviderSessionDirectory; + const threadId = asThreadId("thread-unrelated-corruption-mid-start"); + + yield* provider.startSession(threadId, { + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, + threadId, + cwd: "/tmp/project-unrelated-corruption-mid-start", + runtimeMode: "full-access", + }); + // Corrupt the persisted binding to an unrelated provider (pi) while codex is live. + yield* directory.upsert({ + threadId, + provider: ProviderDriverKind.make("pi"), + providerInstanceId: ProviderInstanceId.make("pi"), + runtimeMode: "full-access", + }); + + const registered = yield* Deferred.make(); + const releaseStart = yield* Deferred.make(); + const startClaudeNormally = routing.claude.startSession.getMockImplementation()!; + routing.claude.startSession.mockImplementationOnce((input) => + Effect.gen(function* () { + const started = yield* startClaudeNormally(input); + yield* Deferred.succeed(registered, undefined); + yield* Deferred.await(releaseStart); + return started; + }), + ); + + const replacementFiber = yield* Effect.forkChild( + provider.startSession(threadId, { + provider: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: claudeAgentInstanceId, + threadId, + cwd: "/tmp/project-unrelated-corruption-mid-start", + runtimeMode: "full-access", + }), + ); + + yield* Deferred.await(registered); + const exit = yield* Effect.exit(provider.listSessions()); + assert.equal(Exit.hasDies(exit), true); + + yield* Deferred.succeed(releaseStart, undefined); + yield* Fiber.join(replacementFiber); + }), + ); + it.effect("recovers stale sessions for sendTurn using persisted cwd", () => Effect.gen(function* () { const provider = yield* ProviderService; diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index 426135b7d..38b972462 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -471,6 +471,33 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( }; /** Early sessions that finished starting, kept for whoever adopts them. */ const earlyStartedSessions = new Map(); + /** + * Sessions mid-handoff/start whose adapter may already list the new runtime + * before `stopStaleSessionsForThread` and `upsertSessionBinding` finish. + */ + const startingInstancesByThread = new Map< + ThreadId, + { + readonly fromInstanceId: ProviderInstanceId | undefined; + readonly toInstanceId: ProviderInstanceId; + } + >(); + /** + * Monotonic counter and last completed handoff per thread so a `listSessions` + * call that snapshotted adapters before a handoff finished can distinguish a + * stale outgoing runtime from genuine binding corruption. + */ + const handoffEpochByThread = new Map(); + const lastHandoffByThread = new Map< + ThreadId, + { + readonly fromInstanceId: ProviderInstanceId | undefined; + readonly toInstanceId: ProviderInstanceId; + } + >(); + const bumpHandoffEpoch = (threadId: ThreadId) => { + handoffEpochByThread.set(threadId, (handoffEpochByThread.get(threadId) ?? 0) + 1); + }; const awaitEarlyGate = (threadId: string): Effect.Effect => { const gate = earlyGates.get(threadId); return gate === undefined ? Effect.void : Deferred.await(gate); @@ -1166,76 +1193,97 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( // The cursor the adapter gets is the one decided above, never the // caller's as given: a forgotten conversation's must not get through. const { resumeCursor: _requestedCursor, ...startInput } = input; - const session = yield* adapter.startSession( - yield* withProjectInstructions({ - ...startInput, - providerInstanceId: resolvedInstanceId, - ...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}), - ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}), - // An early start reopens the conversation or fails: starting it fresh - // instead is left to the ordinary start, which tells the thread. - ...(early ? { resumePolicy: "required" as const } : {}), - }), - ); - - if (session.provider !== adapter.provider) { - return yield* toValidationError( - "ProviderService.startSession", - `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`, + const inFlightHandoff = { + fromInstanceId: persistedBinding?.providerInstanceId, + toInstanceId: resolvedInstanceId, + } as const; + const { sessionWithInstance, sessionStart } = yield* Effect.gen(function* () { + yield* Effect.sync(() => { + bumpHandoffEpoch(threadId); + startingInstancesByThread.set(threadId, inFlightHandoff); + }); + const session = yield* adapter.startSession( + yield* withProjectInstructions({ + ...startInput, + providerInstanceId: resolvedInstanceId, + ...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}), + ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}), + // An early start reopens the conversation or fails: starting it fresh + // instead is left to the ordinary start, which tells the thread. + ...(early ? { resumePolicy: "required" as const } : {}), + }), ); - } - const sessionStart = { - kind: classifyProviderSessionStart({ - hasPreviousBinding: persistedBinding !== undefined, - previousProvider: persistedBinding?.provider, - previousInstanceId: persistedBinding?.providerInstanceId, - nextProvider: resolvedProvider, - nextInstanceId: resolvedInstanceId, - hasContextSeed: input.contextSeed !== undefined, - hasResumeCursor: effectiveResumeCursor !== undefined, - }), - startMs: yield* millisSince(startBeganNanos), - }; - turnLatency.sessionStarted(threadId, { - beganAtMs: startBeganAtMs, - atMs: yield* Clock.currentTimeMillis, - instanceId: resolvedInstanceId, - timing: sessionStart, - }); - const sessionWithInstance = { - ...session, - providerInstanceId: resolvedInstanceId, - // It reopened the conversation its cursor named: the adapter took a - // cursor and didn't report that it couldn't (resumeFailed). - ...(effectiveResumeCursor !== undefined && - effectiveResumeCursor !== null && - session.resumeFailed !== true - ? { resumed: true } - : {}), - ...(owesHistorySeed ? { resumeFailed: true } : {}), - }; - yield* stopStaleSessionsForThread({ - threadId, - currentInstanceId: resolvedInstanceId, - }); - // A fresh early start's conversation exists only once something uses - // it; until then a later start must not try to resume it. - const fresh = - effectiveResumeCursor === undefined && - input.contextSeed === undefined && - input.forkFrom === undefined; - yield* upsertSessionBinding(sessionWithInstance, threadId, { - modelSelection: input.modelSelection, - earlyUnused: early && fresh, - // Owed until a send carries it: the forgotten conversation's, the - // seed this start handed over (an adapter may hold it until a send), - // or the history of a conversation the adapter couldn't reopen. - ...(historyOwed || input.contextSeed !== undefined || session.resumeFailed === true - ? { historyOwed: true } - : {}), - startedWith: { guideTools: input.guideTools === true }, - }); + if (session.provider !== adapter.provider) { + return yield* toValidationError( + "ProviderService.startSession", + `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`, + ); + } + const sessionStart = { + kind: classifyProviderSessionStart({ + hasPreviousBinding: persistedBinding !== undefined, + previousProvider: persistedBinding?.provider, + previousInstanceId: persistedBinding?.providerInstanceId, + nextProvider: resolvedProvider, + nextInstanceId: resolvedInstanceId, + hasContextSeed: input.contextSeed !== undefined, + hasResumeCursor: effectiveResumeCursor !== undefined, + }), + startMs: yield* millisSince(startBeganNanos), + }; + turnLatency.sessionStarted(threadId, { + beganAtMs: startBeganAtMs, + atMs: yield* Clock.currentTimeMillis, + instanceId: resolvedInstanceId, + timing: sessionStart, + }); + const sessionWithInstance = { + ...session, + providerInstanceId: resolvedInstanceId, + // It reopened the conversation its cursor named: the adapter took a + // cursor and didn't report that it couldn't (resumeFailed). + ...(effectiveResumeCursor !== undefined && + effectiveResumeCursor !== null && + session.resumeFailed !== true + ? { resumed: true } + : {}), + ...(owesHistorySeed ? { resumeFailed: true } : {}), + }; + + yield* stopStaleSessionsForThread({ + threadId, + currentInstanceId: resolvedInstanceId, + }); + // A fresh early start's conversation exists only once something uses + // it; until then a later start must not try to resume it. + const fresh = + effectiveResumeCursor === undefined && + input.contextSeed === undefined && + input.forkFrom === undefined; + yield* upsertSessionBinding(sessionWithInstance, threadId, { + modelSelection: input.modelSelection, + earlyUnused: early && fresh, + // Owed until a send carries it: the forgotten conversation's, the + // seed this start handed over (an adapter may hold it until a send), + // or the history of a conversation the adapter couldn't reopen. + ...(historyOwed || input.contextSeed !== undefined || session.resumeFailed === true + ? { historyOwed: true } + : {}), + startedWith: { guideTools: input.guideTools === true }, + }); + return { sessionWithInstance, sessionStart } as const; + }).pipe( + Effect.ensuring( + Effect.sync(() => { + if (startingInstancesByThread.get(threadId) === inFlightHandoff) { + startingInstancesByThread.delete(threadId); + lastHandoffByThread.set(threadId, inFlightHandoff); + bumpHandoffEpoch(threadId); + } + }), + ), + ); yield* analytics.record("provider.session.started", { ...analyticsAgentProperties({ provider: sessionWithInstance.provider, @@ -2868,6 +2916,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( const listSessions: ProviderServiceShape["listSessions"] = Effect.fn("listSessions")( function* () { + const handoffEpochBefore = new Map(handoffEpochByThread); const currentAdapters = yield* getAdapterEntries; const sessionsByProvider = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) => adapter.listSessions().pipe( @@ -2918,14 +2967,41 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( "ProviderService.listSessions", binding, ); - if (binding.provider !== session.provider) { - return yield* Effect.die( - new Error( - `ProviderService.listSessions: thread '${session.threadId}' is active on provider '${session.provider}' but persisted binding names provider '${binding.provider}'.`, - ), - ); - } - if (overrides.providerInstanceId !== session.providerInstanceId) { + if ( + binding.provider !== session.provider || + overrides.providerInstanceId !== session.providerInstanceId + ) { + // A replacement start registers the new runtime before stopping the + // outgoing session and updating the persisted binding. Omit only the + // mismatched half belonging to that transition (in flight, or + // completed between our adapter snapshot and binding read) so real + // out-of-band binding corruption still dies loudly. + const inFlight = startingInstancesByThread.get(session.threadId); + const matchesInFlightHandoff = + inFlight !== undefined && + ((session.providerInstanceId === inFlight.toInstanceId && + overrides.providerInstanceId === inFlight.fromInstanceId) || + (session.providerInstanceId === inFlight.fromInstanceId && + overrides.providerInstanceId === inFlight.toInstanceId)); + const completedDuringSnapshot = + handoffEpochByThread.get(session.threadId) !== handoffEpochBefore.get(session.threadId); + const lastHandoff = completedDuringSnapshot + ? lastHandoffByThread.get(session.threadId) + : undefined; + const matchesCompletedHandoff = + lastHandoff !== undefined && + session.providerInstanceId === lastHandoff.fromInstanceId && + overrides.providerInstanceId === lastHandoff.toInstanceId; + if (matchesInFlightHandoff || matchesCompletedHandoff) { + continue; + } + if (binding.provider !== session.provider) { + return yield* Effect.die( + new Error( + `ProviderService.listSessions: thread '${session.threadId}' is active on provider '${session.provider}' but persisted binding names provider '${binding.provider}'.`, + ), + ); + } return yield* Effect.die( new Error( `ProviderService.listSessions: thread '${session.threadId}' is active on provider instance '${session.providerInstanceId}' but persisted binding names '${overrides.providerInstanceId}'.`, diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index d999e49fb..d3684154b 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -2645,6 +2645,7 @@ export function makeAcpAdapter( cwd, model: boundModelSelection?.model, threadId: input.threadId, + providerThreadId: started.sessionId, resumeCursor: makeAcpResumeCursor( started.sessionId, history, diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 66e8837fb..936613afd 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -4838,6 +4838,13 @@ const ThreadSessionSetCommand = Schema.Struct({ continueAfterUsageLimits: Schema.optional(Schema.Boolean), /** See TurnStartedBy. */ turnStartedBy: Schema.optional(TurnStartedBy), + /** + * When true, this update is a runtime observation for a session that must + * still hold the thread's slot (same participant and provider instance, and + * not launching a different provider instance). If the slot has already moved + * on, the decider rejects the stale update instead of clobbering it. + */ + requireCurrentSession: Schema.optional(Schema.Boolean), createdAt: IsoDateTime, });