:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(agent): guard refreshSession's query swap like /clear's (#88769)
Phil Haacke25723b24450
diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.refresh.test.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.refresh.test.tsindex a85e6852379a..12aabdf02f2d 100644--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.refresh.test.ts+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.refresh.test.ts@@ -29,6 +29,18 @@ let nextInitPromise: Promise<InitResult> = Promise.resolve({models: [],});+/** Points nextInitPromise at a deferred the test settles once the refresh has+ * reached its init await (after `vi.waitFor` on createdQueries). */+function deferInit() {+ let resolve!: (result: InitResult) => void;+ let reject!: (error: Error) => void;+ nextInitPromise = new Promise<InitResult>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { resolve, reject };+}+function makeQueryHandle(): SdkQueryHandle {return {interrupt: vi.fn().mockResolvedValue(undefined),@@ -69,12 +81,31 @@ vi.mock("./mcp/tool-metadata", () => ({const { ClaudeAcpAgent } = await import("./claude-agent");type Agent = InstanceType<typeof ClaudeAcpAgent>;-function makeAgent(): Agent {- const client = {+interface ClientMocks {+ sessionUpdate: ReturnType<typeof vi.fn>;+ extNotification: ReturnType<typeof vi.fn>;+}++function makeAgent(): { agent: Agent; client: ClientMocks } {+ const client: ClientMocks = {sessionUpdate: vi.fn().mockResolvedValue(undefined),extNotification: vi.fn().mockResolvedValue(undefined),- } as unknown as AgentSideConnection;- return new ClaudeAcpAgent(client);+ };+ const agent = new ClaudeAcpAgent(client as unknown as AgentSideConnection);+ return { agent, client };+}++function findUpdate(+ client: ClientMocks,+ sessionUpdate: string,+): Record<string, unknown> | undefined {+ const match = client.sessionUpdate.mock.calls.find(+ ([call]) =>+ (call as { update?: { sessionUpdate?: string } }).update+ ?.sessionUpdate === sessionUpdate,+ );+ return (match?.[0] as { update: Record<string, unknown> } | undefined)+ ?.update;}function installFakeSession(@@ -145,6 +176,7 @@ function installFakeSession(return {session,oldQuery,+ input,endSpy,abortController,buildInProcessMcpServers,@@ -174,14 +206,14 @@ describe("ClaudeAcpAgent.extMethod refresh_session", () => {});it("returns methodNotFound for unknown extension methods", async () => {- const agent = makeAgent();+ const { agent } = makeAgent();await expect(agent.extMethod("_posthog/nope", {})).rejects.toThrow(/Method not found/i,);});it("rejects when payload has no refreshable fields", async () => {- const agent = makeAgent();+ const { agent } = makeAgent();installFakeSession(agent, "s-empty");await expect(@@ -190,7 +222,7 @@ describe("ClaudeAcpAgent.extMethod refresh_session", () => {});it("rejects when mcpServers is not an array", async () => {- const agent = makeAgent();+ const { agent } = makeAgent();installFakeSession(agent, "s-malformed");await expect(@@ -201,7 +233,7 @@ describe("ClaudeAcpAgent.extMethod refresh_session", () => {});it("rejects refresh while a prompt is in flight", async () => {- const agent = makeAgent();+ const { agent } = makeAgent();const { session } = installFakeSession(agent, "s-1");(session as unknown as { turnQueue: unknown[] }).turnQueue = [{ promptUuid: "u-1", settled: false },@@ -215,7 +247,7 @@ describe("ClaudeAcpAgent.extMethod refresh_session", () => {});it("rejects when session model does not support MCP injection", async () => {- const agent = makeAgent();+ const { agent } = makeAgent();installFakeSession(agent, "s-haiku", { modelId: "claude-haiku-4-5" });await expect(@@ -228,8 +260,8 @@ describe("ClaudeAcpAgent.extMethod refresh_session", () => {it("throws a RequestError and closes the timed-out query so it cannot leak", async () => {vi.useFakeTimers();try {- const agent = makeAgent();- installFakeSession(agent, "s-timeout");+ const { agent } = makeAgent();+ const { session } = installFakeSession(agent, "s-timeout");// Never resolves — withTimeout must win the race.nextInitPromise = new Promise<InitResult>(() => {});@@ -248,13 +280,242 @@ describe("ClaudeAcpAgent.extMethod refresh_session", () => {await expect(promise).rejects.toThrow(/Session refresh timed out after/);// The new query is closed so its CLI subprocess does not leak.expect(createdQueries[0]?.close).toHaveBeenCalledTimes(1);+ // The session is closed too, so a later prompt rejects SESSION_ENDED+ // instead of pushing into the retired input stream.+ expect((session as unknown as { queryClosed: boolean }).queryClosed).toBe(+ true,+ );} finally {vi.useRealTimers();}});+ it("refuses a second refresh while one is already in progress", async () => {+ // ACP handlers are not serialized, so a second refresh can arrive at any+ // await point of the first. Racing two swaps against the same session+ // would orphan a live SDK query; the second must be refused.+ const { agent } = makeAgent();+ installFakeSession(agent, "s-concurrent-refresh");+ const init = deferInit();++ const first = agent.extMethod(POSTHOG_METHODS.REFRESH_SESSION, {+ mcpServers: freshMcpServers,+ });+ // Let the first refresh reach its init await (one replacement query live).+ await vi.waitFor(() => expect(createdQueries).toHaveLength(1));++ await expect(+ agent.extMethod(POSTHOG_METHODS.REFRESH_SESSION, {+ mcpServers: freshMcpServers,+ }),+ ).rejects.toThrow(/query swap \(refresh or \/clear\) is in progress/);++ // The refused refresh started no second swap.+ expect(createdQueries).toHaveLength(1);++ init.resolve({ result: "success", commands: [], models: [] });+ await expect(first).resolves.toEqual({ refreshed: true });+ });++ it("ignores a cancel that arrives while a refresh is in progress", async () => {+ // cancel() → interrupt() targets session.query, which mid-refresh is the+ // half-initialized replacement; interrupting it would corrupt the swap.+ const { agent } = makeAgent();+ const { oldQuery } = installFakeSession(agent, "s-cancel-mid-refresh");+ const init = deferInit();++ const refreshPromise = agent.extMethod(POSTHOG_METHODS.REFRESH_SESSION, {+ mcpServers: freshMcpServers,+ });+ await vi.waitFor(() => expect(createdQueries).toHaveLength(1));++ await agent.cancel({ sessionId: "s-cancel-mid-refresh" });++ // Neither the retired query nor the booting replacement is interrupted:+ // the replacement's interrupt would corrupt the swap, and the retired+ // query already had its one interrupt from retireQuery (count frozen+ // here while the cancel could add another).+ expect(createdQueries[0].interrupt).not.toHaveBeenCalled();+ expect(oldQuery.interrupt).toHaveBeenCalledTimes(1);++ init.resolve({ result: "success", commands: [], models: [] });+ await expect(refreshPromise).resolves.toEqual({ refreshed: true });+ });++ it("holds a prompt that arrives mid-refresh and lands it on the fresh input stream", async () => {+ // A prompt racing the swap must wait for the refresh to settle instead of+ // pushing into the retired input stream, where it would be silently lost.+ // Watching every Pushable instance's push tells the streams apart without+ // touching Pushable's private queue.+ const { agent } = makeAgent();+ const { session, input: oldInput } = installFakeSession(+ agent,+ "s-prompt-mid-refresh",+ );+ const pushSpy = vi.spyOn(Pushable.prototype, "push");+ const init = deferInit();++ const refreshPromise = agent.extMethod(POSTHOG_METHODS.REFRESH_SESSION, {+ mcpServers: freshMcpServers,+ });+ await vi.waitFor(() => expect(createdQueries).toHaveLength(1));+ // Only the prompt's push is of interest; anything the swap itself pushed+ // would already have happened.+ pushSpy.mockClear();++ const promptPromise = agent.prompt({+ sessionId: "s-prompt-mid-refresh",+ prompt: [{ type: "text", text: "hello" }],+ });+ // The turn it queues never settles (the mocked query yields nothing);+ // swallow that so the test doesn't end on an unhandled rejection.+ promptPromise.catch(() => {});+ // Wait out a macrotask: the prompt's swap-gate await must NOT have run+ // its push yet.+ await new Promise((resolve) => setImmediate(resolve));+ expect(pushSpy).not.toHaveBeenCalled();++ init.resolve({ result: "success", commands: [], models: [] });+ await expect(refreshPromise).resolves.toEqual({ refreshed: true });++ await vi.waitFor(() => expect(pushSpy).toHaveBeenCalledTimes(1));+ // The released prompt pushed into the fresh stream, not the retired one.+ expect((session as unknown as { input: Pushable<unknown> }).input).not.toBe(+ oldInput,+ );+ expect(pushSpy.mock.instances[0]).toBe(+ (session as unknown as { input: Pushable<unknown> }).input,+ );+ pushSpy.mockRestore();+ });++ it("refuses a /clear that arrives while a refresh is in progress", async () => {+ const { agent, client } = makeAgent();+ installFakeSession(agent, "s-clear-mid-refresh");+ const init = deferInit();++ const refreshPromise = agent.extMethod(POSTHOG_METHODS.REFRESH_SESSION, {+ mcpServers: freshMcpServers,+ });+ await vi.waitFor(() => expect(createdQueries).toHaveLength(1));++ const result = await agent.prompt({+ sessionId: "s-clear-mid-refresh",+ prompt: [{ type: "text", text: "/clear" }],+ });++ expect(result.stopReason).toBe("end_turn");+ const chunk = findUpdate(client, "agent_message_chunk");+ expect((chunk?.content as { text?: string })?.text).toMatch(+ /already in progress/,+ );+ // The refused /clear started no second swap.+ expect(createdQueries).toHaveLength(1);++ init.resolve({ result: "success", commands: [], models: [] });+ await expect(refreshPromise).resolves.toEqual({ refreshed: true });+ });++ it("drops a prompt whose pre-prompt await runs long enough for a refresh to start under it", async () => {+ // The prompt path awaits ensureLocalToolsConnected (a real RPC) before it+ // enqueues a turn, and the swap entry points refuse only once turnQueue+ // has an entry. So a refresh started mid-await sees "no in-flight turns"+ // and proceeds; the prompt, on the other side of the await, finds the+ // input stream now retiring and must not push the turn into the queue,+ // or it would strand there unsettled.+ const { agent } = makeAgent();+ const { session, input: oldInput } = installFakeSession(+ agent,+ "s-prompt-start-then-refresh",+ );+ let resolveStatus!: (value: unknown) => void;+ const statusBlocked = new Promise<unknown>((resolve) => {+ resolveStatus = resolve;+ });+ // Block the pre-prompt local-tools status check so the refresh can start+ // (and reach its own init await) while the prompt is parked on the await.+ (+ session as unknown as { query: { mcpServerStatus: unknown } }+ ).query.mcpServerStatus = vi.fn().mockImplementation(() => statusBlocked);+ const pushSpy = vi.spyOn(Pushable.prototype, "push");+ const init = deferInit();++ // Fire the prompt first; it parks on the status await before enqueue.+ const promptPromise = agent.prompt({+ sessionId: "s-prompt-start-then-refresh",+ prompt: [{ type: "text", text: "hello" }],+ });+ // Wait out a macrotask so the prompt reaches the blocked status await.+ await new Promise((resolve) => setImmediate(resolve));++ // With the prompt not yet enqueued (turnQueue is still empty), start the+ // refresh and let it reach the init await of its own replacement query.+ const refreshPromise = agent.extMethod(POSTHOG_METHODS.REFRESH_SESSION, {+ mcpServers: freshMcpServers,+ });+ await vi.waitFor(() => expect(createdQueries).toHaveLength(1));++ // Unblock the prompt's status await. On the other side, querySwap is+ // still set, so the prompt must fail before turnQueue.push rather than+ // strand the turn in the queue behind a retiring input stream.+ resolveStatus([{ name: "posthog-code-tools", status: "connected" }]);+ await expect(promptPromise).rejects.toThrow(/session has ended/i);++ // The turn never reached the queue, so nothing was pushed to either+ // stream and the refresh is free to settle on the fresh query.+ expect((session as unknown as { turnQueue: unknown[] }).turnQueue).toEqual(+ [],+ );+ expect(pushSpy).not.toHaveBeenCalled();++ init.resolve({ result: "success", commands: [], models: [] });+ await expect(refreshPromise).resolves.toEqual({ refreshed: true });+ // Sanity: the swap really did replace the input stream the prompt was+ // about to write into. Without the guard the prompt's push would have+ // landed on the retired stream instead of failing.+ expect((session as unknown as { input: Pushable<unknown> }).input).not.toBe(+ oldInput,+ );+ pushSpy.mockRestore();+ });++ it("closes the session when the fresh session fails to initialize", async () => {+ // A non-timeout failure (SDK subprocess crash) must get the same+ // treatment as a timeout: terminate the unproven replacement and close+ // the session, so queryClosed gates every later prompt into SESSION_ENDED+ // instead of pushing into the retired input stream.+ const { agent } = makeAgent();+ const { session } = installFakeSession(agent, "s-init-crash");+ const init = deferInit();++ const refreshPromise = agent.extMethod(POSTHOG_METHODS.REFRESH_SESSION, {+ mcpServers: freshMcpServers,+ });+ const rejection = expect(refreshPromise).rejects.toThrow(+ /SDK subprocess crashed/,+ );+ await vi.waitFor(() => expect(createdQueries).toHaveLength(1));+ init.reject(new Error("SDK subprocess crashed"));+ await rejection;++ expect((session as unknown as { queryClosed: boolean }).queryClosed).toBe(+ true,+ );+ // The failed replacement query is torn down, not leaked.+ expect(createdQueries).toHaveLength(1);+ expect(createdQueries[0].close).toHaveBeenCalled();++ // A prompt after the failed swap gets a clean session-ended rejection.+ await expect(+ agent.prompt({+ sessionId: "s-init-crash",+ prompt: [{ type: "text", text: "hello" }],+ }),+ ).rejects.toThrow(/session has ended/);+ });+it("swaps query/input/options and preserves session state", async () => {- const agent = makeAgent();+ const { agent } = makeAgent();const { session, oldQuery, endSpy } = installFakeSession(agent, "s-2");const result = await agent.extMethod(POSTHOG_METHODS.REFRESH_SESSION, {@@ -304,7 +565,7 @@ describe("ClaudeAcpAgent.extMethod refresh_session", () => {});it("aborts the old controller and allocates a fresh one for the new query", async () => {- const agent = makeAgent();+ const { agent } = makeAgent();const { session, abortController: oldController } = installFakeSession(agent,"s-abort",@@ -329,7 +590,7 @@ describe("ClaudeAcpAgent.extMethod refresh_session", () => {});it("recovers when interrupting the old query throws Operation aborted", async () => {- const agent = makeAgent();+ const { agent } = makeAgent();const { session, oldQuery, endSpy } = installFakeSession(agent,"s-interrupt-throws",@@ -352,7 +613,7 @@ describe("ClaudeAcpAgent.extMethod refresh_session", () => {});it("re-fetches MCP tool metadata for the new query", async () => {- const agent = makeAgent();+ const { agent } = makeAgent();installFakeSession(agent, "s-metadata");await agent.extMethod(POSTHOG_METHODS.REFRESH_SESSION, {@@ -382,7 +643,7 @@ describe("ClaudeAcpAgent.extMethod refresh_session", () => {expected: "claude-sonnet-4-6",},])("$name", async ({ modelId, expected }) => {- const agent = makeAgent();+ const { agent } = makeAgent();installFakeSession(agent, "s-model", { modelId });await agent.extMethod(POSTHOG_METHODS.REFRESH_SESSION, {@@ -393,7 +654,7 @@ describe("ClaudeAcpAgent.extMethod refresh_session", () => {});it("rebuilds a FRESH in-process local-tools server across refresh", async () => {- const agent = makeAgent();+ const { agent } = makeAgent();const { session, buildInProcessMcpServers } = installFakeSession(agent,"s-inprocess",@@ -424,7 +685,7 @@ describe("ClaudeAcpAgent.extMethod refresh_session", () => {});it("clears the MCP tool metadata cache on refresh", async () => {- const agent = makeAgent();+ const { agent } = makeAgent();installFakeSession(agent, "s-cache");await agent.extMethod(POSTHOG_METHODS.REFRESH_SESSION, {@@ -452,7 +713,7 @@ describe("ClaudeAcpAgent self-heal: ensureLocalToolsConnected", () => {}it("is a no-op when the signed-commit server is connected", async () => {- const agent = makeAgent();+ const { agent } = makeAgent();const { oldQuery } = installFakeSession(agent, "s-healthy");oldQuery.mcpServerStatus.mockResolvedValue([{ name: "posthog-code-tools", status: "connected" },@@ -463,7 +724,7 @@ describe("ClaudeAcpAgent self-heal: ensureLocalToolsConnected", () => {});it("rebuilds and reconnects a fresh server when disconnected", async () => {- const agent = makeAgent();+ const { agent } = makeAgent();const { session, oldQuery, buildInProcessMcpServers } = installFakeSession(agent,"s-down",@@ -491,7 +752,7 @@ describe("ClaudeAcpAgent self-heal: ensureLocalToolsConnected", () => {});it("passes every external server through when reconnecting", async () => {- const agent = makeAgent();+ const { agent } = makeAgent();const { session, oldQuery } = installFakeSession(agent, "s-multi");(session as unknown as {@@ -525,7 +786,7 @@ describe("ClaudeAcpAgent self-heal: ensureLocalToolsConnected", () => {});it("treats a server missing from status as disconnected", async () => {- const agent = makeAgent();+ const { agent } = makeAgent();const { oldQuery } = installFakeSession(agent, "s-missing");oldQuery.mcpServerStatus.mockResolvedValue([{ name: "some-other", status: "connected" },@@ -536,7 +797,7 @@ describe("ClaudeAcpAgent self-heal: ensureLocalToolsConnected", () => {});it("does not block the turn when the status RPC fails", async () => {- const agent = makeAgent();+ const { agent } = makeAgent();const { oldQuery } = installFakeSession(agent, "s-statuserr");oldQuery.mcpServerStatus.mockRejectedValue(new Error("rpc down"));@@ -547,7 +808,7 @@ describe("ClaudeAcpAgent self-heal: ensureLocalToolsConnected", () => {it("does not block the turn when the status RPC hangs", async () => {vi.useFakeTimers();try {- const agent = makeAgent();+ const { agent } = makeAgent();const { oldQuery } = installFakeSession(agent, "s-statushang");oldQuery.mcpServerStatus.mockReturnValue(new Promise(() => {}));@@ -562,7 +823,7 @@ describe("ClaudeAcpAgent self-heal: ensureLocalToolsConnected", () => {});it("returns false when reconnect fails", async () => {- const agent = makeAgent();+ const { agent } = makeAgent();const { oldQuery } = installFakeSession(agent, "s-reconnect-fail");oldQuery.mcpServerStatus.mockResolvedValue(DISCONNECTED_STATUS);oldQuery.setMcpServers.mockRejectedValue(new Error("connect boom"));@@ -571,7 +832,7 @@ describe("ClaudeAcpAgent self-heal: ensureLocalToolsConnected", () => {});it("is a no-op when no in-process server is enabled", async () => {- const agent = makeAgent();+ const { agent } = makeAgent();const { session, oldQuery } = installFakeSession(agent, "s-none");(session as unknown as { localToolsServerNames: string[] }diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.tsindex 63ddda7f8faa..605718dc3e04 100644--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts@@ -575,11 +575,14 @@ export class ClaudeAcpAgent extends BaseAcpAgent {userMessage.uuid = promptUuid;const isLocalOnlyCommand = !!command && LOCAL_ONLY_COMMANDS.has(command);- if (this.session.clearing) {- // A /clear is swapping the SDK query underneath. Wait for it to settle- // so this prompt lands on the fresh input stream, not the retired one- // (a failed clear sets queryClosed, which the check below rejects).- await this.session.clearing;+ if (this.session.querySwap) {+ // A /clear or refreshSession is swapping the SDK query underneath. Wait+ // for it to settle so this prompt lands on the fresh input stream, not+ // the retired one (a failed swap sets queryClosed, which the check+ // below rejects). Not the last gate: the awaits before enqueue (slash+ // commands, pre-prompt local-tools) leave this prompt off turnQueue, so+ // a swap can still start there and must be re-checked before enqueue.+ await this.session.querySwap;}if (command && !isLocalOnlyCommand) {@@ -653,6 +656,18 @@ export class ClaudeAcpAgent extends BaseAcpAgent {turn.reject = reject;});+ if (this.session.querySwap) {+ // A swap started during this method's pre-enqueue awaits (the prompt is+ // not yet on turnQueue, so the entry-point refusals don't see it); fail+ // before enqueue rather than push the turn into a retiring stream.+ turn.reject(RequestError.internalError(undefined, SESSION_ENDED_MESSAGE));+ return response;+ }+ if (this.session.queryClosed) {+ turn.reject(RequestError.internalError(undefined, SESSION_ENDED_MESSAGE));+ return response;+ }+this.session.turnQueue.push(turn);this.dispatchQueuedInput(this.session);this.ensureConsumer(params.sessionId);@@ -1596,12 +1611,13 @@ export class ClaudeAcpAgent extends BaseAcpAgent {if (session.queryClosed) {return;}- if (session.clearing) {- // A /clear is swapping the SDK query: there is no turn to cancel, and- // interrupting the half-initialized replacement would corrupt the swap.- // A wedged clear self-limits: retireQuery's interrupt() and the new- // query's init are both time-bounded (see retireQuery, performClear).- this.logger.debug("Ignoring cancel while a /clear is in progress", {+ if (session.querySwap) {+ // A /clear or refreshSession is swapping the SDK query: there is no turn+ // to cancel, and interrupting the half-initialized replacement would+ // corrupt the swap. A wedged swap self-limits: retireQuery's interrupt()+ // and the new query's init are both time-bounded (see retireQuery,+ // performClear).+ this.logger.debug("Ignoring cancel while a query swap is in progress", {sessionId: this.sessionId,});return;@@ -1741,6 +1757,30 @@ export class ClaudeAcpAgent extends BaseAcpAgent {}}+ /**+ * Claim the session's query-swap slot, run `fn`, and release the slot when+ * it settles. The claim is synchronous — `fn` must run synchronously up to+ * its own first await — so the flag is visible before any other ACP handler+ * can interleave (handlers are not serialized). Waiters only need+ * settlement, so the stored promise never rejects; a failure still surfaces+ * through the returned promise.+ */+ private async withQuerySwap<T>(+ session: Session,+ fn: () => Promise<T>,+ ): Promise<T> {+ const swap = fn();+ session.querySwap = swap.then(+ () => undefined,+ () => undefined,+ );+ try {+ return await swap;+ } finally {+ session.querySwap = undefined;+ }+ }+/*** `/clear` — drop the conversation and start over in place.*@@ -1758,11 +1798,11 @@ export class ClaudeAcpAgent extends BaseAcpAgent {if (session.queryClosed) {throw RequestError.internalError(undefined, SESSION_ENDED_MESSAGE);}- // A second /clear mid-swap would race the same session fields+ // A second swap mid-swap would race the same session fields// (query/input/abortController) and orphan a live SDK query; a clear// mid-turn would rip the query out from under the active prompt.- const refusal = session.clearing- ? "A conversation clear is already in progress."+ const refusal = session.querySwap+ ? "A session refresh or conversation clear is already in progress. Wait for it to finish and try again.": session.activeTurn !== null || session.turnQueue.length > 0? "Cannot clear the conversation while a turn is in progress. Wait for it to finish (or cancel it) and try again.": null;@@ -1777,25 +1817,11 @@ export class ClaudeAcpAgent extends BaseAcpAgent {return { stopReason: "end_turn" };}- // Claim the session synchronously, before the first await: ACP handlers- // are not serialized, so a prompt/cancel/second clear can arrive at any- // await point of the swap. They key off this flag (see Session.clearing).- // performClear runs synchronously up to its first await, so the claim is- // visible before any other handler can interleave. Waiters only need- // settlement; a failure still surfaces through the returned promise.- const clear = this.performClear(params, session);- session.clearing = clear.then(- () => undefined,- () => undefined,+ return this.withQuerySwap(session, () =>+ this.performClear(params, session),);- try {- return await clear;- } finally {- session.clearing = undefined;- }}- /** Body of {@link clearConversation}; only runs holding `session.clearing`. */private async performClear(params: PromptRequest,session: Session,@@ -2103,14 +2129,14 @@ export class ClaudeAcpAgent extends BaseAcpAgent {}}- private async refreshSession(+ private refreshSession(mcpServers: Record<string, McpServerConfig>,): Promise<void> {const prev = this.session;- if (prev.clearing) {+ if (prev.querySwap) {throw new RequestError(-32002,- "Cannot refresh session while a conversation clear is in progress",+ "Cannot refresh session while a query swap (refresh or /clear) is in progress",);}if (prev.activeTurn !== null || prev.turnQueue.length > 0) {@@ -2126,59 +2152,87 @@ export class ClaudeAcpAgent extends BaseAcpAgent {);}+ return this.withQuerySwap(prev, () =>+ this.performRefresh(prev, mcpServers),+ );+ }++ /** Body of {@link refreshSession}; see {@link withQuerySwap} for the claim+ * contract. */+ private async performRefresh(+ prev: Session,+ mcpServers: Record<string, McpServerConfig>,+ ): Promise<void> {this.logger.info("Refreshing session with fresh MCP servers", {serverCount: Object.keys(mcpServers).length,sessionId: this.sessionId,});- await this.retireQuery(prev);+ // Declared outside the try so the catch can tear down a half-built+ // replacement; assigned inside, where retireQuery also runs so a failure+ // anywhere in the swap gets the same close-out (mirrors performClear).+ let newQuery: Query | undefined;+ let newAbortController: AbortController | undefined;+ try {+ await this.retireQuery(prev);- // Reuse every option from the running session; swap mcpServers, re-root- // identity on `resume` instead of `sessionId`, and give the new Query a- // fresh AbortController.- const newAbortController = new AbortController();- const { sessionId: _drop, ...rest } = prev.queryOptions;+ // Reuse every option from the running session; swap mcpServers, re-root+ // identity on `resume` instead of `sessionId`, and give the new Query a+ // fresh AbortController.+ newAbortController = new AbortController();+ const { sessionId: _drop, ...rest } = prev.queryOptions;- // Rebuild the in-process ("sdk") server fresh; reusing the prior instance- // throws "Already connected to a transport" and drops the signed-commit tools.- const freshInProcess = prev.buildInProcessMcpServers();- if (Object.keys(freshInProcess).length > 0) {- this.logger.info("Rebuilt in-process MCP servers on refresh", {- sessionId: this.sessionId,- servers: Object.keys(freshInProcess),- });- }+ // Rebuild the in-process ("sdk") server fresh; reusing the prior instance+ // throws "Already connected to a transport" and drops the signed-commit tools.+ const freshInProcess = prev.buildInProcessMcpServers();+ if (Object.keys(freshInProcess).length > 0) {+ this.logger.info("Rebuilt in-process MCP servers on refresh", {+ sessionId: this.sessionId,+ servers: Object.keys(freshInProcess),+ });+ }- const newOptions: Options = {- ...rest,- mcpServers: { ...mcpServers, ...freshInProcess },- resume: prev.sdkSessionId,- forkSession: false,- abortController: newAbortController,- // `rest.model` is the creation-time value; the user may have switched- // models since, so re-root the new Query on the live session model.- ...(prev.modelId && { model: toSdkModelId(prev.modelId) }),- };+ const newOptions: Options = {+ ...rest,+ mcpServers: { ...mcpServers, ...freshInProcess },+ resume: prev.sdkSessionId,+ forkSession: false,+ abortController: newAbortController,+ // `rest.model` is the creation-time value; the user may have switched+ // models since, so re-root the new Query on the live session model.+ ...(prev.modelId && { model: toSdkModelId(prev.modelId) }),+ };- const newInput = new Pushable<SDKUserMessage>();- const newQuery = query({ prompt: newInput, options: newOptions });+ const newInput = new Pushable<SDKUserMessage>();+ newQuery = query({ prompt: newInput, options: newOptions });- prev.query = newQuery;- prev.input = newInput;- prev.queryOptions = newOptions;- prev.abortController = newAbortController;+ prev.query = newQuery;+ prev.input = newInput;+ prev.queryOptions = newOptions;+ prev.abortController = newAbortController;- const result = await withTimeout(- newQuery.initializationResult(),- SESSION_VALIDATION_TIMEOUT_MS,- );- if (result.result === "timeout") {- this.terminateQuery(newQuery, newAbortController);- throw new RequestError(- -32603,- `Session refresh timed out after ${SESSION_VALIDATION_TIMEOUT_MS}ms`,- { sessionId: this.sessionId },+ const result = await withTimeout(+ newQuery.initializationResult(),+ SESSION_VALIDATION_TIMEOUT_MS,);+ if (result.result === "timeout") {+ throw new Error(+ `Session refresh timed out after ${SESSION_VALIDATION_TIMEOUT_MS}ms`,+ );+ }+ } catch (error) {+ // The old query is already retired and the new one is unproven, so any+ // failure here — retireQuery, timeout, or SDK init rejection — leaves+ // the session unusable. Tear down any replacement that was allocated+ // and close the session out (same as performClear) rather than leaving+ // it half-swapped: queryClosed gates every later prompt into+ // SESSION_ENDED.+ if (newQuery && newAbortController) {+ this.terminateQuery(newQuery, newAbortController);+ }+ prev.queryClosed = true;+ const message = error instanceof Error ? error.message : String(error);+ throw new RequestError(-32603, message, { sessionId: this.sessionId });}this.refreshMcpMetadata(newQuery);diff --git a/products/desktop/packages/agent/src/adapters/claude/types.ts b/products/desktop/packages/agent/src/adapters/claude/types.tsindex 9d91219d3766..0b36ec468fe1 100644--- a/products/desktop/packages/agent/src/adapters/claude/types.ts+++ b/products/desktop/packages/agent/src/adapters/claude/types.ts@@ -121,10 +121,11 @@ export type Session = BaseSession & {queryGeneration: number;/** The query iterator ended and can't be revived; new prompts reject. */queryClosed?: boolean;- /** Set while a /clear is swapping the SDK query; resolves when it settles- * (success or failure). Prompts await it, cancel/refresh refuse during it,- * and a second /clear is rejected — the swap must never be raced. */- clearing?: Promise<void>;+ /** Set while an in-place SDK query swap (/clear or refreshSession) is in+ * flight; resolves when it settles (success or failure). Prompts await it,+ * cancel and the other swap path refuse during it, and a second swap is+ * rejected — the swap must never be raced. */+ querySwap?: Promise<void>;cancelController?: AbortController;forceCancelTimer?: ReturnType<typeof setTimeout>;emitRawSDKMessages: boolean | SDKMessageFilter[];