From 95f2c7d16aa6499012f5f07bc28780e04fbc176f Mon Sep 17 00:00:00 2001 From: Gilad Rubin Date: Tue, 17 Nov 2026 18:57:22 +0200 Subject: [PATCH] Keep a Claude agent's process and background work when its effort level changes (#10008) Changing the thinking level of a running Claude agent marked its query for a restart. The next turn, mode change or model change then retired the Claude process, which ended every background shell, workflow and subagent it ran with "connection lost". A move between two effort levels now goes to the running query through applyFlagSettings({ effortLevel }), as Fast mode already does, and marks no restart. Switching thinking off, to ultracode or back to the default still restarts, because those change how the query is launched. If the running process does not take the change, the old restart path runs, so the change is never lost. Row: app-built-from-one-set Paseo: c6210e21-fc13-4dfa-adfc-43a050c7d75a Co-authored-by: gilad-rubin <6134299+gilad-rubin@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../claude/agent.live-settings.test.ts | 5 +- .../claude/agent.runtime-exit.test.ts | 79 +++++++++++++++++++ .../server/agent/providers/claude/agent.ts | 26 +++++- 3 files changed, 107 insertions(+), 3 deletions(-) diff --git a/packages/server/src/server/agent/providers/claude/agent.live-settings.test.ts b/packages/server/src/server/agent/providers/claude/agent.live-settings.test.ts index cb272ebecb..5f90adba8b 100644 --- a/packages/server/src/server/agent/providers/claude/agent.live-settings.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.live-settings.test.ts @@ -123,7 +123,8 @@ test.each(["mode", "model", "commands"] as const)( try { await session.startTurn("Run the foreground command"); await running.promise; - expect(await session.setThinkingOption?.("medium")).toMatchObject({ + // Ultracode is launched with the query, so the change waits for a restart. + expect(await session.setThinkingOption?.("ultracode")).toMatchObject({ message: "Thinking level applies next turn", }); if (control === "mode") await session.setMode("acceptEdits"); @@ -149,7 +150,7 @@ test.each(["mode", "model", "commands"] as const)( await session.startTurn("Run another command with the new thinking level"); queries[1].work.resolve(); expect(await terminal.promise).toBe("turn_completed"); - expect(efforts).toEqual(["low", "medium"]); + expect(efforts).toEqual(["low", "xhigh"]); } finally { await session.close(); } diff --git a/packages/server/src/server/agent/providers/claude/agent.runtime-exit.test.ts b/packages/server/src/server/agent/providers/claude/agent.runtime-exit.test.ts index d70d068717..b700ff81ac 100644 --- a/packages/server/src/server/agent/providers/claude/agent.runtime-exit.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.runtime-exit.test.ts @@ -44,6 +44,7 @@ function createQueryMock(events: unknown[], options: QueryMockOptions = {}): Que close: vi.fn(() => undefined), setPermissionMode: vi.fn(async () => undefined), setModel: vi.fn(async () => undefined), + applyFlagSettings: vi.fn(async () => undefined), supportedModels: vi.fn(async () => [{ value: "opus", displayName: "Opus" }]), supportedCommands: vi.fn(async () => []), rewindFiles: vi.fn(async () => ({ canRewind: true })), @@ -382,6 +383,84 @@ describe("Claude runtime exit", () => { } }); + test("keeps the process and its background work when the effort level changes", async () => { + let capturedOptions: Options | undefined; + const child = createChildProcessStub(); + const query = createQueryMock(BACKGROUND_SHELL_TURN_EVENTS, { + tail: new Promise(() => undefined), + onReturn: () => child.emit("exit", 0, null), + }); + const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => { + capturedOptions = options; + return query; + }); + vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(child); + const client = new ClaudeAgentClient({ + logger: createTestLogger(), + queryFactory, + resolveBinary: async () => "/test/claude/bin", + }); + const session = await client.createSession({ + provider: "claude", + cwd: process.cwd(), + thinkingOptionId: "low", + }); + + try { + await session.run("start a background shell"); + capturedOptions?.spawnClaudeCodeProcess?.(SPAWN_OPTIONS); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + + await expect(session.setThinkingOption?.("high")).resolves.toBeUndefined(); + // A pending restart would be carried out here. + await session.listCommands(); + + expect(query.applyFlagSettings).toHaveBeenCalledWith({ effortLevel: "high" }); + expect(queryFactory).toHaveBeenCalledTimes(1); + expect(query.return).not.toHaveBeenCalled(); + expect(child.killSignals).toEqual([]); + expect(events).not.toContainEqual( + expect.objectContaining({ type: "background_work", provider: "claude", items: null }), + ); + } finally { + await session.close(); + } + }); + + test("restarts with the new effort level when the running process does not take it", async () => { + const efforts: Options["effort"][] = []; + const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => { + efforts.push(options.effort); + const query = createQueryMock(BACKGROUND_SHELL_TURN_EVENTS, { + tail: new Promise(() => undefined), + }); + vi.mocked(query.applyFlagSettings).mockRejectedValue(new Error("unsupported")); + return query; + }); + vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(createChildProcessStub()); + const client = new ClaudeAgentClient({ + logger: createTestLogger(), + queryFactory, + resolveBinary: async () => "/test/claude/bin", + }); + const session = await client.createSession({ + provider: "claude", + cwd: process.cwd(), + thinkingOptionId: "low", + }); + + try { + await session.run("start a background shell"); + await session.setThinkingOption?.("high"); + await session.listCommands(); + + expect(efforts).toEqual(["low", "high"]); + } finally { + await session.close(); + } + }); + test("ignores background work a retired query reports after its restart", async () => { let capturedOptions: Options | undefined; let deliverLateEvent: ((event: unknown) => void) | undefined; diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index 7bd696e7aa..1087e6dfe2 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -2859,6 +2859,7 @@ class ClaudeAgentSession implements AgentSession { ? thinkingOptionId : null; + const previousThinkingOptionId = this.config.thinkingOptionId; if (!normalizedThinkingOptionId || normalizedThinkingOptionId === "default") { this.config.thinkingOptionId = undefined; } else if (isClaudeThinkingOption(normalizedThinkingOptionId)) { @@ -2867,12 +2868,35 @@ class ClaudeAgentSession implements AgentSession { } else { throw new Error(`Unknown thinking option: ${normalizedThinkingOptionId}`); } - this.queryRestartNeeded = true; + if (!(await this.applyEffortToRunningQuery(previousThinkingOptionId))) { + this.queryRestartNeeded = true; + } if (this.activeForegroundTurnId || this.autonomousTurn) { return THINKING_APPLIES_NEXT_TURN_NOTICE; } } + // A move between two effort levels changes only the effort, which a running Claude process + // takes through flag settings, so the process and its background work stay. Switching thinking + // off, to ultracode or back to the default changes how the query is launched, so it still + // restarts the query. The recorded option feeds every later launch either way. + private async applyEffortToRunningQuery( + previousThinkingOptionId: string | undefined, + ): Promise { + const effort = this.config.thinkingOptionId; + if (!this.query || this.queryRestartNeeded) return false; + if (!isClaudeThinkingEffort(previousThinkingOptionId) || !isClaudeThinkingEffort(effort)) { + return false; + } + try { + await this.query.applyFlagSettings({ effortLevel: effort }); + return true; + } catch (error) { + this.logger.warn({ err: error, effort }, "Claude did not take a live effort change"); + return false; + } + } + async applyOptions(options: ProviderOptions): Promise { // Every option but Fast is read when the query is built, and replacing a started query would // end its background work, so once it exists only Fast can change.