Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion apps/desktop/src/main/services/chat/agentChatService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -38319,6 +38324,21 @@ 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. 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, {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Replacement chat repeats the current message

On a replacement send, refreshReconstructionContext treats the current message as history because showTurnBeforeRuntime already recorded it. runAcpTurn sends it again as the live prompt, crowding out one older message when the history is full.

Learn more

runAcpTurn records the outgoing user message before opening the provider session so the user can see startup progress. Recording writes the message into the in-memory history immediately via commitChatEvent. collectConversationEntries reads that history along with the transcript. buildRecentConversationContext keeps the newest 20 entries for ordinary chats. The outgoing message takes one of those slots before the prompt builder appends it as the live request.

Example: A Qwen chat has ten completed exchanges with one user entry and one assistant entry each. After Restart agent session, the provider rejects the old ID. The replacement sees 19 earlier entries plus “What did I say first?” in its history, then receives the same question as the live prompt. The first user entry is missing.

Recommended fix: Pass the opening turn ID from runAcpTurn to the reconstruction path and exclude that turn before selecting the history tail. Filter both the transcript and live-ring fallback by turn ID, not by message text, so an identical request from an earlier turn remains in history.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

type: "system_notice",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replacement tail restages current turn

Medium Severity

Rebuilding reconstruction in onRuntimeCreated runs after showTurnBeforeRuntime has already written this send's user_message. refreshReconstructionContext then folds that current turn into the replacement session's conversation tail, and consumePendingTurnContextPrefix prepends it again as the prompt. On the idle rejoin-fallback path this PR targets, the new thread sees the latest user turn twice — once as prior history and once as the live message.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit d2cc38f. Configure here.

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);
Expand Down Expand Up @@ -79621,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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ import {
createAcpSessionPool,
createMockAcpAgent,
createService,
flushAllQueuedTranscriptWrites,
fs,
getDynamicAcpModelDescriptors,
getModelById,
installRealTranscriptParser,
path,
readPersistedChatState,
respondWithSession,
Expand Down Expand Up @@ -963,6 +965,114 @@ 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. 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 () => {
const harness = await openAcpHarness({
provider: "qwen",
Expand Down
Loading