From d2cc38f4c1210f7d355abf208b74509b29b07625 Mon Sep 17 00:00:00 2001 From: Arul Sharma Date: Mon, 23 Nov 2026 11:08:52 -0500 Subject: [PATCH 1/2] fix(chat): tell a replacement ACP session the conversation it lost When an ACP agent no longer has the chat's stored session (the -32002 rejoin refusal, or a Restart session), the host silently opens session/new. onRuntimeCreated only recorded the new id, so the next turn landed on an agent that had never seen the kept turns ADE still displays, with no notice and no conversation tail. Claude, Codex, Muse and Copilot all notify and re-orient in that situation; ACP did neither. Now onRuntimeCreated treats a stored id that opened as a new session as the replacement it is: it emits a warning notice naming the provider, re-stages the once-per-thread sections (resetStagedSection, so a prior "none" continuity key cannot count as no change), and rebuilds the turn context so the conversation tail rides that same turn. Brand-new chats and successful resume/load are untouched, as are entry-plan selection, prompt order and the queued-steer path. Proof: the new case in agentChatServiceAcpRuntime.test.ts models a restored chat whose first turn resumed the agent's session (spending the conversation tail), then lost that session on a Restart. Pre-fix it fails twice: the replacement's session/prompt carries no "teal" from the kept turn, and no "started a new one" notice is emitted. With the patch both pass, and removing restageSectionsForNewProviderThread makes it red again, proving the reset is load-bearing. The whole file passes (37 tests), and the ade-desktop typecheck is clean. Co-Authored-By: Claude Code --- .../main/services/chat/agentChatService.ts | 13 +++ .../chat/agentChatServiceAcpRuntime.test.ts | 104 ++++++++++++++++++ 2 files changed, 117 insertions(+) diff --git a/apps/desktop/src/main/services/chat/agentChatService.ts b/apps/desktop/src/main/services/chat/agentChatService.ts index 0e7b93b981..bb4a59c581 100644 --- a/apps/desktop/src/main/services/chat/agentChatService.ts +++ b/apps/desktop/src/main/services/chat/agentChatService.ts @@ -38319,6 +38319,19 @@ export function createAgentChatService(args: { managed.runtimeInvalidated = false; managed.acpReasoningEffortInvalidated = false; managed.seededAcpSessionId = runtime.session.sessionId; + // A stored session the agent no longer had: this new session holds + // none of the conversation ADE keeps. Re-stage the once-per-thread + // sections and say so, as Muse's replacement session does. + if (existingSessionId && runtime.session.entryPlan.mode === "new") { + emitChatEvent(managed, { + type: "system_notice", + noticeKind: "warning", + severity: "warning", + message: `${dialect.displayName} could not reopen this chat's session, so it started a new one. Earlier turns are summarized for it.`, + }); + restageSectionsForNewProviderThread(managed); + refreshReconstructionContext(managed); + } managed.session.acpPermissionMode = permissionMode; if (runtime.session.systemPromptAppended) { markLaneGuidanceDelivered(managed, runtime.session.sessionId, runtime.session.systemPromptAppended); diff --git a/apps/desktop/src/main/services/chat/agentChatServiceAcpRuntime.test.ts b/apps/desktop/src/main/services/chat/agentChatServiceAcpRuntime.test.ts index bd77953990..c24771fac9 100644 --- a/apps/desktop/src/main/services/chat/agentChatServiceAcpRuntime.test.ts +++ b/apps/desktop/src/main/services/chat/agentChatServiceAcpRuntime.test.ts @@ -8,9 +8,11 @@ import { createAcpSessionPool, createMockAcpAgent, createService, + flushAllQueuedTranscriptWrites, fs, getDynamicAcpModelDescriptors, getModelById, + installRealTranscriptParser, path, readPersistedChatState, respondWithSession, @@ -963,6 +965,108 @@ describe("acp chat runtime", () => { expect(agent.methodsReceived()).not.toContain("session/new"); }); + it("tells a replacement ACP session the conversation it lost", async () => { + // A chat restored from disk carries its transcript, but the agent may no + // longer have the stored session (the documented -32002 rejoin, or a + // Restart session). The host opens session/new while ADE keeps showing + // the old turns, so the next turn must carry them onto the replacement, + // and the chat must say so. + // A second service reads the restored transcript from disk, not this + // module's event buffer, so the real parser is part of the setup. + installRealTranscriptParser(); + const agents: MockAcpAgent[] = []; + const spawnFreshAgent = () => { + const agent = createMockAcpAgent(); + const index = agents.length; + agent.on("session/new", respondWithSession(index === 2 ? "acp-2" : "acp-1")); + agent.on("session/close", () => ({ result: {} })); + agent.on("session/set_config_option", () => ({ result: {} })); + agent.on("session/cancel", () => ({ result: {} })); + agent.on("session/prompt", async () => ({ result: { stopReason: "end_turn" } })); + if (index < 2) { + // The first two processes still have the session: the rejoin succeeds. + agent.on("session/resume", respondWithSession("acp-1")); + agent.on("session/load", respondWithSession("acp-1")); + } else { + // The third never persisted acp-1: the rejoin is refused as missing. + const missing = () => ({ error: { code: -32002, message: "session not found" } }); + agent.on("session/resume", missing); + agent.on("session/load", missing); + } + agents.push(agent); + return agent.child; + }; + const promptText = (agent: MockAcpAgent) => agent.received + .filter((entry) => entry.method === "session/prompt") + .map((entry) => (entry.params as { prompt: Array<{ type: string; text?: string }> }).prompt + .filter((block) => block.type === "text") + .map((block) => block.text ?? "") + .join("\n")) + .join("\n"); + const doneOn = (events: AgentChatEventEnvelope[], sessionId: string) => events + .filter((envelope) => envelope.sessionId === sessionId && envelope.event.type === "done"); + + const firstPool = createAcpSessionPool(); + acpTeardown.push(() => firstPool.disposeAll("test teardown")); + const firstEvents: AgentChatEventEnvelope[] = []; + const first = createService({ + onEvent: (event: AgentChatEventEnvelope) => firstEvents.push(event), + acpSpawnOverride: spawnFreshAgent, + acpSessionPool: firstPool, + }); + acpTeardown.push(() => { void first.service.disposeAll(); }); + const session = await first.service.createSession({ + laneId: "lane-1", + provider: "qwen", + model: "qwen3-coder-plus", + modelId: "qwen/qwen3-coder-plus", + }); + await first.service.sendMessage({ + sessionId: session.id, + text: "My favourite colour is teal. Reply with only the word: noted", + }); + await vi.waitFor(() => expect(doneOn(firstEvents, session.id)).toHaveLength(1)); + await flushAllQueuedTranscriptWrites(); + + // A second service over the same state is the restored chat: its first + // turn rejoins the agent's session, which already holds the kept turn, so + // the tail is consumed there and the replacement has to be told again. + const secondPool = createAcpSessionPool(); + acpTeardown.push(() => secondPool.disposeAll("test teardown")); + const events: AgentChatEventEnvelope[] = []; + const second = createService({ + onEvent: (event: AgentChatEventEnvelope) => events.push(event), + acpSpawnOverride: spawnFreshAgent, + acpSessionPool: secondPool, + laneService: first.laneService, + sessionService: first.sessionService, + }); + acpTeardown.push(() => { void second.service.disposeAll(); }); + + await second.service.sendMessage({ sessionId: session.id, text: "Second message." }); + await vi.waitFor(() => expect(doneOn(events, session.id)).toHaveLength(1)); + // The resumed thread's turn carries the kept turn, so the tail is spent + // there; nothing is left staged for the replacement. + expect(promptText(agents[1]!)).toContain("teal"); + + await second.service.restartSession({ sessionId: session.id }); + + await second.service.sendMessage({ sessionId: session.id, text: "What did I say first?" }); + await vi.waitFor(() => expect(doneOn(events, session.id)).toHaveLength(2)); + + expect(agents).toHaveLength(3); + // The replacement hears the kept turn, before the new message (the tail is + // prepended, not substituted). + const replacement = promptText(agents[2]!); + expect(replacement).toContain("teal"); + expect(replacement.indexOf("teal")).toBeLessThan(replacement.lastIndexOf("What did I say first?")); + // And the chat says the old session is gone instead of silently starting over. + const notices = events + .filter((envelope) => envelope.sessionId === session.id && envelope.event.type === "system_notice") + .map((envelope) => String((envelope.event as Record).message)); + expect(notices.some((message) => message.includes("Qwen Code") && message.includes("started a new one"))).toBe(true); + }); + it("offers the agent's advertised slash commands once, even when re-sent", async () => { const harness = await openAcpHarness({ provider: "qwen", From 12b57f1536fef5b7d31bd8eca5baf24a1d1a98e4 Mon Sep 17 00:00:00 2001 From: Arul Sharma Date: Mon, 23 Nov 2026 12:00:40 -0500 Subject: [PATCH 2/2] fix(chat): only a session ADE opened can be the lost one Review findings on PR #2476: - A model switch that changes provider kept the previous provider's seeded ACP session id. Handed to the new provider it opened as a new session, so the lost-session guard warned about a conversation loss and staged the conversation tail on top of the full transcript replay the switch had already staged. The seed is now dropped on a provider switch (the persisted copy is already dropped by runtimeInvalidated), and the notice/re-stage only fire for an id ADE itself opened (seed or persisted) rather than a Devin Cloud chat's derived id, which a brand-new chat has never opened. - The proof test pinned the warning's sentence. It now asserts the event shape the contract actually promises: a system_notice warning that names the provider. Proof: agentChatServiceAcpRuntime.test.ts (37 tests) and the ade-desktop typecheck pass. Co-Authored-By: Claude Code --- .../main/services/chat/agentChatService.ts | 19 ++++++++++++++++--- .../chat/agentChatServiceAcpRuntime.test.ts | 16 +++++++++++----- 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/apps/desktop/src/main/services/chat/agentChatService.ts b/apps/desktop/src/main/services/chat/agentChatService.ts index bb4a59c581..aeb4799932 100644 --- a/apps/desktop/src/main/services/chat/agentChatService.ts +++ b/apps/desktop/src/main/services/chat/agentChatService.ts @@ -38185,8 +38185,13 @@ export function createAgentChatService(args: { const invocationKey = acpInvocationKey(spawnPlan); const persisted = readPersistedState(managed.session.id); - const existingSessionId = managed.seededAcpSessionId?.trim() + // The id of a session ADE itself opened for this chat. A Devin Cloud + // chat's derived id (below) only guesses at a session nothing has opened + // yet, so it cannot be evidence that a session was lost. + const storedAcpSessionId = managed.seededAcpSessionId?.trim() || persisted?.acpSessionId?.trim() + || null; + const existingSessionId = storedAcpSessionId // A Devin Cloud chat opened from the panel knows its session by the web // id before it has ever spoken ACP. || (devinCloud && managed.session.devinSessionId?.trim() @@ -38321,8 +38326,10 @@ export function createAgentChatService(args: { managed.seededAcpSessionId = runtime.session.sessionId; // A stored session the agent no longer had: this new session holds // none of the conversation ADE keeps. Re-stage the once-per-thread - // sections and say so, as Muse's replacement session does. - if (existingSessionId && runtime.session.entryPlan.mode === "new") { + // sections and say so, as Muse's replacement session does. Only a + // session ADE opened can be lost; a provider switch clears the seed + // and replays the whole transcript instead. + if (storedAcpSessionId && runtime.session.entryPlan.mode === "new") { emitChatEvent(managed, { type: "system_notice", noticeKind: "warning", @@ -79634,6 +79641,12 @@ export function createAgentChatService(args: { } if (previousProvider !== nextProvider || freshThreadForRoute) { delete managed.session.threadId; + // An ACP session id belongs to the provider that minted it. Carried + // onto the next provider, a deliberate switch looks like a session + // the agent no longer has (a `new` entry under a stored id), which + // warns about a lost conversation and stacks the tail on the full + // replay staged below. `runtimeInvalidated` drops the persisted copy. + delete managed.seededAcpSessionId; managed.runtimeInvalidated = true; managed.acpReasoningEffortInvalidated = false; clearDeliveredDirectiveEpoch(managed); diff --git a/apps/desktop/src/main/services/chat/agentChatServiceAcpRuntime.test.ts b/apps/desktop/src/main/services/chat/agentChatServiceAcpRuntime.test.ts index c24771fac9..51f3166fbd 100644 --- a/apps/desktop/src/main/services/chat/agentChatServiceAcpRuntime.test.ts +++ b/apps/desktop/src/main/services/chat/agentChatServiceAcpRuntime.test.ts @@ -1060,11 +1060,17 @@ describe("acp chat runtime", () => { const replacement = promptText(agents[2]!); expect(replacement).toContain("teal"); expect(replacement.indexOf("teal")).toBeLessThan(replacement.lastIndexOf("What did I say first?")); - // And the chat says the old session is gone instead of silently starting over. - const notices = events - .filter((envelope) => envelope.sessionId === session.id && envelope.event.type === "system_notice") - .map((envelope) => String((envelope.event as Record).message)); - expect(notices.some((message) => message.includes("Qwen Code") && message.includes("started a new one"))).toBe(true); + // And the chat says the old session is gone instead of silently starting + // over. Naming the provider is the contract; the sentence is not. + const notices = events.filter( + (envelope) => envelope.sessionId === session.id && envelope.event.type === "system_notice", + ); + expect(notices.some((envelope) => { + const notice = envelope.event as { noticeKind?: string; severity?: string; message?: string }; + return notice.noticeKind === "warning" + && notice.severity === "warning" + && Boolean(notice.message?.includes("Qwen Code")); + })).toBe(true); }); it("offers the agent's advertised slash commands once, even when re-sent", async () => {