fix(timeline): commit confirmed plugin rewind cuts and stream reload turn metrics

Preserve the confirmed at_target cut via RewindAppliedError when plugin session replay fails after session.revert succeeds, so reloading recovers even a first-message rewind. Carry turnMetrics on live timeline events appended by Reload agent so open chats match fresh timeline pages. Fix three async-timeline timing expectations in mcp-server and codex-async-questions tests.
This commit is contained in:
Mohamed Boudra
2026-11-24 09:18:19 +01:00
parent 2789421fbd
commit b7af3da71f
10 changed files with 143 additions and 25 deletions
@@ -5093,4 +5093,30 @@ describe("turn metrics", () => {
expect(repeated.tail).toBe(first.tail);
});
it("stamps turn metrics carried on a live timeline event appended by reload", () => {
const result = processAgentStreamEvents({
events: [
makeStreamReducerEvent(makeTimelineEvent("question", "user_message"), 1),
makeStreamReducerEvent(
{
type: "timeline",
provider: "claude",
item: { type: "assistant_message", text: "Appended reply." },
turnMetrics: metrics,
},
2,
),
],
currentTail: [],
currentHead: [],
currentCursor: { epoch: "epoch-1", startSeq: 0, endSeq: 0 },
hasAuthoritativeBaseline: true,
});
expect(metricsByKind([...result.tail, ...result.head])).toEqual([
{ kind: "user_message", turnMetrics: undefined },
{ kind: "assistant_message", turnMetrics: metrics },
]);
});
});
+4 -1
View File
@@ -1671,7 +1671,10 @@ export function reduceStreamUpdate(
),
event,
);
return event.item.type === "reasoning" ? updated : finalizeActiveThoughts(updated);
const stamped = event.turnMetrics?.length
? stampCompletedTurnMetrics(updated, event.turnMetrics, event.turnId)
: updated;
return event.item.type === "reasoning" ? stamped : finalizeActiveThoughts(stamped);
}
case "turn_completed":
return stampCompletedTurnMetrics(finalizeActiveThoughts(state), event.metrics, event.turnId);
+1
View File
@@ -856,6 +856,7 @@ export const AgentStreamEventPayloadSchema = z.discriminatedUnion("type", [
provider: AgentProviderSchema,
item: AgentTimelineItemPayloadSchema,
turnId: z.string().optional(),
turnMetrics: z.array(AgentMetricSchema).optional(),
}),
z.object({
type: z.literal("permission_requested"),
@@ -14058,8 +14058,17 @@ test.each(["first load", "reconcile"])(
{ workspaceId: undefined },
);
const events: AgentManagerEvent[] = [];
manager.subscribe((event) => events.push(event), { agentId: agent.id, replayState: false });
if (path === "reconcile") {
await manager.reconcileProviderHistory(agent.id);
const streamedMetrics = events.flatMap((event) =>
event.type === "agent_stream" && event.event.type === "timeline"
? [event.event.turnMetrics ?? null]
: [],
);
expect(streamedMetrics).toEqual([null, first, null, second, null, null]);
}
expect(
@@ -64,6 +64,7 @@ import {
type ImportedTimelineEntry,
type ImportableProviderSession,
type ListImportableSessionsOptions,
RewindAppliedError,
RewindNotAppliedError,
} from "./agent-sdk-types.js";
import { buildArchivedAgentRecord, type ArchivedStoredAgentRecord } from "./agent-archive.js";
@@ -795,7 +796,12 @@ function toTimelineEntry(event: Extract<AgentStreamEvent, { type: "timeline" }>)
/** The live event that publishes a row committed from provider history. */
function historyEvent(provider: AgentProvider, commit: TimelineCommit): AgentStreamEvent {
return { type: "timeline", provider, item: commit.row.item };
return {
type: "timeline",
provider,
item: commit.row.item,
...(commit.row.turnMetrics ? { turnMetrics: commit.row.turnMetrics } : {}),
};
}
function projectImportedTimelineEntries(
@@ -4357,10 +4363,16 @@ export class AgentManager {
mode: target.mode,
})) ?? { kind: "at_target" };
} catch (error) {
if (!(error instanceof RewindNotAppliedError))
throw new RewindOutcomeUnknownError({ cause: error });
await this.timeline.abandonRewind(scope, intent.id);
throw error;
if (error instanceof RewindNotAppliedError) {
await this.timeline.abandonRewind(scope, intent.id);
throw error;
}
if (error instanceof RewindAppliedError) {
await this.timeline.recordRewindCut(scope, intent.id, error.cut);
await this.completeRewind(agent, intent.id);
throw error.cause ?? error;
}
throw new RewindOutcomeUnknownError({ cause: error });
}
if (result.kind === "unreported") {
await this.persistRewoundSession(agent);
@@ -471,6 +471,7 @@ export type AgentStreamEvent =
provider: AgentProvider;
turnId?: string;
timestamp?: string;
turnMetrics?: AgentMetric[];
}
| {
type: "permission_requested";
@@ -670,6 +671,28 @@ export class RewindNotAppliedError extends Error {
}
}
/**
* The provider applied the rewind with a known cut, then failed while refreshing its local
* session state. Paseo commits the confirmed cut and lets Reload reopen the session.
*/
export class RewindAppliedError extends Error {
constructor(
readonly cut: ConversationRewindCut,
message: string,
options?: { cause?: unknown },
) {
super(message, options);
this.name = "RewindAppliedError";
}
static from(cut: ConversationRewindCut, error: unknown): RewindAppliedError {
if (error instanceof RewindAppliedError) return error;
return new RewindAppliedError(cut, error instanceof Error ? error.message : String(error), {
cause: error,
});
}
}
export interface AgentSessionConfig {
provider: AgentProvider;
cwd: string;
@@ -4803,7 +4803,9 @@ describe("message order for one recipient", () => {
}
/** Everything the queue will deliver without a new prompt has been delivered. */
async function settled(): Promise<void> {
await agentManager.flush();
await delivery.waitForDispatch(recipient.id, new AbortController().signal);
await agentManager.flush();
expect(delivery.hasPending(recipient.id)).toBe(false);
}
/** Resolves when the message is queued; a steer or an interrupt by default when it is dispatched. */
@@ -4909,7 +4911,7 @@ describe("message order for one recipient", () => {
{ from: recipient.senderId, text: "Go ahead and cut the release" },
{ from: "person", text: "Pause the release" },
]);
const rows = recipient.agentManager.getTimeline(recipient.recipientId);
const rows = await recipient.agentManager.getTimeline(recipient.recipientId);
expect(rows.flatMap((row) => (row.type === "user_message" ? [row.text] : []))).toEqual([
"Pause the release",
]);
@@ -18,7 +18,6 @@ import { sendPreparedPromptToAgent } from "./agent-prompt.js";
import { setImmediate as nextTurn } from "node:timers/promises";
import { describe, expect, test } from "vitest";
import { createTestLogger } from "../../test-utils/test-logger.js";
import { RewindOutcomeUnknownError } from "./rewind/rewind.js";
import {
RewindNotAppliedError,
type AgentClient,
@@ -846,22 +845,24 @@ test("failed plugin rewind replay blocks prompts until retry without repeating n
);
});
test("a failed plugin rewind replay blocks prompts until a reload settles the committed rewind", async () => {
test("a failed plugin rewind replay blocks prompts until reload reopens the rewound session", async () => {
let failReplay = true;
await withRewindAgent(
async ({ manager, agentId, messages }) => {
// The native revert committed, but the session could not replay what it kept.
await expect(manager.rewind(agentId, "client-B", "conversation")).rejects.toMatchObject({
name: "RewindOutcomeUnknownError",
cause: { message: "replay failed" },
});
await expect(manager.runAgent(agentId, "D")).rejects.toBeInstanceOf(
RewindOutcomeUnknownError,
// The native revert committed at target, then reopening the session for replay failed.
await expect(manager.rewind(agentId, "client-B", "conversation")).rejects.toThrow(
"replay failed",
);
await manager.reloadAgentSession(agentId);
expect(await messages()).toEqual(["A", "Reply A"]);
await expect(manager.runAgent(agentId, "D")).rejects.toThrow("Retry the rewind or reload");
await manager.reloadAgentSession(agentId);
await manager.runAgent(agentId, "D");
expect(await messages()).toEqual(["A", "Reply A", "D", "Reply D"]);
expect((await messages()).filter((text) => !text.startsWith("[System Error]"))).toEqual([
"A",
"Reply A",
"D",
"Reply D",
]);
},
{
handleInput: async (input, emit) => {
@@ -883,10 +884,9 @@ test("reload after failed plugin rewind replay resumes the committed fork", asyn
let failReplay = true;
await withRewindAgent(
async ({ manager, agentId, messages }) => {
await expect(manager.rewind(agentId, "client-B", "conversation")).rejects.toMatchObject({
name: "RewindOutcomeUnknownError",
cause: { message: "replay failed" },
});
await expect(manager.rewind(agentId, "client-B", "conversation")).rejects.toThrow(
"replay failed",
);
await manager.reloadAgentSession(agentId, undefined, { rehydrateFromDisk: true });
expect(await messages()).toEqual(["A", "Reply A"]);
},
@@ -920,6 +920,38 @@ test("rewinding a plugin agent to its first prompt empties the chat and accepts
});
});
test("a failed replay after rewinding the first prompt still recovers on reload", async () => {
let failReplay = true;
await withRewindAgent(
async ({ manager, agentId, messages }) => {
await expect(manager.rewind(agentId, "client-A", "conversation")).rejects.toThrow(
"replay failed",
);
expect(await messages()).toEqual([]);
await expect(manager.runAgent(agentId, "D")).rejects.toThrow("Retry the rewind or reload");
await manager.reloadAgentSession(agentId);
await manager.runAgent(agentId, "D");
expect((await messages()).filter((text) => !text.startsWith("[System Error]"))).toEqual([
"D",
"Reply D",
]);
},
{
handleInput: async (input, emit) => {
if (input.type !== "session.open" || input.history !== "replay" || !failReplay)
return false;
failReplay = false;
emit({
type: "request.failed",
requestId: input.requestId,
error: { message: "replay failed" },
});
return true;
},
},
);
});
test("closing during plugin rewind replay closes each native binding once", async () => {
let opened!: () => void;
let release!: () => void;
@@ -69,7 +69,7 @@ import type {
AgentClientDiagnosticContext,
ConversationRewindCut,
} from "./agent-sdk-types.js";
import { RewindNotAppliedError } from "./agent-sdk-types.js";
import { RewindAppliedError, RewindNotAppliedError } from "./agent-sdk-types.js";
import {
resolveProviderLaunch,
checkProviderLaunchAvailable,
@@ -2059,10 +2059,17 @@ class PluginAgentSession implements AgentSession {
scope,
});
if (scope !== "files") {
const cut: ConversationRewindCut = { kind: "at_target" };
const persistence = this.bridge.persistence;
if (!persistence) throw new Error("Plugin rewind removed session persistence");
if (!persistence) {
throw RewindAppliedError.from(cut, new Error("Plugin rewind removed session persistence"));
}
this.replay = { persistence, config: this.bridge.config, messageId, scope, closed: false };
await this.ensureReplay();
try {
await this.ensureReplay();
} catch (error) {
throw RewindAppliedError.from(cut, error);
}
}
}
@@ -241,6 +241,7 @@ test("manager snapshots capture pending and answered question state before the t
const { manager, agent } = await manage(session);
try {
await ask();
await manager.flush();
const [permission] = session.getPendingPermissions();
expect(manager.getAgent(agent.id)?.persistence?.metadata?.asyncQuestions).toEqual([
{
@@ -274,6 +275,7 @@ test("concurrent answers deliver only one response to the active Codex turn", as
const { manager, agent } = await manage(session);
try {
await ask();
await manager.flush();
const [permission] = session.getPendingPermissions();
const results = await Promise.allSettled([
manager.respondToPermission(agent.id, permission.id, answer),
@@ -294,6 +296,7 @@ test("a failed submission releases the request so the user can retry", async ()
const { manager, agent } = await manage(session);
try {
await ask();
await manager.flush();
const [permission] = session.getPendingPermissions();
await expect(manager.respondToPermission(agent.id, permission.id, answer)).rejects.toThrow(
"Delivery failed",