From 6e2fee462f148fe1aa158976da4435c753cc814a Mon Sep 17 00:00:00 2001 From: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:04:00 +0000 Subject: [PATCH] fix(server): fork from a response that background work outlives (#9627) Forking from a reply failed with "This checkpoint changed after it was created" whenever a tool call started before that reply and finished after it, the shape of background Bash, Monitor, Task and Codex terminals. The projection keeps one row per tool call from its start to its latest update, so the row spans the reply, and the fork refused any copied row that spans the checkpoint. Copy such a tool call into the fork marked running: its state at the checkpoint can't be read back. Plugin cards that span the checkpoint stay out, and a cursor from another epoch or a reply that is gone is still refused. --- docs/timeline-sync.md | 9 +- .../src/server/agent/activity-curator.test.ts | 104 +++++++++++------- .../src/server/agent/activity-curator.ts | 40 +++---- .../fork-background-work.e2e.test.ts | 56 ++++++++++ .../server/test-utils/fake-agent-client.ts | 47 ++++++++ 5 files changed, 194 insertions(+), 62 deletions(-) create mode 100644 packages/server/src/server/daemon-e2e/fork-background-work.e2e.test.ts diff --git a/docs/timeline-sync.md b/docs/timeline-sync.md index 245829d92..33a89123d 100644 --- a/docs/timeline-sync.md +++ b/docs/timeline-sync.md @@ -95,10 +95,11 @@ Provider message IDs are not guaranteed for every displayed item. Paseo-generate Actions that address a point in chat history, such as Fork, use the daemon timeline `epoch` plus the projected item's `seqEnd`. The app carries that position on the rendered assistant item for both live and fetched history. When adjacent projected chunks merge, the merged item retains the newer chunk's position. The daemon validates the epoch and locates the projected item at the selected position. A fork -includes projected items through that checkpoint. If an item the fork copies spans the checkpoint -and changed afterward, the daemon refuses that fork with an actionable error: discarded historical -payloads cannot be reconstructed from sequence metadata. Plugin cards are not copied, so a card -updated after the checkpoint does not block it. Forking the current context remains available. +includes projected items through that checkpoint. A tool call that started before the checkpoint +and changed after it, such as background work that outlives a reply, is copied as still running: +the projection keeps only its latest payload, so its state at the checkpoint can't be read back. +Plugin cards are not copied. A position from another epoch, or one that is gone, is refused; +forking the current context remains available. ## Resume behavior diff --git a/packages/server/src/server/agent/activity-curator.test.ts b/packages/server/src/server/agent/activity-curator.test.ts index 6a1d85bcf..6b8e5d484 100644 --- a/packages/server/src/server/agent/activity-curator.test.ts +++ b/packages/server/src/server/agent/activity-curator.test.ts @@ -3,6 +3,7 @@ import { buildAgentForkContextAttachment, curateAgentActivity } from "./activity import type { AgentTimelineItem } from "./agent-sdk-types.js"; import type { AgentTimelineRow } from "./agent-timeline-store-types.js"; import { formatAgentMessage, projectAgentMessages } from "./agent-messages/index.js"; +import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js"; function toolCallItem(params: { callId: string; @@ -39,6 +40,29 @@ function row(seq: number, item: AgentTimelineItem): AgentTimelineRow { }; } +/** Rows as the daemon hands them to a fork: projected by the timeline store. */ +function storeTimeline(items: readonly AgentTimelineItem[]) { + const store = new InMemoryAgentTimelineStore(); + store.initialize("agent-1"); + for (const item of items) store.append("agent-1", item); + const { epoch, rows } = store.fetch("agent-1", { limit: 0 }); + return { epoch, rows }; +} + +function backgroundTaskItem(input: { status: "running" | "completed"; log: string }) { + return toolCallItem({ + callId: "background-task", + name: "Task", + status: input.status, + detail: { + type: "sub_agent", + subAgentType: "Explore", + description: "Audit the migrations", + log: input.log, + }, + }); +} + describe("curateAgentActivity", () => { it("keeps reasoning before the assistant text that followed it", () => { const timeline: AgentTimelineItem[] = [ @@ -414,44 +438,48 @@ second line'`, expect(result.attachment.text).toContain("[Assistant] Done."); }); - it("rejects a checkpoint whose projected tool state changed later", () => { - expect(() => - buildAgentForkContextAttachment({ - boundaryMessageId: "assistant-1", - rows: [ - row(1, { type: "user_message", text: "Run it", messageId: "user-1" }), - row( - 2, - toolCallItem({ - callId: "terminal-1", - name: "terminal", - status: "running", - detail: { - type: "plain_text", - label: "before boundary", - }, - }), - ), - row(3, { - type: "assistant_message", - text: "Partial result.", - messageId: "assistant-1", - }), - row( - 4, - toolCallItem({ - callId: "terminal-1", - name: "terminal", - status: "completed", - detail: { - type: "plain_text", - label: "after boundary", - }, - }), - ), - ], - }), - ).toThrow("Fork from a later completed response"); + it("forks at a response that background work outlives, by message id", () => { + const { rows } = storeTimeline([ + { type: "user_message", text: "Audit in the background", messageId: "user-1" }, + backgroundTaskItem({ status: "running", log: "scanning" }), + { type: "assistant_message", text: "Audit started.", messageId: "assistant-1" }, + backgroundTaskItem({ status: "completed", log: "FINAL REPORT after the response" }), + { type: "user_message", text: "Any findings?", messageId: "user-2" }, + ]); + expect(rows[1]).toMatchObject({ seqStart: 2, seqEnd: 4 }); + + const result = buildAgentForkContextAttachment({ boundaryMessageId: "assistant-1", rows }); + + expect(result.itemCount).toBe(3); + expect(result.boundaryMessageId).toBe("assistant-1"); + expect(result.attachment.text).toContain( + "[User] Audit in the background\n[Explore] Audit the migrations\n[Assistant] Audit started.\n", + ); + expect(result.attachment.text).not.toContain("FINAL REPORT"); + expect(result.attachment.text).not.toContain("Any findings?"); + }); + + it("forks at a response that background work outlives, by timeline cursor", () => { + const { epoch, rows } = storeTimeline([ + { type: "user_message", text: "Audit in the background", messageId: "user-1" }, + backgroundTaskItem({ status: "running", log: "scanning" }), + { type: "assistant_message", text: "Audit started." }, + backgroundTaskItem({ status: "completed", log: "FINAL REPORT after the response" }), + { type: "assistant_message", text: "The audit finished." }, + ]); + + const result = buildAgentForkContextAttachment({ + cursorBoundary: { timelineEpoch: epoch, cursor: { epoch, seq: 3 } }, + rows, + }); + + expect(result.boundaryCursor).toEqual({ epoch, seq: 3 }); + expect(result.itemCount).toBe(3); + expect(result.attachment.text).toContain( + "[User] Audit in the background\n[Explore] Audit the migrations\n[Assistant] Audit started.\n", + ); + expect(result.attachment.text).not.toContain("FINAL REPORT"); + expect(result.attachment.text).not.toContain("The audit finished."); }); it("forks from a checkpoint when a plugin card was updated after it", () => { diff --git a/packages/server/src/server/agent/activity-curator.ts b/packages/server/src/server/agent/activity-curator.ts index a0c537254..f76c0ffbb 100644 --- a/packages/server/src/server/agent/activity-curator.ts +++ b/packages/server/src/server/agent/activity-curator.ts @@ -1,4 +1,4 @@ -import type { AgentTimelineItem } from "./agent-sdk-types.js"; +import type { AgentTimelineItem, ToolCallTimelineItem } from "./agent-sdk-types.js"; import type { AgentMessage } from "@getpaseo/protocol/agent-message"; import type { AgentAttachment } from "@getpaseo/protocol/messages"; import type { AgentTimelineRow } from "./agent-timeline-store-types.js"; @@ -13,7 +13,7 @@ const MAX_TOOL_SUMMARY_CHARS = 200; const MAX_FORK_CONTEXT_CHARS = 100_000; const MAX_FORK_METADATA_CHARS = 1_000; const FORK_HISTORY_OMITTED = "[Earlier chat history omitted]\n"; -// A fork copies only these kinds, so only they can make a checkpoint stale. +// A fork copies only these kinds. const FORK_CONTEXT_KINDS: readonly AgentTimelineItem["type"][] = [ "user_message", "assistant_message", @@ -275,25 +275,25 @@ function selectForkContextRows(input: { ); } const boundarySeq = projectedRows[boundaryIndex].seqEnd; - if ( - projectedRows.some( - (row) => - FORK_CONTEXT_KINDS.includes(row.item.type) && - row.seqStart <= boundarySeq && - row.seqEnd > boundarySeq, - ) - ) { - throw new Error( - "This checkpoint changed after it was created. Fork from a later completed response instead.", - ); - } - const projected = projectedRows.filter((row) => row.seqEnd <= boundarySeq); + // Only tool calls and plugin cards fold later updates into an earlier row, and a fork doesn't + // copy plugin cards. So the only row that spans the checkpoint and still reaches the fork is a + // tool call. + const items = projectedRows.flatMap((row) => { + if (row.seqEnd <= boundarySeq) return [row.item]; + if (row.seqStart > boundarySeq || row.item.type !== "tool_call") return []; + return [toolCallAtCheckpoint(row.item)]; + }); - return { - items: projected.map((entry) => entry.item), - boundaryCursor, - boundaryMessageId, - }; + return { items, boundaryCursor, boundaryMessageId }; +} + +/** + * A tool call that started before the checkpoint and changed after it, such as background work + * that outlives a reply. The projection keeps only its latest payload, so the fork copies it as + * still running. + */ +function toolCallAtCheckpoint(item: ToolCallTimelineItem): ToolCallTimelineItem { + return { ...item, status: "running", error: null }; } function trimContextMetadata(value: string | null | undefined): string | null { diff --git a/packages/server/src/server/daemon-e2e/fork-background-work.e2e.test.ts b/packages/server/src/server/daemon-e2e/fork-background-work.e2e.test.ts new file mode 100644 index 000000000..d8dbfe7eb --- /dev/null +++ b/packages/server/src/server/daemon-e2e/fork-background-work.e2e.test.ts @@ -0,0 +1,56 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, expect, test } from "vitest"; +import { createDaemonTestContext, type DaemonTestContext } from "../test-utils/index.js"; + +let ctx: DaemonTestContext; +let cwd: string; + +beforeEach(async () => { + ctx = await createDaemonTestContext(); + cwd = mkdtempSync(path.join(tmpdir(), "fork-background-work-")); +}); + +afterEach(async () => { + await ctx.cleanup(); + rmSync(cwd, { recursive: true, force: true }); +}, 30_000); + +test("forks from a reply that background work outlived", async () => { + const agent = await ctx.client.createAgent({ provider: "claude", cwd }); + await ctx.client.sendMessage(agent.id, "Start background work"); + expect((await ctx.client.waitForFinish(agent.id, 15_000)).status).toBe("idle"); + await ctx.client.sendMessage(agent.id, "Any findings?"); + expect((await ctx.client.waitForFinish(agent.id, 15_000)).status).toBe("idle"); + + const page = await ctx.client.fetchAgentTimeline(agent.id, { direction: "tail", limit: 0 }); + const reply = page.entries.find( + (entry) => entry.item.type === "assistant_message" && entry.item.text === "Audit started.", + ); + if (reply?.item.type !== "assistant_message" || !reply.item.messageId) { + throw new Error("Expected the reply to carry a provider message id"); + } + const task = page.entries.find((entry) => entry.item.type === "tool_call"); + // The Task row started before the reply and completed after it. + expect(task?.item).toMatchObject({ name: "Task", status: "completed" }); + expect(task?.seqStart).toBeLessThan(reply.seqEnd); + expect(task?.seqEnd).toBeGreaterThan(reply.seqEnd); + + const byMessage = await ctx.client.buildAgentForkContext(agent.id, { + boundaryMessageId: reply.item.messageId, + }); + const byCursor = await ctx.client.buildAgentForkContext(agent.id, { + boundaryCursor: { epoch: page.epoch, seq: reply.seqEnd }, + }); + + for (const fork of [byMessage, byCursor]) { + expect(fork.itemCount).toBe(3); + expect(fork.attachment?.text).toContain( + "[User] Start background work\n[Explore] Audit the migrations\n[Assistant] Audit started.\n", + ); + expect(fork.attachment?.text).not.toContain("Any findings?"); + } + expect(byMessage.boundaryMessageId).toBe(reply.item.messageId); + expect(byCursor.boundaryCursor).toEqual({ epoch: page.epoch, seq: reply.seqEnd }); +}, 60_000); diff --git a/packages/server/src/server/test-utils/fake-agent-client.ts b/packages/server/src/server/test-utils/fake-agent-client.ts index 1be2a405e..e9a0d9828 100644 --- a/packages/server/src/server/test-utils/fake-agent-client.ts +++ b/packages/server/src/server/test-utils/fake-agent-client.ts @@ -547,6 +547,48 @@ class FakeAgentSession implements AgentSession { this.notifySubscribers(completed); } + private async emitEvent(event: AgentStreamEvent): Promise { + await this.appendHistoryEvent(event); + this.notifySubscribers(event); + } + + /** + * A background Task that outlives the turn's reply: the Task starts, the assistant replies, + * then the Task completes. + */ + private async emitBackgroundWorkTurn(): Promise { + const callId = randomUUID(); + const task = (status: "running" | "completed", log: string): AgentStreamEvent => ({ + type: "timeline", + provider: this.providerName, + item: { + type: "tool_call", + name: "Task", + callId, + status, + error: null, + detail: { + type: "sub_agent", + subAgentType: "Explore", + description: "Audit the migrations", + log, + }, + }, + }); + await this.emitEvent(task("running", "")); + await this.emitEvent({ + type: "timeline", + provider: this.providerName, + item: { type: "assistant_message", text: "Audit started.", messageId: randomUUID() }, + }); + await this.emitEvent(task("completed", "Found 2 unsafe migrations.")); + await this.emitEvent({ + type: "turn_completed", + provider: this.providerName, + usage: { inputTokens: 1, outputTokens: 1 }, + }); + } + private async emitStressTurn(stress: { count: number; coalesced: boolean }): Promise { for (let index = 0; index < stress.count; index += 1) { const stressUpdate: AgentStreamEvent = { @@ -790,6 +832,11 @@ class FakeAgentSession implements AgentSession { this.notifySubscribers(child); } + if (textPrompt === "Start background work") { + await this.emitBackgroundWorkTurn(); + return; + } + if (textPrompt.toLowerCase().includes("emit a turn failure")) { const failed: AgentStreamEvent = { type: "turn_failed",