fix(timeline): sync provider history at whole turn boundaries

This commit is contained in:
Mohamed Boudra
2026-11-18 14:45:23 +01:00
parent 28c9806da8
commit 0c11263d4d
7 changed files with 78 additions and 431 deletions
+5 -4
View File
@@ -40,10 +40,11 @@ deleting the agent, or a provider removing one of its own children, deletes hist
- **Rewind** retires a range of rows. They leave the conversation and stay stored, in the same
epoch. See [Rewind retires rows](#rewind-retires-rows).
- **Provider history** is imported only into an agent that has no history. After that, resume
does not read it. Reload agent and Unarchive append only the rows the provider has after the
owned conversation, as ordinary live rows. Any other difference, including an answer Paseo saw only part of or a prompt sent with
attachments, changes nothing and is reported as diverged. A provider child Paseo already holds,
listed or retired, is never imported again.
does not read it. Reload agent and Unarchive require the provider history to start with the
same prompt IDs and text in order. They then append whole new turns, starting at the next
prompt. Existing replies, including partial replies, stay as recorded. If the prompts differ,
for example because the provider stored expanded attachment text, the chat stays unchanged and
Paseo reports a mismatch. A provider child Paseo already holds, listed or retired, is never imported again.
- **Archive and reload** keep the history and the provider children. An archived chat reads them
without its provider. Deleting the agent deletes its history and every child's, retired ones
included.
@@ -1089,13 +1089,10 @@ test("Reload agent keeps the history when the provider history differs or cannot
await expect(reloadAgent(manager, agent.id)).rejects.toThrow("history stream closed");
expect(await manager.fetchTimeline(agent.id)).toEqual(committed);
// Edited outside Paseo under the same prompt: the owned answer stays.
// A replayed answer can differ from what Paseo recorded. Keep the owned answer.
failRead = false;
providerHistory = [providerHistory[0]!, { type: "assistant_message", text: "rewritten" }];
expect(await reloadAgent(manager, agent.id)).toEqual({
kind: "diverged",
reason: "The provider history has a different last answer",
});
expect(await reloadAgent(manager, agent.id)).toEqual({ kind: "unchanged" });
expect(await manager.fetchTimeline(agent.id)).toEqual(committed);
} finally {
if (agentId) await manager.closeAgent(agentId).catch(() => undefined);
@@ -2065,8 +2065,7 @@ export class AgentManager {
/**
* Brings in what the provider's own history adds to the agent's owned history, which is never
* changed: rows the provider has after the owned conversation are appended as ordinary live rows.
* Any other difference, including an answer Paseo saw only part of, is reported as `diverged`
* and changes nothing.
* A mismatch in the prompt sequence is reported as `diverged` and changes nothing.
*/
reconcileProviderHistory(agentId: string): Promise<ProviderHistoryReconcile> {
return this.runLifecycleMutation(agentId, async () => {
@@ -1231,7 +1231,7 @@ function mapCodexStreamRetryToStatusLine(
...(retry.details ? { text: retry.details } : {}),
icon: "sparkles" as const,
},
metadata: { synthetic: true, source: "codex_stream_retry", liveOnly: true },
metadata: { synthetic: true, source: "codex_stream_retry" },
};
if (outcome.status === "failed") {
return { ...base, status: "failed", error: outcome.error };
@@ -1220,114 +1220,35 @@ describe.each(TIMELINE_CONTRACT_BACKENDS)("provider history over a $name backend
expect(texts(await timeline.readRows(scope))).toEqual(["a", "A"]);
});
function tool(callId: string, output: string, status: "running" | "completed" = "completed") {
const detail = { type: "shell" as const, command: "npm test", output };
const item: AgentTimelineItem =
status === "running"
? { type: "tool_call", callId, name: "shell", status, error: null, detail }
: { type: "tool_call", callId, name: "shell", status, error: null, detail };
return { item };
}
it("changes nothing when the provider holds the same conversation", async () => {
const { backend, timeline } = await owned([
prompt("a"),
tool("t1", "3 passed"),
reply("Tests "),
reply("pass."),
// Paseo writes notifications itself; the provider has none.
{ item: { type: "notification", level: "info", message: "Agent resumed" } },
prompt("b"),
reply("B"),
]);
const appendsBefore = backend.appends.length;
const published: unknown[] = [];
const result = await timeline.reconcileProviderHistory(
scope,
[
prompt("a"),
// The same tool call, its fields in another order.
{
item: {
detail: { output: "3 passed", command: "npm test", type: "shell" },
error: null,
status: "completed",
name: "shell",
callId: "t1",
type: "tool_call",
},
},
// The provider stores the answer whole; Paseo streamed it in chunks.
reply("Tests pass."),
prompt("b"),
reply("B"),
],
{ publish: (commits) => published.push(commits) },
);
expect(result).toEqual({ kind: "unchanged" });
expect(published).toEqual([]);
expect(backend.appends.length).toBe(appendsBefore);
expect(await timeline.describe(scope)).toMatchObject({ epoch: "e", retirementCount: 0 });
});
it("appends provider history without dropping live-only status rows", async () => {
const status: AgentTimelineItem = {
type: "tool_call",
name: "codex_retry",
callId: "retry",
status: "completed",
error: null,
detail: { type: "plain_text", label: "Reconnected" },
metadata: { liveOnly: true },
};
const { timeline } = await owned([prompt("a"), reply("A"), { item: status }]);
const result = await timeline.reconcileProviderHistory(scope, [
it("syncs whole new turns despite different output under matching prompts", async () => {
const initial = [
prompt("a"),
reply("A"),
reply("\n\n---\n\nSecond message"),
prompt("b"),
reply("B"),
reply("The answer is"),
];
const { timeline } = await owned(initial);
const before = await timeline.readRows(scope);
const replay = [
prompt("a"),
reply("A"),
reply("Second message"),
prompt("b"),
reply("The answer is 42."),
];
expect(await timeline.reconcileProviderHistory(scope, replay)).toEqual({ kind: "unchanged" });
const result = await timeline.reconcileProviderHistory(scope, [
...replay,
prompt("c"),
reply("C"),
]);
expect(result).toMatchObject({ kind: "appended" });
expect((await timeline.readRows(scope)).map((row) => row.item)).toEqual([
prompt("a").item,
reply("A").item,
status,
prompt("b").item,
reply("B").item,
]);
});
it.each<{ name: string; live: TimelineEntry[]; replay: TimelineEntry[] }>([
{
name: "compaction",
live: [
{ item: { type: "compaction", status: "loading", trigger: "auto" } },
{ item: { type: "compaction", status: "completed", trigger: "auto", preTokens: 100 } },
],
replay: [{ item: { type: "compaction", status: "completed" } }],
},
{
name: "to-do",
live: [{ item: { type: "todo", items: [{ text: "Check tests", completed: true }] } }],
replay: [],
},
])("keeps $name status while reconciling later provider turns", async ({ live, replay }) => {
const initial = [prompt("a"), ...live, reply("A")];
const { timeline } = await owned(initial);
const provider = [prompt("a"), ...replay, reply("A")];
expect(await timeline.reconcileProviderHistory(scope, provider)).toEqual({ kind: "unchanged" });
const continuation = [prompt("b"), reply("B")];
expect(
await timeline.reconcileProviderHistory(scope, [...provider, ...continuation]),
).toMatchObject({ kind: "appended" });
expect((await timeline.readRows(scope)).map((row) => row.item)).toEqual(
[...initial, ...continuation].map(({ item }) => item),
);
const after = await timeline.readRows(scope);
expect(after.slice(0, before.length)).toEqual(before);
expect(texts(after.slice(before.length))).toEqual(["c", "C"]);
});
it("appends the turns the provider has after the owned conversation", async () => {
@@ -1348,83 +1269,6 @@ describe.each(TIMELINE_CONTRACT_BACKENDS)("provider history over a $name backend
});
it.each([
{
case: "the turn has no output yet",
owned: [prompt("a"), reply("A"), prompt("b")],
appended: ["tool_call", "B"],
},
{
case: "the turn ends on a finished tool call",
owned: [prompt("a"), reply("A"), prompt("b"), tool("t1", "3 passed")],
appended: ["B"],
},
])("appends the rows the provider has after the last turn when $case", async (example) => {
const { timeline } = await owned(example.owned);
const before = await timeline.readRows(scope);
const result = await timeline.reconcileProviderHistory(scope, [
prompt("a"),
reply("A"),
prompt("b"),
tool("t1", "3 passed"),
reply("B"),
]);
expect(result).toMatchObject({ kind: "appended" });
if (result.kind !== "appended") throw new Error("expected an append");
expect(committedTexts(result.commits)).toEqual(example.appended);
// The rows Paseo already showed are the same rows, unchanged.
expect((await timeline.readRows(scope)).slice(0, before.length)).toEqual(before);
expect(await timeline.describe(scope)).toMatchObject({ epoch: "e", retirementCount: 0 });
});
it.each([
{
case: "an earlier answer differs under the same prompts",
provider: [prompt("a"), reply("edited"), prompt("b"), reply("B"), prompt("c"), reply("C")],
reason: "The provider history has a different answer",
},
{
case: "the last answer differs under the same prompts",
provider: [prompt("a"), reply("A"), prompt("b"), reply("something else"), prompt("c")],
reason: "The provider history has a different last answer",
},
{
case: "the provider's last answer is shorter than Paseo's",
provider: [prompt("a"), reply("A"), prompt("b"), reply("B"), prompt("c")],
owned: [prompt("a"), reply("A"), prompt("b"), reply("B and more")],
reason: "The provider history has a different last answer",
},
{
case: "the provider finished an answer Paseo saw only part of",
owned: [prompt("a"), reply("A"), prompt("b"), reply("The answer is")],
provider: [prompt("a"), reply("A"), prompt("b"), reply("The answer is 42."), prompt("c")],
reason: "The provider history has a different last answer",
},
{
case: "a tool call Paseo saw running has finished",
owned: [prompt("a"), reply("A"), prompt("b"), tool("t1", "", "running")],
provider: [prompt("a"), reply("A"), prompt("b"), tool("t1", "3 passed"), reply("B")],
reason: "The provider history has a different last answer",
},
{
case: "only the indentation of an answer differs",
owned: [prompt("a"), reply("def f():\n return 1"), prompt("b"), reply("B")],
provider: [prompt("a"), reply("def f():\n return 1"), prompt("b"), reply("B")],
reason: "The provider history has a different answer",
},
{
case: "only the spacing inside a string differs",
owned: [prompt("a"), reply("A"), prompt("b"), reply('print("a b")')],
provider: [prompt("a"), reply("A"), prompt("b"), reply('print("a b")'), prompt("c")],
reason: "The provider history has a different last answer",
},
{
case: "the answer is the same but a tool result differs",
owned: [prompt("a"), tool("t1", "3 passed"), reply("Done"), prompt("b"), reply("B")],
provider: [prompt("a"), tool("t1", "1 failed"), reply("Done"), prompt("b"), reply("B")],
reason: "The provider history has a different answer",
},
{
case: "the prompts differ",
provider: [prompt("a"), reply("A"), prompt("x"), reply("B"), prompt("c")],
@@ -1436,9 +1280,7 @@ describe.each(TIMELINE_CONTRACT_BACKENDS)("provider history over a $name backend
reason: "The provider history is missing turns Paseo shows",
},
])("keeps the owned history when $case", async (example) => {
const { backend, timeline } = await owned(
example.owned ?? [prompt("a"), reply("A"), prompt("b"), reply("B")],
);
const { backend, timeline } = await owned([prompt("a"), reply("A"), prompt("b"), reply("B")]);
const before = await timeline.readRows(scope);
const appendsBefore = backend.appends.length;
@@ -1,277 +1,85 @@
import type { AgentTimelineItem } from "../../agent-sdk-types.js";
import { mergeToolCallItems, type ProjectedTimelineRow } from "../../timeline-projection.js";
import type { ProjectedTimelineRow } from "../../timeline-projection.js";
import type { TimelineEntry, TimelinePrompt } from "./backend.js";
/**
* What the provider's history adds to the owned history. Owned rows are never changed: the plan
* only appends rows the provider has after them.
*/
export type ProviderHistoryPlan =
| { kind: "unchanged" }
| { kind: "append"; entries: TimelineEntry[] }
| { kind: "diverged"; reason: string };
type ToolCallItem = Extract<AgentTimelineItem, { type: "tool_call" }>;
/**
* A run of turn content compared as a whole. Consecutive assistant text joins into one text
* segment, as the projection joins streamed chunks; a tool call folds its updates by `callId`.
*/
type Segment =
| { kind: "text" | "reasoning"; text: string }
| { kind: "tool_call"; item: ToolCallItem };
interface Turn {
/** The provider's id for the prompt that opens the turn. */
promptId: string | undefined;
/** The opening prompt's text, as the timeline shows it. */
promptText: string;
segments: Segment[];
interface Prompt {
id: string | undefined;
text: string;
}
interface OwnedTurn extends Turn {
/** A prompt Paseo submitted that the provider never acknowledged follows the opening prompt. */
hasUndeliveredPrompt: boolean;
}
interface ProviderTurn extends Turn {
/** Index of the opening prompt in the provider entries. */
interface ProviderPrompt extends Prompt {
start: number;
/** Index of the first and of the last provider entry of each segment. */
segmentStarts: number[];
segmentEnds: number[];
}
/**
* Turns are aligned by the provider's prompt ids and compared exactly, prompt text included. A
* provider prompt id repeated with other text is divergence. Every owned turn but the
* last must equal the provider's. The last may be a whole-segment prefix of the provider's, whose
* further rows are appended as new rows. A segment that differs at all, including an answer Paseo
* saw only part of or a tool call that finished since, is divergence, and nothing is written.
*
* Compare prompts, assistant and reasoning text, and tool calls by `callId`, `name`,
* `status`, `error` and `detail`. Status and presentation rows can differ between the live
* stream and history replay. They stay in the timeline without affecting this comparison.
* Sync only whole new turns. The provider's prompts must start with Paseo's acknowledged prompts
* in order, with matching IDs and text. Live output and replay may represent the same turn
* differently, so neither decides whether an existing turn matches.
*/
export function planProviderHistory(input: {
rows: readonly ProjectedTimelineRow[];
prompts: readonly TimelinePrompt[];
provider: readonly TimelineEntry[];
}): ProviderHistoryPlan {
const owned = ownedTurns(input.rows, input.prompts);
const provider = providerTurns(input.provider);
if ([...owned.turns, ...provider].some((turn) => turn.promptId === undefined)) {
const owned = ownedPrompts(input.rows, input.prompts);
const provider = providerPrompts(input.provider);
if ([...owned.prompts, ...provider].some((prompt) => prompt.id === undefined)) {
return { kind: "diverged", reason: "A prompt has no provider id" };
}
if (owned.turns.length > provider.length) {
if (owned.prompts.length > provider.length) {
return { kind: "diverged", reason: "The provider history is missing turns Paseo shows" };
}
if (provider.some((turn, index) => index > 0 && turn.promptId === provider[index - 1].promptId)) {
if (provider.some((prompt, index) => index > 0 && prompt.id === provider[index - 1].id)) {
return { kind: "diverged", reason: "The provider history has two prompts with one id" };
}
const promptsDiffer = owned.turns.some(
(turn, index) =>
turn.promptId !== provider[index].promptId || turn.promptText !== provider[index].promptText,
);
if (promptsDiffer) {
if (owned.prompts.some((prompt, index) => !samePrompt(prompt, provider[index]))) {
return { kind: "diverged", reason: "The provider history has different prompts" };
}
const last = owned.turns.length - 1;
const earlierDiffers = owned.turns
.slice(0, Math.max(last, 0))
.some((turn, index) => !sameSegments(turn.segments, provider[index].segments));
if (earlierDiffers) {
return { kind: "diverged", reason: "The provider history has a different answer" };
}
let appendFrom: number;
if (last < 0) {
appendFrom = input.rows.length === 0 ? 0 : (provider[0]?.start ?? input.provider.length);
} else {
const from = continuationStart(owned.turns[last], provider[last]);
if (from === null) {
return { kind: "diverged", reason: "The provider history has a different last answer" };
}
appendFrom = from ?? provider[last + 1]?.start ?? input.provider.length;
}
const entries = input.provider.slice(appendFrom);
if (entries.length === 0) return { kind: "unchanged" };
const trailing = last >= 0 ? owned.turns[last] : owned.preamble;
if (trailing.hasUndeliveredPrompt) {
// Appending would put provider turns after a prompt the provider never received.
const next = provider[owned.prompts.length];
if (!next) return { kind: "unchanged" };
if (owned.trailingUndeliveredPrompt) {
return { kind: "diverged", reason: "A prompt the provider did not receive is last" };
}
return { kind: "append", entries };
return { kind: "append", entries: input.provider.slice(next.start) };
}
/**
* Where the provider's last-turn entries continue past the owned turn: an entry index, undefined
* when the turns are equal, or null when the owned turn is not a whole-segment prefix of the
* provider's. Appended entries must not update a segment Paseo already shows, such as a later
* update to a tool call.
*/
function continuationStart(owned: OwnedTurn, provider: ProviderTurn): number | undefined | null {
const matched = owned.segments.length;
if (!sameSegments(owned.segments, provider.segments.slice(0, matched))) return null;
if (matched === provider.segments.length) return undefined;
const from = provider.segmentStarts[matched];
const matchedEnd = Math.max(provider.start, ...provider.segmentEnds.slice(0, matched));
return matchedEnd < from ? from : null;
}
function ownedTurns(
function ownedPrompts(
rows: readonly ProjectedTimelineRow[],
prompts: readonly TimelinePrompt[],
): { preamble: OwnedTurn; turns: OwnedTurn[] } {
): { prompts: Prompt[]; trailingUndeliveredPrompt: boolean } {
const promptsBySeq = new Map(prompts.map((prompt) => [prompt.seqStart, prompt]));
const preamble: OwnedTurn = {
promptId: undefined,
promptText: "",
segments: [],
hasUndeliveredPrompt: false,
};
const turns: OwnedTurn[] = [];
let current = preamble;
const acknowledged: Prompt[] = [];
let trailingUndeliveredPrompt = false;
for (const row of rows) {
const prompt = row.item.type === "user_message" ? promptsBySeq.get(row.seqStart) : undefined;
if (
prompt &&
row.item.type === "user_message" &&
(!prompt.submitted || prompt.providerMessageId)
) {
current = {
promptId: prompt.providerMessageId ?? prompt.messageId,
promptText: row.item.text,
segments: [],
hasUndeliveredPrompt: false,
};
turns.push(current);
} else if (prompt) {
current.hasUndeliveredPrompt = true;
} else {
addToSegments(current.segments, row.item);
if (row.item.type !== "user_message") continue;
const prompt = promptsBySeq.get(row.seqStart);
if (!prompt) continue;
trailingUndeliveredPrompt = prompt.submitted && !prompt.providerMessageId;
if (!trailingUndeliveredPrompt) {
acknowledged.push({ id: prompt.providerMessageId ?? prompt.messageId, text: row.item.text });
}
}
return { preamble, turns };
return { prompts: acknowledged, trailingUndeliveredPrompt };
}
function providerTurns(entries: readonly TimelineEntry[]): ProviderTurn[] {
const turns: ProviderTurn[] = [];
entries.forEach((entry, index) => {
const current = turns.at(-1);
if (entry.item.type === "user_message") {
// Some providers replay a prompt twice in a row; it is one turn. The same id with other
// text opens its own turn, which the plan reports as divergence.
const repeated =
entry.item.messageId !== undefined &&
current?.promptId === entry.item.messageId &&
current.promptText === entry.item.text;
if (!repeated) {
turns.push({
promptId: entry.item.messageId,
promptText: entry.item.text,
segments: [],
start: index,
segmentStarts: [],
segmentEnds: [],
});
}
return;
}
if (!current) return;
const segment = addToSegments(current.segments, entry.item);
if (segment === null) return;
if (segment === current.segmentStarts.length) current.segmentStarts.push(index);
current.segmentEnds[segment] = index;
function providerPrompts(entries: readonly TimelineEntry[]): ProviderPrompt[] {
const prompts: ProviderPrompt[] = [];
entries.forEach(({ item }, start) => {
if (item.type !== "user_message") return;
const prompt = { id: item.messageId, text: item.text, start };
const previous = prompts.at(-1);
// Some providers replay a prompt twice. Reusing an ID for different text is a mismatch.
if (previous && prompt.id !== undefined && samePrompt(prompt, previous)) return;
prompts.push(prompt);
});
return turns;
return prompts;
}
/** Adds an item to its turn's segments; returns the segment's index, or null if not compared. */
function addToSegments(segments: Segment[], item: AgentTimelineItem): number | null {
const previous = segments.at(-1);
switch (item.type) {
case "assistant_message":
case "reasoning": {
const kind = item.type === "assistant_message" ? "text" : "reasoning";
if (previous?.kind === kind) {
previous.text += item.text;
} else {
segments.push({ kind, text: item.text });
}
return segments.length - 1;
}
case "tool_call": {
// Live status rows stay in the timeline but have no counterpart in provider history.
if (item.metadata?.liveOnly === true) return null;
const index = segments.findIndex(
(segment) => segment.kind === "tool_call" && segment.item.callId === item.callId,
);
const existing = segments[index];
if (existing?.kind !== "tool_call") {
segments.push({ kind: "tool_call", item });
return segments.length - 1;
}
existing.item = mergeToolCallItems(existing.item, item);
return index;
}
case "user_message":
case "error":
case "notification":
case "plugin":
case "compaction":
case "todo":
return null;
}
}
function sameSegments(a: readonly Segment[], b: readonly Segment[]): boolean {
return a.length === b.length && a.every((segment, index) => sameSegment(segment, b[index]));
}
function sameSegment(a: Segment, b: Segment): boolean {
if (a.kind === "tool_call" || b.kind === "tool_call") {
return (
a.kind === "tool_call" &&
b.kind === "tool_call" &&
sameValue(toolCallContent(a.item), toolCallContent(b.item))
);
}
return a.kind === b.kind && a.text === b.text;
}
function toolCallContent(item: ToolCallItem): unknown {
return {
callId: item.callId,
name: item.name,
status: item.status,
error: item.error,
detail: item.detail,
};
}
/** Structural equality: object key order and absent-versus-undefined keys are not content. */
function sameValue(a: unknown, b: unknown): boolean {
if (a === b) return true;
if (Array.isArray(a) || Array.isArray(b)) {
return (
Array.isArray(a) &&
Array.isArray(b) &&
a.length === b.length &&
a.every((value, index) => sameValue(value, b[index]))
);
}
if (!isRecord(a) || !isRecord(b)) return false;
const aKeys = definedKeys(a);
const bKeys = definedKeys(b);
return aKeys.length === bKeys.length && aKeys.every((key) => sameValue(a[key], b[key]));
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function definedKeys(value: Record<string, unknown>): string[] {
return Object.keys(value).filter((key) => value[key] !== undefined);
function samePrompt(a: Prompt, b: Prompt): boolean {
return a.id === b.id && a.text === b.text;
}
@@ -176,7 +176,7 @@ describe("daemon E2E - Reload agent brings in what the on-disk session added", (
expect(again.entries).toEqual(after.entries);
}, 30_000);
test("Reload agent reports an external edit to an earlier answer and keeps the history", async () => {
test("Reload agent reports an external edit to an earlier prompt and keeps the history", async () => {
const logger = pino({ level: "silent" });
daemon = await createTestPaseoDaemon({
agentClients: {
@@ -197,10 +197,10 @@ describe("daemon E2E - Reload agent brings in what the on-disk session added", (
projection: "canonical",
});
// The session file now holds a different first answer, with only its spacing changed.
// The session file now holds a different first prompt, with only its spacing changed.
const edited: ClaudeJsonlEntry[] = [
userEntry(sessionId, cwd, "first hello", "user-uuid-1"),
assistantEntry(sessionId, cwd, "first reply"),
userEntry(sessionId, cwd, "first hello", "user-uuid-1"),
assistantEntry(sessionId, cwd, "first reply"),
userEntry(sessionId, cwd, "second hello", "user-uuid-2"),
assistantEntry(sessionId, cwd, "second reply"),
];