Skip to content

Commit 64f067e

Browse files
committed
fix(server): keep deferred Claude options pending until restart
Do not cache a requested model selection when session replacement is deferred for live background work. The next turn can still restart to apply restart-only options such as fastMode.
1 parent 6b2b615 commit 64f067e

3 files changed

Lines changed: 205 additions & 28 deletions

File tree

‎apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,7 @@ describe("ProviderCommandReactor", () => {
166166
});
167167
});
168168

169+
/** Isolated ProviderCommandReactor harness with shared in-memory background-liveness state. */
169170
async function createHarness(input?: {
170171
readonly baseDir?: string;
171172
readonly initialTitle?: string;
@@ -3588,6 +3589,109 @@ describe("ProviderCommandReactor", () => {
35883589
});
35893590
});
35903591

3592+
it("restarts a claude session for deferred provider options after background work ends", async () => {
3593+
const harness = await createHarness({
3594+
threadModelSelection: {
3595+
instanceId: ProviderInstanceId.make("claudeAgent"),
3596+
model: "claude-sonnet-4-6",
3597+
},
3598+
});
3599+
const now = "2026-01-01T00:00:00.000Z";
3600+
const threadId = ThreadId.make("thread-1");
3601+
const fastModeSelection = createModelSelection(
3602+
ProviderInstanceId.make("claudeAgent"),
3603+
"claude-sonnet-4-6",
3604+
[{ id: "fastMode", value: true }],
3605+
);
3606+
3607+
await Effect.runPromise(
3608+
harness.engine.dispatch({
3609+
type: "thread.turn.start",
3610+
commandId: CommandId.make("cmd-turn-start-claude-deferred-fast-1"),
3611+
threadId,
3612+
message: {
3613+
messageId: asMessageId("user-message-claude-deferred-fast-1"),
3614+
role: "user",
3615+
text: "first claude turn",
3616+
attachments: [],
3617+
},
3618+
modelSelection: createModelSelection(
3619+
ProviderInstanceId.make("claudeAgent"),
3620+
"claude-sonnet-4-6",
3621+
),
3622+
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
3623+
runtimeMode: "approval-required",
3624+
createdAt: now,
3625+
}),
3626+
);
3627+
3628+
await waitFor(() => harness.startSession.mock.calls.length === 1);
3629+
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
3630+
3631+
harness.threadBackgroundLiveness.recordTaskLiveness({
3632+
threadId,
3633+
taskId: "task-live",
3634+
taskType: "local_agent",
3635+
status: "in_progress",
3636+
kind: "started",
3637+
});
3638+
3639+
await Effect.runPromise(
3640+
harness.engine.dispatch({
3641+
type: "thread.turn.start",
3642+
commandId: CommandId.make("cmd-turn-start-claude-deferred-fast-2"),
3643+
threadId,
3644+
message: {
3645+
messageId: asMessageId("user-message-claude-deferred-fast-2"),
3646+
role: "user",
3647+
text: "second claude turn",
3648+
attachments: [],
3649+
},
3650+
modelSelection: fastModeSelection,
3651+
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
3652+
runtimeMode: "approval-required",
3653+
createdAt: now,
3654+
}),
3655+
);
3656+
3657+
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
3658+
expect(harness.startSession.mock.calls.length).toBe(1);
3659+
expect(harness.stopSession.mock.calls.length).toBe(0);
3660+
3661+
harness.threadBackgroundLiveness.recordTaskLiveness({
3662+
threadId,
3663+
taskId: "task-live",
3664+
taskType: "local_agent",
3665+
status: "completed",
3666+
kind: "completed",
3667+
});
3668+
3669+
await Effect.runPromise(
3670+
harness.engine.dispatch({
3671+
type: "thread.turn.start",
3672+
commandId: CommandId.make("cmd-turn-start-claude-deferred-fast-3"),
3673+
threadId,
3674+
message: {
3675+
messageId: asMessageId("user-message-claude-deferred-fast-3"),
3676+
role: "user",
3677+
text: "third claude turn",
3678+
attachments: [],
3679+
},
3680+
modelSelection: fastModeSelection,
3681+
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
3682+
runtimeMode: "approval-required",
3683+
createdAt: now,
3684+
}),
3685+
);
3686+
3687+
await waitFor(() => harness.startSession.mock.calls.length === 2);
3688+
await waitFor(() => harness.sendTurn.mock.calls.length === 3);
3689+
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
3690+
resumeCursor: { opaque: "resume-1" },
3691+
modelSelection: fastModeSelection,
3692+
});
3693+
});
3694+
35913695
it("restarts the provider session when runtime mode is updated on the thread", async () => {
35923696
const harness = await createHarness();
35933697
const now = "2026-01-01T00:00:00.000Z";

‎apps/server/src/orchestration/Layers/ProviderCommandReactor.ts‎

Lines changed: 91 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,62 @@ export function providerErrorLabelFromInstanceHint(input: {
136136
);
137137
}
138138

139+
type ThreadBackgroundLivenessState = "working" | "monitoring" | null | undefined;
140+
141+
/** Reject a runtime-mode replacement while projected background work is still live. */
142+
function shouldRejectRuntimeModeReplacementWhileLive(input: {
143+
readonly activeRuntimeMode: RuntimeMode | undefined;
144+
readonly desiredRuntimeMode: RuntimeMode;
145+
readonly backgroundLiveness: ThreadBackgroundLivenessState;
146+
}): boolean {
147+
return (
148+
input.activeRuntimeMode !== undefined &&
149+
input.activeRuntimeMode !== input.desiredRuntimeMode &&
150+
input.backgroundLiveness != null
151+
);
152+
}
153+
154+
/** Reuse the live provider process instead of replacing it while background work is projected. */
155+
function shouldDeferProviderSessionRestartWhileLive(
156+
backgroundLiveness: ThreadBackgroundLivenessState,
157+
): boolean {
158+
return backgroundLiveness != null;
159+
}
160+
161+
/** Last model selection applied to the live session, or the thread selection on a cache miss. */
162+
function appliedThreadModelSelection(
163+
cache: Map<string, ModelSelection>,
164+
threadId: ThreadId,
165+
threadModelSelection: ModelSelection,
166+
): ModelSelection {
167+
return cache.get(threadId) ?? threadModelSelection;
168+
}
169+
170+
/** Cache a model selection only after the live provider session applied it. */
171+
function rememberAppliedThreadModelSelection(
172+
cache: Map<string, ModelSelection>,
173+
threadId: ThreadId,
174+
selection: ModelSelection | undefined,
175+
applied: boolean,
176+
): void {
177+
if (applied && selection !== undefined) {
178+
cache.set(threadId, selection);
179+
}
180+
}
181+
182+
/** Restart Claude when the requested ModelSelection, including restart-only options, changed. */
183+
function shouldRestartClaudeSessionForModelSelectionChange(input: {
184+
readonly preferredProvider: ProviderDriverKind;
185+
readonly requestedModelSelection: ModelSelection | undefined;
186+
readonly appliedModelSelection: ModelSelection;
187+
}): boolean {
188+
return (
189+
input.preferredProvider === "claudeAgent" &&
190+
input.requestedModelSelection !== undefined &&
191+
!Equal.equals(input.appliedModelSelection, input.requestedModelSelection)
192+
);
193+
}
194+
139195
function findProviderAdapterRequestError(
140196
cause: Cause.Cause<ProviderServiceError>,
141197
): ProviderAdapterRequestError | undefined {
@@ -640,16 +696,18 @@ const make = Effect.gen(function* () {
640696
}
641697
const preferredProvider: ProviderDriverKind = desiredDriverKind;
642698
if (
643-
activeThreadSession !== null &&
644-
thread.runtimeMode !== activeThreadSession.runtimeMode &&
645-
thread.backgroundLiveness != null
699+
shouldRejectRuntimeModeReplacementWhileLive({
700+
activeRuntimeMode: activeThreadSession?.runtimeMode,
701+
desiredRuntimeMode,
702+
backgroundLiveness: thread.backgroundLiveness,
703+
})
646704
) {
647705
yield* Effect.logWarning(
648706
"provider command reactor rejecting runtime-mode replacement while background work is live",
649707
{
650708
threadId,
651709
backgroundLiveness: thread.backgroundLiveness,
652-
currentRuntimeMode: activeThreadSession.runtimeMode,
710+
currentRuntimeMode: activeThreadSession?.runtimeMode,
653711
desiredRuntimeMode,
654712
},
655713
);
@@ -783,15 +841,17 @@ const make = Effect.gen(function* () {
783841
requestedModelSelection !== undefined &&
784842
activeSession?.providerInstanceId !== requestedModelSelection.instanceId;
785843
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "unsupported";
786-
const previousModelSelection = threadModelSelections.get(threadId) ?? thread.modelSelection;
787-
// Claude compares the full ModelSelection, including options. Cache
788-
// misses fall back to the thread's persisted selection so same-model
789-
// option changes still restart, without treating undefined vs
790-
// requested as a change.
844+
const previousModelSelection = appliedThreadModelSelection(
845+
threadModelSelections,
846+
threadId,
847+
thread.modelSelection,
848+
);
791849
const shouldRestartForModelSelectionChange =
792-
preferredProvider === "claudeAgent" &&
793-
requestedModelSelection !== undefined &&
794-
!Equal.equals(previousModelSelection, requestedModelSelection);
850+
shouldRestartClaudeSessionForModelSelectionChange({
851+
preferredProvider,
852+
requestedModelSelection,
853+
appliedModelSelection: previousModelSelection,
854+
});
795855

796856
if (
797857
!runtimeModeChanged &&
@@ -801,15 +861,13 @@ const make = Effect.gen(function* () {
801861
!shouldRestartForModelSelectionChange
802862
) {
803863
yield* refreshWorkspaceSnapshot;
804-
return existingSessionThreadId;
864+
return { threadId: existingSessionThreadId, appliedRequestedSelection: true };
805865
}
806866

807-
// Claude replacement drains liveTaskIds without session.exited. Reuse
808-
// the current process while projected background work is still live.
809867
// Runtime-mode changes are rejected above: sendTurn keeps the
810868
// startSession permission callback, so a stale bypassPermissions
811869
// session must not be treated as ready.
812-
if (thread.backgroundLiveness != null) {
870+
if (shouldDeferProviderSessionRestartWhileLive(thread.backgroundLiveness)) {
813871
yield* Effect.logWarning(
814872
"provider command reactor deferring provider session restart while background work is live",
815873
{
@@ -823,7 +881,7 @@ const make = Effect.gen(function* () {
823881
},
824882
);
825883
yield* refreshWorkspaceSnapshot;
826-
return existingSessionThreadId;
884+
return { threadId: existingSessionThreadId, appliedRequestedSelection: false };
827885
}
828886

829887
const resumeCursor = shouldRestartForModelChange
@@ -860,12 +918,12 @@ const make = Effect.gen(function* () {
860918
cwd: restartedSession.cwd,
861919
});
862920
yield* bindSessionToThread(restartedSession);
863-
return restartedSession.threadId;
921+
return { threadId: restartedSession.threadId, appliedRequestedSelection: true };
864922
}
865923

866924
const startedSession = yield* startProviderSession(undefined);
867925
yield* bindSessionToThread(startedSession);
868-
return startedSession.threadId;
926+
return { threadId: startedSession.threadId, appliedRequestedSelection: true };
869927
});
870928

871929
const buildSendTurnRequestForThread = Effect.fnUntraced(function* (input: {
@@ -882,13 +940,16 @@ const make = Effect.gen(function* () {
882940
new Error(`Thread '${input.threadId}' was not found in read model.`),
883941
);
884942
}
885-
yield* ensureSessionForThread(input.threadId, input.createdAt, {
943+
const ensuredSession = yield* ensureSessionForThread(input.threadId, input.createdAt, {
886944
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
887945
pendingTurnStart: true,
888946
});
889-
if (input.modelSelection !== undefined) {
890-
threadModelSelections.set(input.threadId, input.modelSelection);
891-
}
947+
rememberAppliedThreadModelSelection(
948+
threadModelSelections,
949+
input.threadId,
950+
input.modelSelection,
951+
ensuredSession.appliedRequestedSelection,
952+
);
892953
const normalizedInput = toNonEmptyProviderInput(input.messageText);
893954
const normalizedAttachments = input.attachments ?? [];
894955
const activeSession = yield* providerService
@@ -1476,17 +1537,20 @@ const make = Effect.gen(function* () {
14761537
() => void compactingThreadIds.delete(event.payload.threadId),
14771538
);
14781539
yield* Effect.gen(function* () {
1479-
yield* ensureSessionForThread(
1540+
const ensuredSession = yield* ensureSessionForThread(
14801541
event.payload.threadId,
14811542
event.payload.createdAt,
14821543
event.payload.modelSelection !== undefined
14831544
? { modelSelection: event.payload.modelSelection, pendingTurnStart: true }
14841545
: { pendingTurnStart: true },
14851546
);
14861547
compactionSessionEnsured = true;
1487-
if (event.payload.modelSelection !== undefined) {
1488-
threadModelSelections.set(event.payload.threadId, event.payload.modelSelection);
1489-
}
1548+
rememberAppliedThreadModelSelection(
1549+
threadModelSelections,
1550+
event.payload.threadId,
1551+
event.payload.modelSelection,
1552+
ensuredSession.appliedRequestedSelection,
1553+
);
14901554
yield* providerService.compactThread(
14911555
event.payload.threadId,
14921556
event.payload.modelSelection,

‎apps/server/src/provider/Layers/ClaudeAdapter.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2064,6 +2064,15 @@ function sdkNativeItemId(message: SDKMessage): string | undefined {
20642064
return undefined;
20652065
}
20662066

2067+
/** True when startSession would replace a live Claude query that still has running child tasks. */
2068+
function shouldBlockClaudeSessionReplacementForLiveTasks(existingContext: {
2069+
readonly stopped: boolean;
2070+
readonly liveTaskIds: ReadonlySet<string>;
2071+
}): boolean {
2072+
return !existingContext.stopped && existingContext.liveTaskIds.size > 0;
2073+
}
2074+
2075+
/** Create the Claude Agent provider adapter for query sessions and runtime events. */
20672076
export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
20682077
claudeSettings: ClaudeSettings,
20692078
options?: ClaudeAdapterLiveOptions,
@@ -4409,7 +4418,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
44094418
// process when child work is still running, but do not report the
44104419
// stale session as a successful start — callers would bind the
44114420
// requested runtime mode / model selection and send the turn.
4412-
if (!existingContext.stopped && existingContext.liveTaskIds.size > 0) {
4421+
if (shouldBlockClaudeSessionReplacementForLiveTasks(existingContext)) {
44134422
yield* emitRuntimeWarning(
44144423
existingContext,
44154424
`Claude session replacement blocked: ${existingContext.liveTaskIds.size} live task(s) are still running.`,

0 commit comments

Comments
 (0)