diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 2525b42b27..352391108f 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -13592,6 +13592,33 @@ test("the last assistant message is the newest turn's reply, not joined to the p } }); +test("the last assistant message read from rebuilt history is the newest reply, not joined to the one before it", async () => { + // Rows replayed from provider history have no turn id. A reply the agent starts on its own, + // such as Claude waking after a background subagent, follows the previous reply with no user + // message between them; only their message ids tell them apart. + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-history-last-reply-")); + const codex = fakeCodexEmitting({ + historyItems: [ + { type: "user_message", text: "Start a background task.", messageId: "user-1" }, + { type: "assistant_message", text: "Started it, ", messageId: "message-1" }, + { type: "assistant_message", text: "I will report back.", messageId: "message-1" }, + { type: "assistant_message", text: "The task finished.", messageId: "message-2" }, + ], + }); + const manager = new AgentManager({ clients: { codex }, logger }); + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + try { + await manager.hydrateTimelineFromProvider(agent.id, { force: true }); + + expect(await manager.getLastAssistantMessage(agent.id)).toBe("The task finished."); + } finally { + await manager.closeAgent(agent.id); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("reads the last durable assistant response without loading a stored-only child", async () => { const store = new RecordingTimelineStore(); await store.appendCommitted("stored-child", { diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index cfd43b2cb5..ece45289e2 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -3,7 +3,7 @@ import { ProviderOptionsValidationError } from "./provider-options.js"; import type { AgentToolResult } from "@getpaseo/plugin/server"; import type { RuntimeCleanupCandidate } from "./idle-runtime-cleanup/index.js"; import { AgentNotFoundError, ensureAgentLoaded } from "./agent-loading.js"; -import { projectTimelineRows } from "./timeline-projection.js"; +import { continuesAssistantMessage, projectTimelineRows } from "./timeline-projection.js"; import type { PluginLifecycle } from "../plugins/lifecycle/index.js"; import { describeHookAgent, publishAgentStream } from "../plugins/lifecycle/index.js"; import { applyRecordPatch } from "../record-patch.js"; @@ -4072,24 +4072,16 @@ export class AgentManager { private getLastAssistantMessageSegmentFromTimeline( timeline: readonly Pick[], ): { text: string; startsAtBeginning: boolean } | null { - // Collect the last contiguous assistant messages of one turn (Claude streams chunks). - // A turn the provider starts on its own has no user message before its reply. + // Collect the chunks of the last assistant message (Claude streams chunks). A turn the + // provider starts on its own has no user message before its reply. const chunks: string[] = []; - let replyTurnId: string | undefined; let startsAtBeginning = false; for (let i = timeline.length - 1; i >= 0; i--) { - const { item, turnId } = timeline[i]; - if (item.type !== "assistant_message") { - if (chunks.length) { - break; - } - continue; - } - if (chunks.length === 0) { - replyTurnId = turnId; - } else if (turnId !== replyTurnId) { + const { item } = timeline[i]; + if (chunks.length > 0 && !continuesAssistantMessage(timeline[i], timeline[i + 1])) { break; } + if (item.type !== "assistant_message") continue; chunks.push(item.text); startsAtBeginning = i === 0; } diff --git a/packages/server/src/server/agent/timeline-projection.ts b/packages/server/src/server/agent/timeline-projection.ts index bd5357e581..905748d752 100644 --- a/packages/server/src/server/agent/timeline-projection.ts +++ b/packages/server/src/server/agent/timeline-projection.ts @@ -241,6 +241,23 @@ function mergeReasoningChunks(entries: readonly WorkingEntry[]): WorkingEntry[] return output; } +/** + * Whether `next`, the row right after `previous`, is another chunk of the same assistant + * message. A turn id or message id change starts a new message, which matters where rows + * replayed from provider history carry no turn id. + */ +export function continuesAssistantMessage( + previous: Pick, + next: Pick, +): boolean { + return ( + previous.item.type === "assistant_message" && + next.item.type === "assistant_message" && + previous.turnId === next.turnId && + (next.item.messageId === undefined || next.item.messageId === previous.item.messageId) + ); +} + function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[] { const output: WorkingEntry[] = []; @@ -248,10 +265,8 @@ function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[] const previous = output[output.length - 1]; const shouldMerge = previous && - previous.item.type === "assistant_message" && - entry.item.type === "assistant_message" && previous.seqEnd + 1 === entry.seqStart && - previous.turnId === entry.turnId; + continuesAssistantMessage(previous, entry); if (!shouldMerge || !previous) { output.push(entry); @@ -262,13 +277,6 @@ function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[] { type: "assistant_message" } >; const entryAssistant = entry.item as Extract; - if ( - entryAssistant.messageId !== undefined && - previousAssistant.messageId !== entryAssistant.messageId - ) { - output.push(entry); - continue; - } const collapsedKinds = new Set([ ...previous.collapsed,