Skip to content

Commit ce691bd

Browse files
committed
fix(server): keep live Claude tasks when replacing a session
Claude startSession replaced a live thread session without emitting session.exited, which silently stopped in-flight subagent tasks. Defer replacement while liveTaskIds is non-empty, skip Claude restarts on a model-selection cache miss, and reuse the session when projected background work is still live.
1 parent 7445aa7 commit ce691bd

4 files changed

Lines changed: 179 additions & 0 deletions

File tree

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

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3249,6 +3249,61 @@ describe("ProviderCommandReactor", () => {
32493249
});
32503250
});
32513251

3252+
it("does not restart a claude session when the model-selection cache has not been primed", async () => {
3253+
const harness = await createHarness({
3254+
threadModelSelection: {
3255+
instanceId: ProviderInstanceId.make("claudeAgent"),
3256+
model: "claude-sonnet-4-6",
3257+
},
3258+
});
3259+
const now = "2026-01-01T00:00:00.000Z";
3260+
3261+
await Effect.runPromise(
3262+
harness.engine.dispatch({
3263+
type: "thread.turn.start",
3264+
commandId: CommandId.make("cmd-turn-start-claude-cache-miss-1"),
3265+
threadId: ThreadId.make("thread-1"),
3266+
message: {
3267+
messageId: asMessageId("user-message-claude-cache-miss-1"),
3268+
role: "user",
3269+
text: "first claude turn",
3270+
attachments: [],
3271+
},
3272+
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
3273+
runtimeMode: "approval-required",
3274+
createdAt: now,
3275+
}),
3276+
);
3277+
3278+
await waitFor(() => harness.startSession.mock.calls.length === 1);
3279+
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
3280+
3281+
await Effect.runPromise(
3282+
harness.engine.dispatch({
3283+
type: "thread.turn.start",
3284+
commandId: CommandId.make("cmd-turn-start-claude-cache-miss-2"),
3285+
threadId: ThreadId.make("thread-1"),
3286+
message: {
3287+
messageId: asMessageId("user-message-claude-cache-miss-2"),
3288+
role: "user",
3289+
text: "second claude turn",
3290+
attachments: [],
3291+
},
3292+
modelSelection: createModelSelection(
3293+
ProviderInstanceId.make("claudeAgent"),
3294+
"claude-sonnet-4-6",
3295+
),
3296+
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
3297+
runtimeMode: "approval-required",
3298+
createdAt: now,
3299+
}),
3300+
);
3301+
3302+
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
3303+
expect(harness.startSession.mock.calls.length).toBe(1);
3304+
expect(harness.stopSession.mock.calls.length).toBe(0);
3305+
});
3306+
32523307
it("restarts the provider session when runtime mode is updated on the thread", async () => {
32533308
const harness = await createHarness();
32543309
const now = "2026-01-01T00:00:00.000Z";

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

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -764,9 +764,13 @@ const make = Effect.gen(function* () {
764764
activeSession?.providerInstanceId !== requestedModelSelection.instanceId;
765765
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "unsupported";
766766
const previousModelSelection = threadModelSelections.get(threadId);
767+
// Claude compares the full ModelSelection, including options. A cache
768+
// miss (undefined vs requested) must not restart: the SDK can continue
769+
// in-session, and startSession would otherwise replace a live process.
767770
const shouldRestartForModelSelectionChange =
768771
preferredProvider === "claudeAgent" &&
769772
requestedModelSelection !== undefined &&
773+
previousModelSelection !== undefined &&
770774
!Equal.equals(previousModelSelection, requestedModelSelection);
771775

772776
if (
@@ -780,6 +784,25 @@ const make = Effect.gen(function* () {
780784
return existingSessionThreadId;
781785
}
782786

787+
// Claude replacement drains liveTaskIds without session.exited. Reuse
788+
// the current process while projected background work is still live.
789+
if (thread.backgroundLiveness != null) {
790+
yield* Effect.logWarning(
791+
"provider command reactor deferring provider session restart while background work is live",
792+
{
793+
threadId,
794+
backgroundLiveness: thread.backgroundLiveness,
795+
runtimeModeChanged,
796+
cwdChanged,
797+
instanceChanged,
798+
shouldRestartForModelChange,
799+
shouldRestartForModelSelectionChange,
800+
},
801+
);
802+
yield* refreshWorkspaceSnapshot;
803+
return existingSessionThreadId;
804+
}
805+
783806
const resumeCursor = shouldRestartForModelChange
784807
? undefined
785808
: (activeSession?.resumeCursor ?? undefined);

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

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4186,6 +4186,92 @@ describe("ClaudeAdapterLive", () => {
41864186
);
41874187
});
41884188

4189+
it.effect("does not replace a session while live tasks are still running", () => {
4190+
const queries: FakeClaudeQuery[] = [];
4191+
const layer = Layer.effect(
4192+
ClaudeAdapter,
4193+
Effect.gen(function* () {
4194+
const claudeConfig = decodeClaudeSettings({});
4195+
return yield* makeClaudeAdapter(claudeConfig, {
4196+
createQuery: () => {
4197+
const query = new FakeClaudeQuery();
4198+
queries.push(query);
4199+
return query;
4200+
},
4201+
});
4202+
}),
4203+
).pipe(
4204+
Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")),
4205+
Layer.provideMerge(ServerSettingsService.layerTest()),
4206+
Layer.provideMerge(NodeServices.layer),
4207+
);
4208+
4209+
return Effect.gen(function* () {
4210+
const adapter = yield* ClaudeAdapter;
4211+
4212+
const taskStartedFiber = yield* adapter.streamEvents.pipe(
4213+
Stream.filter((event) => event.type === "task.started"),
4214+
Stream.take(1),
4215+
Stream.runCollect,
4216+
Effect.forkChild,
4217+
);
4218+
4219+
const firstSession = yield* adapter.startSession({
4220+
threadId: THREAD_ID,
4221+
provider: ProviderDriverKind.make("claudeAgent"),
4222+
runtimeMode: "full-access",
4223+
});
4224+
yield* adapter.sendTurn({
4225+
threadId: firstSession.threadId,
4226+
input: "spawn agents",
4227+
attachments: [],
4228+
});
4229+
4230+
queries[0]?.emit({
4231+
type: "system",
4232+
subtype: "task_started",
4233+
task_id: "task-live",
4234+
description: "Agent A",
4235+
task_type: "local_agent",
4236+
uuid: "task-live-uuid",
4237+
session_id: "sdk-session",
4238+
} as unknown as SDKMessage);
4239+
yield* Fiber.join(taskStartedFiber);
4240+
4241+
const warningFiber = yield* adapter.streamEvents.pipe(
4242+
Stream.filter((event) => event.type === "runtime.warning"),
4243+
Stream.take(1),
4244+
Stream.runCollect,
4245+
Effect.forkChild,
4246+
);
4247+
4248+
const secondSession = yield* adapter.startSession({
4249+
threadId: THREAD_ID,
4250+
provider: ProviderDriverKind.make("claudeAgent"),
4251+
runtimeMode: "full-access",
4252+
resumeCursor: firstSession.resumeCursor,
4253+
});
4254+
4255+
const warnings = Array.from(yield* Fiber.join(warningFiber));
4256+
const activeSessions = yield* adapter.listSessions();
4257+
4258+
assert.equal(queries.length, 1);
4259+
assert.equal(queries[0]?.closeCalls, 0);
4260+
assert.equal(yield* adapter.hasSession(THREAD_ID), true);
4261+
assert.equal(activeSessions.length, 1);
4262+
assert.equal(secondSession.threadId, firstSession.threadId);
4263+
assert.deepEqual(activeSessions[0]?.resumeCursor, secondSession.resumeCursor);
4264+
assert.equal(warnings.length, 1);
4265+
assert.equal(warnings[0]?.type, "runtime.warning");
4266+
if (warnings[0]?.type === "runtime.warning") {
4267+
assert.match(warnings[0].payload.message, /live task/);
4268+
}
4269+
}).pipe(
4270+
Effect.provideService(Random.Random, makeDeterministicRandomService()),
4271+
Effect.provide(layer),
4272+
);
4273+
});
4274+
41894275
it.effect("stopSession does not throw into the SDK prompt consumer", () => {
41904276
// The SDK consumes user messages via `for await (... of prompt)`.
41914277
// Stopping a session must end that loop cleanly — not throw an error.

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4404,6 +4404,21 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
44044404

44054405
const existingContext = sessions.get(input.threadId);
44064406
if (existingContext) {
4407+
// Replacement closes the query and records liveTaskIds as
4408+
// task.completed(stopped) without session.exited. Keep the live
4409+
// process when child work is still running; a later idle start can
4410+
// replace once the set is empty.
4411+
if (!existingContext.stopped && existingContext.liveTaskIds.size > 0) {
4412+
yield* emitRuntimeWarning(
4413+
existingContext,
4414+
`Claude session replacement deferred: ${existingContext.liveTaskIds.size} live task(s) are still running.`,
4415+
{
4416+
existingSessionStatus: existingContext.session.status,
4417+
liveTaskCount: existingContext.liveTaskIds.size,
4418+
},
4419+
);
4420+
return { ...existingContext.session };
4421+
}
44074422
yield* Effect.logWarning("claude.session.replacing", {
44084423
threadId: input.threadId,
44094424
existingSessionStatus: existingContext.session.status,

0 commit comments

Comments
 (0)