Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
180 changes: 180 additions & 0 deletions apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
65 changes: 49 additions & 16 deletions apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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,
});
Expand Down Expand Up @@ -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 =
Expand All @@ -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
Expand Down
Loading
Loading