Compare commits

..
Author SHA1 Message Date
Mohamed Boudra bf83a03ce9 fix(timeline): acknowledge replayed prompts with client IDs 2026-11-18 15:21:47 +01:00
18 changed files with 202 additions and 536 deletions
@@ -12,8 +12,6 @@ import { limitAgentTimelineItemContent } from "./agent-timeline-content.js";
import type { AgentTimelineRow } from "./agent-timeline-store-types.js";
import { projectTimelineRows } from "./timeline-projection.js";
import { AgentTimeline } from "./timeline/index.js";
import { OmpAgentClient } from "./providers/omp/agent.js";
import { FakeOmp } from "./providers/omp/test-utils/fake-omp.js";
import { DeferredTimelineBackend } from "./timeline/testing.js";
import type {
AgentCapabilityFlags,
@@ -426,213 +424,6 @@ afterEach(() => {
vi.useRealTimers();
});
describe("root live turn membership", () => {
test.each([
{ sequence: "while idle", agentStarted: false, emptyCycle: false },
{ sequence: "between agent_start and turn_start", agentStarted: true, emptyCycle: false },
{ sequence: "after an empty cycle", agentStarted: true, emptyCycle: true },
])(
"keeps OMP replies in separate turns with a notice $sequence",
async ({ agentStarted, emptyCycle }) => {
const runtime = new FakeOmp();
const provider = "omp";
const logger = createTestLogger();
const manager = new AgentManager({
clients: {
omp: new OmpAgentClient({
runtime,
logger,
runtimeSettings: { command: { mode: "replace", argv: [process.execPath] } },
}),
},
logger,
});
const workdir = mkdtempSync(join(tmpdir(), "omp-live-turns-"));
const events: AgentManagerEvent[] = [];
manager.subscribe((event) => events.push(event), { replayState: false });
const { id } = await manager.createAgent({ provider, cwd: workdir }, undefined, {
workspaceId: undefined,
});
try {
const session = runtime.latestSession();
const finishReply = async (text: string) => {
const completed = () =>
getStreamEvents(events, id).filter(
(event) => event.type === "agent_stream" && event.event.type === "turn_completed",
).length;
const before = completed();
session.streamAssistantText(text, text);
session.finishTurn({ role: "assistant", content: [] });
await vi.waitFor(() => {
expect(completed()).toBe(before + 1);
});
};
const notice = (message: string) => {
session.emit({ type: "extension_ui_request", id: message, method: "notify", message });
};
session.beginTurn();
await finishReply("First reply");
if (agentStarted) session.emit({ type: "agent_start" });
if (emptyCycle) session.emit({ type: "agent_end", messages: [] });
notice("Idle notice");
session.beginTurn();
session.acceptCustomMessage("<system-notice>Completion</system-notice>");
notice("Running notice");
await finishReply("Second reply");
const page = await manager.fetchTimeline(id, { wholeTurns: true, limit: 0 });
const ids = page.rows.map((row) => row.turnId);
expect(
page.rows.map(({ item }) => {
if (item.type === "assistant_message") return item.text;
if (item.type === "notification") return item.message;
return item.type;
}),
).toEqual(["First reply", "Idle notice", "Completion", "Running notice", "Second reply"]);
const [first, idle, wake] = ids;
expect(ids).toEqual([
expect.any(String),
expect.any(String),
expect.any(String),
wake,
wake,
]);
expect(new Set([first, idle, wake]).size).toBe(3);
expect(
getTimelineStreamEvents(events, id).map((event) =>
event.type === "agent_stream" && event.event.type === "timeline"
? event.event.turnId
: null,
),
).toEqual(ids);
expect(
(await manager.fetchTimeline(id, { wholeTurns: true, limit: 1 })).rows.map(
(row) => row.turnId,
),
).toEqual([wake, wake, wake]);
} finally {
await manager.closeAgent(id);
rmSync(workdir, { recursive: true, force: true });
}
},
);
test("keeps a Claude completion with the run it wakes after an independent notice", async () => {
const harness = createHarness({ provider: "claude" });
try {
const { agentId, session } = await createManagedSession(harness);
session.pushEvent(assistant("First reply", "claude", "first"));
session.pushEvent(
timelineEvent({ type: "notification", level: "info", message: "Idle" }, "claude"),
);
session.pushEvent(
timelineEvent(
{ type: "notification", level: "info", message: "Task finished" },
"claude",
"wake",
),
);
session.pushEvent({ type: "turn_started", provider: "claude", turnId: "wake" });
session.pushEvent(assistant("Second reply", "claude", "wake"));
session.pushEvent({ type: "turn_completed", provider: "claude", turnId: "wake" });
await vi.waitFor(() => {
expect(getStreamEvents(harness.events, agentId).at(-1)).toMatchObject({
event: { type: "turn_completed", turnId: "wake" },
});
});
const page = await harness.manager.fetchTimeline(agentId, { wholeTurns: true, limit: 0 });
expect(page.rows.map((row) => row.turnId)).toEqual([
"first",
expect.any(String),
"wake",
"wake",
]);
expect(page.rows[1]?.turnId).not.toBe("first");
expect(page.rows[1]?.turnId).not.toBe("wake");
expect(
(await harness.manager.fetchTimeline(agentId, { wholeTurns: true, limit: 1 })).rows.map(
(row) => row.item,
),
).toEqual([
{ type: "notification", level: "info", message: "Task finished" },
{ type: "assistant_message", text: "Second reply" },
]);
} finally {
harness.cleanup();
}
});
test("keeps adjacent idle text chunks together across coalescer windows", async () => {
vi.useFakeTimers();
const harness = createHarness();
try {
const { agentId, session } = await createManagedSession(harness);
session.pushEvent(assistant("one "));
session.pushEvent(assistant("two "));
await waitForSessionEventQueue();
await vi.advanceTimersByTimeAsync(COALESCE_WINDOW_MS);
session.pushEvent(assistant("three"));
session.pushEvent(
timelineEvent({ type: "notification", level: "info", message: "Independent notice" }),
);
session.pushEvent(assistant("another reply"));
await waitForSessionEventQueue();
await harness.manager.flush();
const rows = (await harness.manager.fetchTimeline(agentId, { wholeTurns: true, limit: 0 }))
.rows;
expect(getTimelineItems(rows)).toEqual([
{ type: "assistant_message", text: "one two three" },
{ type: "notification", level: "info", message: "Independent notice" },
{ type: "assistant_message", text: "another reply" },
]);
expect(rows.map((row) => row.turnId)).toEqual([
expect.any(String),
expect.any(String),
expect.any(String),
]);
expect(new Set(rows.map((row) => row.turnId)).size).toBe(3);
} finally {
harness.cleanup();
}
});
test("a late tool update keeps the turn where the tool started", async () => {
const harness = createHarness();
try {
const { agentId, session } = await createManagedSession(harness);
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "first" });
session.pushEvent(timelineEvent(toolCall()));
session.pushEvent(terminalEvent("turn_completed", "first"));
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "second" });
session.pushEvent(timelineEvent(toolCall({ status: "completed" }), "codex", "second"));
session.pushEvent(assistant("Second reply"));
session.pushEvent(terminalEvent("turn_completed", "second"));
await vi.waitFor(() => {
expect(getStreamEvents(harness.events, agentId).at(-1)).toMatchObject({
event: { type: "turn_completed", turnId: "second" },
});
});
const page = await harness.manager.fetchTimeline(agentId, { wholeTurns: true, limit: 0 });
expect(page.rows.map(({ turnId, item }) => ({ turnId, item }))).toEqual([
{ turnId: "first", item: { ...toolCall({ status: "completed" }), metadata: undefined } },
{ turnId: "second", item: { type: "assistant_message", text: "Second reply" } },
]);
expect(
getTimelineStreamEvents(harness.events, agentId).map((event) =>
event.type === "agent_stream" && event.event.type === "timeline"
? event.event.turnId
: null,
),
).toEqual(["first", "first", "second"]);
} finally {
harness.cleanup();
}
});
});
describe("target coalesced behavior", () => {
test("bounds tool output before persisting and streaming it", async () => {
const harness = createHarness();
@@ -742,7 +533,6 @@ describe("target coalesced behavior", () => {
const harness = createHarness();
try {
const { agentId, session } = await createManagedSession(harness);
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "streaming-turn" });
for (let i = 0; i < 1000; i++) {
session.pushEvent(assistant("x"));
@@ -769,13 +559,11 @@ describe("target coalesced behavior", () => {
{
type: "timeline",
provider: "codex",
turnId: "streaming-turn",
item: { type: "assistant_message", text: "x" },
},
{
type: "timeline",
provider: "codex",
turnId: "streaming-turn",
item: { type: "assistant_message", text: "x".repeat(999) },
},
]);
@@ -821,7 +609,6 @@ describe("target coalesced behavior", () => {
const harness = createHarness();
try {
const { agentId, session } = await createManagedSession(harness);
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "streaming-turn" });
const runningToolCall = toolCall({ output: "running" });
for (let i = 0; i < 500; i++) {
@@ -945,7 +732,6 @@ describe("target coalesced behavior", () => {
const harness = createHarness();
try {
const { agentId, session } = await createManagedSession(harness);
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "streaming-turn" });
session.pushEvent(assistant("before"));
session.pushEvent(timelineEvent(toolCall({ output: "running" })));
@@ -982,7 +768,6 @@ describe("target coalesced behavior", () => {
const harness = createHarness();
try {
const { agentId, session } = await createManagedSession(harness);
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "streaming-turn" });
session.pushEvent(assistant("a"));
session.pushEvent(timelineEvent(toolCall({ output: "first" })));
@@ -1014,7 +799,6 @@ describe("target coalesced behavior", () => {
const harness = createHarness();
try {
const { agentId, session } = await createManagedSession(harness);
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "streaming-turn" });
session.pushEvent(assistant("a1"));
session.pushEvent(reasoning("r1"));
@@ -1096,10 +880,10 @@ describe("target coalesced behavior", () => {
workdir: secondWorkdir,
});
first.session.pushEvent(assistant("a", "codex", "first"));
second.session.pushEvent(assistant("b", "codex", "second"));
first.session.pushEvent(assistant("a", "codex", "first"));
second.session.pushEvent(assistant("b", "codex", "second"));
first.session.pushEvent(assistant("a"));
second.session.pushEvent(assistant("b"));
first.session.pushEvent(assistant("a"));
second.session.pushEvent(assistant("b"));
await waitForSessionEventQueue();
await vi.advanceTimersByTimeAsync(COALESCE_WINDOW_MS);
@@ -1133,7 +917,6 @@ describe("target coalesced behavior", () => {
const harness = createHarness();
try {
const { agentId, session } = await createManagedSession(harness);
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "streaming-turn" });
session.pushEvent(assistant("codex", "codex"));
session.pushEvent(assistant("claude", "claude"));
@@ -1145,16 +928,10 @@ describe("target coalesced behavior", () => {
expect(getTimelineItems(rows)).toEqual([{ type: "assistant_message", text: "codexclaude" }]);
expect(events.map((event) => (event.type === "agent_stream" ? event.event : null))).toEqual([
{
type: "timeline",
provider: "codex",
turnId: "streaming-turn",
item: { type: "assistant_message", text: "codex" },
},
{ type: "timeline", provider: "codex", item: { type: "assistant_message", text: "codex" } },
{
type: "timeline",
provider: "claude",
turnId: "streaming-turn",
item: { type: "assistant_message", text: "claude" },
},
]);
@@ -1479,7 +1256,6 @@ describe("target coalesced behavior", () => {
const idempotencyHarness = createHarness();
try {
const { agentId, session } = await createManagedSession(idempotencyHarness);
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "streaming-turn" });
session.pushEvent(assistant("a"));
session.pushEvent(assistant("b"));
@@ -1509,7 +1285,6 @@ describe("target coalesced behavior", () => {
const reentryHarness = createHarness();
try {
const { agentId, session } = await createManagedSession(reentryHarness);
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "streaming-turn" });
let didPushDuringFlush = false;
reentryHarness.manager.subscribe(
(event) => {
@@ -1561,7 +1336,6 @@ describe("target coalesced behavior", () => {
const harness = createHarness();
try {
const { agentId, session } = await createManagedSession(harness);
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "streaming-turn" });
session.pushEvent(assistant("flush"));
session.pushEvent(assistant("-pending"));
@@ -800,10 +800,7 @@ test("a subscriber that throws on publication leaves the committed item in histo
await expect(
manager.appendTimelineItem(agent.id, { type: "assistant_message", text: " and next" }),
).resolves.toMatchObject({ seq: 2 });
expect(await manager.getTimeline(agent.id)).toEqual([
{ type: "assistant_message", text: "kept" },
{ type: "assistant_message", text: " and next" },
]);
expect(await manager.getLastAssistantMessage(agent.id)).toBe("kept and next");
expect(logs).toContainEqual(
expect.objectContaining({
msg: "Failed to publish committed timeline item",
@@ -7209,13 +7206,17 @@ test("getTimelineRows falls back to the in-memory timeline when no durable store
text: "row two",
});
const rows = await manager.getTimelineRows(snapshot.id);
expect(rows.map(({ seq, item }) => ({ seq, item }))).toEqual([
{ seq: 1, item: { type: "assistant_message", text: "row one" } },
{ seq: 2, item: { type: "assistant_message", text: "row two" } },
await expect(manager.getTimelineRows(snapshot.id)).resolves.toEqual([
{
seq: 2,
seqStart: 1,
seqEnd: 2,
sourceSeqRanges: [{ startSeq: 1, endSeq: 2 }],
collapsed: ["assistant_merge"],
timestamp: expect.any(String),
item: { type: "assistant_message", text: "row onerow two" },
},
]);
expect(rows.map((row) => row.turnId)).toEqual([expect.any(String), expect.any(String)]);
expect(rows[0]?.turnId).not.toBe(rows[1]?.turnId);
});
test("getAgent does not expose committed history internals once manager owns the seam", async () => {
@@ -9966,17 +9967,7 @@ test("streamAgent clears pending run when startTurn fails before a turn id exist
clientMessageId: "rejected-prompt",
messageId: "rejected-prompt",
},
{
type: "assistant_message",
text: "[System Error] Invalid request: missing field `text`",
messageId: expect.any(String),
},
]);
const rejectedRows = await manager.getTimelineRows(agent.id);
expect(rejectedRows.map((row) => row.turnId)).toEqual([
expect.any(String),
rejectedRows[0]?.turnId,
{ type: "assistant_message", text: "[System Error] Invalid request: missing field `text`" },
]);
await expect(manager.runAgent(agent.id, "second turn")).resolves.toEqual(
@@ -13236,7 +13227,6 @@ test("authoritative timeline records a daemon-handled submitted prompt before it
const timeline = (await manager.fetchTimeline(snapshot.id, { direction: "tail", limit: 20 }))
.rows;
expect(timeline.map((row) => row.turnId)).toEqual([expect.any(String), timeline[0]?.turnId]);
expect(timeline.map((row) => row.item)).toEqual([
{
type: "user_message",
+112 -165
View File
@@ -499,7 +499,6 @@ type ActiveTurnTerminalDisposition = "closed_current" | "stale" | "untracked";
interface HandleStreamEventOptions {
fromHistory?: boolean;
displayTurnId?: string;
}
interface ManagedAgentBase {
@@ -625,9 +624,9 @@ type AgentMetadata = Record<string, JsonValue>;
function attachManagedTurnIdentity(
agent: ActiveManagedAgent,
event: Exclude<AgentStreamEvent, { type: "timeline" }>,
event: AgentStreamEvent,
fromHistory: boolean,
): { event: Exclude<AgentStreamEvent, { type: "timeline" }>; turnId: string | undefined } {
): { event: AgentStreamEvent; turnId: string | undefined } {
const existingTurnId = getAgentStreamEventTurnId(event);
if (fromHistory || existingTurnId !== undefined) {
return { event, turnId: existingTurnId };
@@ -644,6 +643,12 @@ function attachManagedTurnIdentity(
const turnId = agent.activeForegroundTurnId ?? agent.activeTurnId ?? undefined;
return turnId ? { event: { ...event, turnId }, turnId } : { event, turnId };
}
case "timeline": {
// Live provider items belong to the foreground turn that owns their dispatch.
// Provider history deliberately keeps absent IDs because it has no daemon turn identity.
const turnId = agent.activeForegroundTurnId ?? agent.activeTurnId ?? undefined;
return turnId ? { event: { ...event, turnId }, turnId } : { event, turnId };
}
default:
return { event, turnId: undefined };
}
@@ -814,6 +819,9 @@ function buildImportedTimelineRows(entries: readonly ImportedTimelineEntry[]): A
seq: rows.length + 1,
timestamp: entry.timestamp ?? new Date().toISOString(),
item: limitAgentTimelineItemContent(item),
...(item.type === "user_message" && item.clientMessageId && item.messageId
? { providerMessageId: item.messageId }
: {}),
});
}
}
@@ -923,10 +931,6 @@ export class AgentManager {
>();
private readonly collectingRuntimes = new Set<string>();
private readonly lifecycleMutationTails = new Map<string, Promise<void>>();
private readonly idleTextTurns = new WeakMap<
ActiveManagedAgent,
{ turnId: string; messageId?: string }
>();
private readonly agentStreamCoalescer: AgentStreamCoalescer;
private mcpBaseUrl: string | null;
private readonly mcpAuthToken: string | null;
@@ -977,7 +981,7 @@ export class AgentManager {
onFlush: ({ agentId, item, provider, turnId }) => {
this.trackTimelineWrite(
agentId,
this.recordAndDispatchTimelineItem(agentId, item, provider, turnId ?? randomUUID(), {
this.recordAndDispatchTimelineItem(agentId, item, provider, turnId, {
notifyWaiters: true,
}),
);
@@ -3186,51 +3190,46 @@ export class AgentManager {
return false;
}
onAccepted?.();
await new Promise<void>((promptRecorded, reject) => {
void this.runForegroundMutation(agentId, async () => {
const turnId = this.liveTurnId(agent);
this.touchUpdatedAt(agent);
if (options?.clientMessageId) {
await this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "accepted");
this.emitState(agent);
}
const scope: TimelineScope = { agentId: agent.id };
const dispatch = (event: AgentStreamEvent): void => {
// Persist timeline items so they show up in fetchAgentTimeline; broadcast
// for live subscribers. Other event types are broadcast only, after the
// timeline items emitted before them.
if (event.type === "timeline") {
this.touchUpdatedAt(agent);
if (options?.clientMessageId) {
await this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "accepted", {
turnId,
});
this.emitState(agent);
}
promptRecorded();
const scope: TimelineScope = { agentId: agent.id };
const dispatch = (event: AgentStreamEvent): void => {
if (event.type === "timeline") {
this.touchUpdatedAt(agent);
this.trackTimelineWrite(
agent.id,
this.recordAndDispatchTimelineItem(
agent.id,
limitAgentTimelineItemContent(event.item),
event.provider,
event.turnId ?? turnId,
),
);
return;
}
const timestamp = new Date().toISOString();
const publish = (async () => {
await this.timeline.settled(scope);
this.dispatchStream(agent.id, event, { timestamp });
})();
this.trackTimelineWrite(agent.id, publish);
};
try {
await handler.run({ emit: dispatch, turnId });
} catch (error) {
const text = error instanceof Error ? error.message : "Out-of-band command failed";
dispatch({
type: "timeline",
provider: agent.provider,
item: { type: "assistant_message", text: `[Error] ${text}` },
});
}
}).catch(reject);
const write = this.timeline
.ingest(
scope,
{ item: event.item },
{ publish: (commit) => this.publishTimelineEvent(agent.id, event, commit) },
)
.then((result) => this.reportUnpublished(agent.id, result));
this.trackTimelineWrite(agent.id, write);
return;
}
const timestamp = new Date().toISOString();
const publish = (async () => {
await this.timeline.settled(scope);
this.dispatchStream(agent.id, event, { timestamp });
})();
this.trackTimelineWrite(agent.id, publish);
};
void this.runForegroundMutation(agentId, async () => {
try {
await handler.run({ emit: dispatch });
} catch (error) {
const text = error instanceof Error ? error.message : "Out-of-band command failed";
dispatch({
type: "timeline",
provider: agent.provider,
item: { type: "assistant_message", text: `[Error] ${text}` },
});
}
});
return true;
}
@@ -3242,11 +3241,16 @@ export class AgentManager {
const agent = this.requireAgent(agentId);
item = limitAgentTimelineItemContent(item);
this.touchUpdatedAt(agent);
const turnId = this.liveTurnId(agent);
const result = await this.recordAndDispatchTimelineItem(agentId, item, agent.provider, turnId);
const event: AgentStreamEvent = { type: "timeline", item, provider: agent.provider };
const result = await this.timeline.ingest(
{ agentId },
{ item },
{ publish: (commit) => this.publishTimelineEvent(agentId, event, commit) },
);
if (result.kind === "dropped") {
throw new Error("Timeline item belongs to a rewound turn");
}
this.reportUnpublished(agentId, result);
await this.persistSnapshot(agent);
return { seq: result.row.seq, epoch: result.epoch, retirementCount: result.retirementCount };
}
@@ -3258,7 +3262,6 @@ export class AgentManager {
type: "timeline",
item,
provider: agent.provider,
turnId: this.liveTurnId(agent),
});
}
@@ -3315,22 +3318,16 @@ export class AgentManager {
this.runs.settleForegroundStart(pendingRun, { status: "failed", error: errorMsg });
try {
// A terminal rejection belongs after the submitted prompt even though no provider turn exists.
const turnId = randomUUID();
if (options?.clientMessageId) {
await this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "rejected", {
messageId: options.clientMessageId,
turnId,
});
}
await this.handleStreamEvent(
agent,
{
type: "turn_failed",
provider: agent.provider,
error: errorMsg,
},
{ displayTurnId: turnId },
);
await this.handleStreamEvent(agent, {
type: "turn_failed",
provider: agent.provider,
error: errorMsg,
});
this.finalizeForegroundTurn(agent);
} finally {
// A steer waiting on this start is released only once the run is cleared.
@@ -3597,7 +3594,6 @@ export class AgentManager {
}
private openActiveTurn(agent: ActiveManagedAgent, turnId: string, startedAt: Date): void {
this.idleTextTurns.delete(agent);
agent.activeTurnId = turnId;
agent.activeTurnStartedAt = startedAt;
}
@@ -4683,6 +4679,7 @@ export class AgentManager {
buildImportedTimelineRows(session.initialTimeline).map((row) => ({
item: row.item,
timestamp: row.timestamp,
providerMessageId: row.providerMessageId,
})),
);
}
@@ -5062,10 +5059,7 @@ export class AgentManager {
return;
}
const turnId = getAgentStreamEventTurnId(event);
const matchingWaiters = this.runs.getMatchingWaiters(
agent,
event.type === "timeline" ? (turnId ?? agent.activeForegroundTurnId ?? undefined) : turnId,
);
const matchingWaiters = this.runs.getMatchingWaiters(agent, turnId);
this.logger.trace(
{
agentId: agent.id,
@@ -5078,13 +5072,7 @@ export class AgentManager {
"agent.manager.dispatch_session_event",
);
const shouldNotifyWaiters =
event.type === "timeline"
? await this.onLiveTimelineEvent(agent, {
...event,
item: limitAgentTimelineItemContent(event.item),
})
: await this.handleStreamEvent(agent, event);
const shouldNotifyWaiters = await this.handleStreamEvent(agent, event);
if (!shouldNotifyWaiters) {
return;
@@ -5238,14 +5226,13 @@ export class AgentManager {
private async handleStreamEvent(
agent: ActiveManagedAgent,
sourceEvent: Exclude<AgentStreamEvent, { type: "timeline" }>,
event: AgentStreamEvent,
options?: HandleStreamEventOptions,
): Promise<boolean> {
const { event, turnId: eventTurnId } = attachManagedTurnIdentity(
agent,
sourceEvent,
options?.fromHistory === true,
);
event = limitAgentStreamEventContent(event);
const identified = attachManagedTurnIdentity(agent, event, options?.fromHistory === true);
event = identified.event;
const eventTurnId = identified.turnId;
const isForegroundEvent = agent.activeForegroundTurnId === eventTurnId;
this.traceHandleStreamEventStart(agent, event, eventTurnId, isForegroundEvent);
if (
@@ -5260,6 +5247,10 @@ export class AgentManager {
// Only update timestamp for live events, not history replay
if (!options?.fromHistory) {
this.touchUpdatedAt(agent);
if (this.agentStreamCoalescer.handle(agent.id, event)) {
this.traceCoalescerBuffered(agent, event, eventTurnId);
return false;
}
this.agentStreamCoalescer.flushFor(agent.id);
// A flushed chunk is committed and published before this event, e.g. a terminal status.
await this.timeline.settled({ agentId: agent.id });
@@ -5384,7 +5375,7 @@ export class AgentManager {
private dispatchStreamEventByType(params: {
agent: ActiveManagedAgent;
event: Exclude<AgentStreamEvent, { type: "timeline" }>;
event: AgentStreamEvent;
options: HandleStreamEventOptions | undefined;
isForegroundEvent: boolean;
eventTurnId: string | undefined;
@@ -5436,6 +5427,8 @@ export class AgentManager {
case "options_changed":
this.onStreamOptionsChanged({ agent, patch: event.patch, flags });
return undefined;
case "timeline":
return this.onStreamTimelineEvent({ agent, event, options, flags });
case "turn_completed":
this.onStreamTurnCompleted({
agent,
@@ -5494,43 +5487,36 @@ export class AgentManager {
}
}
private async onLiveTimelineEvent(
agent: ActiveManagedAgent,
event: Extract<AgentStreamEvent, { type: "timeline" }>,
): Promise<boolean> {
const turnId = this.assignLiveTurn(agent, event.turnId, event.item);
const liveEvent = { ...event, turnId };
this.touchUpdatedAt(agent);
if (this.agentStreamCoalescer.handle(agent.id, liveEvent)) {
this.traceCoalescerBuffered(agent, event, turnId ?? undefined);
return false;
}
this.agentStreamCoalescer.flushFor(agent.id);
await this.timeline.settled({ agentId: agent.id });
private async onStreamTimelineEvent(params: {
agent: ActiveManagedAgent;
event: Extract<AgentStreamEvent, { type: "timeline" }>;
options: { fromHistory?: boolean } | undefined;
flags: StreamEventFlags;
}): Promise<void> {
const { agent, event, options, flags } = params;
const resolvedTurnId = turnId ?? randomUUID();
let notifyWaiters = false;
flags.shouldDispatchEvent = false;
flags.shouldNotifyWaiters = false;
for (const item of projectAgentMessages(event.item)) {
if (
item.type === "user_message" &&
item.clientMessageId &&
(await this.reconcileSubmittedPromptEcho(agent, item, resolvedTurnId))
(await this.reconcileSubmittedPromptEcho(agent, item, event.turnId))
)
continue;
const result = await this.recordAndDispatchTimelineItem(
agent.id,
item,
event.provider,
resolvedTurnId,
);
if (result.kind === "dropped") continue;
if (options?.fromHistory) {
await this.timeline.append({ agentId: agent.id }, [toTimelineEntry({ ...event, item })]);
continue;
}
await this.recordAndDispatchTimelineItem(agent.id, item, event.provider, event.turnId);
if (item.type === "user_message") {
agent.lastUserMessageAt = new Date();
this.emitState(agent);
}
notifyWaiters = true;
flags.shouldNotifyWaiters = true;
}
return notifyWaiters;
}
private onStreamTurnCompleted(params: {
@@ -5577,7 +5563,7 @@ export class AgentManager {
eventTurnId: string | undefined;
isForegroundEvent: boolean;
terminalDisposition: ActiveTurnTerminalDisposition;
options: HandleStreamEventOptions | undefined;
options: { fromHistory?: boolean } | undefined;
}): Promise<void> {
const { agent, event, eventTurnId, isForegroundEvent, terminalDisposition, options } = params;
this.logger.warn(
@@ -5604,7 +5590,6 @@ export class AgentManager {
agent,
event.provider,
this.formatTurnFailedMessage(event),
this.liveTurnId(agent, options?.displayTurnId ?? eventTurnId),
options,
);
this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Turn failed");
@@ -5730,64 +5715,35 @@ export class AgentManager {
}
}
private liveTurnId(agent: ActiveManagedAgent, turnId?: string): string {
return this.assignLiveTurn(agent, turnId) ?? randomUUID();
}
private assignLiveTurn(
agent: ActiveManagedAgent,
turnId?: string,
item?: AgentTimelineItem,
): string | null {
const openTurnId = turnId ?? agent.activeForegroundTurnId ?? agent.activeTurnId;
if (openTurnId || (item?.type !== "assistant_message" && item?.type !== "reasoning")) {
this.idleTextTurns.delete(agent);
// Anonymous tool snapshots coalesce by call ID before ingest assigns their turn.
return openTurnId ?? (item?.type === "tool_call" ? null : randomUUID());
}
const previous = this.idleTextTurns.get(agent);
const messageId = item.type === "assistant_message" ? item.messageId : undefined;
const sameMessage =
previous && (!messageId || !previous.messageId || messageId === previous.messageId);
const textTurn = {
turnId: sameMessage ? previous.turnId : randomUUID(),
messageId: messageId ?? previous?.messageId,
};
this.idleTextTurns.set(agent, textTurn);
return textTurn.turnId;
}
private async recordAndDispatchTimelineItem(
agentId: string,
item: AgentTimelineItem,
provider: AgentProvider,
turnId: string,
turnId?: string,
options?: {
providerMessageId?: string;
notifyWaiters?: boolean;
onRecorded?: () => void;
},
): Promise<TimelineIngestResult> {
): Promise<void> {
const event: AgentStreamEvent = {
type: "timeline",
item,
provider,
turnId,
...(turnId !== undefined ? { turnId } : {}),
};
const result = await this.timeline.ingest(
{ agentId },
{
item,
turnId,
...(turnId !== undefined ? { turnId } : {}),
...(options?.providerMessageId ? { providerMessageId: options.providerMessageId } : {}),
},
{
publish: (commit) => {
options?.onRecorded?.();
const committedEvent = { ...event, turnId: commit.row.turnId };
this.publishTimelineEvent(agentId, committedEvent, commit);
if (options?.notifyWaiters) this.notifyForegroundTurnWaiters(agentId, committedEvent);
this.publishTimelineEvent(agentId, event, commit);
if (options?.notifyWaiters) this.notifyForegroundTurnWaiters(agentId, event);
if (
item.type === "tool_call" &&
item.status === "completed" &&
@@ -5803,7 +5759,6 @@ export class AgentManager {
},
);
this.reportUnpublished(agentId, result);
return result;
}
private publishTimelineEvent(agentId: string, event: AgentStreamEvent, commit: TimelineCommit) {
@@ -5906,12 +5861,11 @@ export class AgentManager {
clientMessageId,
...(options?.messageId ? { messageId: options.messageId } : {}),
});
const turnId = this.liveTurnId(agent, options?.turnId);
const writes: Promise<void>[] = [];
for (const item of items) {
// Human attempts stay in history on rejection; delivery notifications require acceptance.
if (outcome === "rejected" && item.type !== "user_message") continue;
writes.push(this.recordSubmittedPromptItem(agent, item, { ...options, turnId }));
writes.push(this.recordSubmittedPromptItem(agent, item, options));
}
await Promise.all(writes);
}
@@ -5922,19 +5876,13 @@ export class AgentManager {
item: AgentTimelineItem,
options?: { providerMessageId?: string; turnId?: string },
): Promise<void> {
return this.recordAndDispatchTimelineItem(
agent.id,
item,
agent.provider,
this.liveTurnId(agent, options?.turnId),
{
...(options?.providerMessageId ? { providerMessageId: options.providerMessageId } : {}),
onRecorded: () => {
this.touchUpdatedAt(agent);
if (item.type === "user_message") agent.lastUserMessageAt = new Date();
},
return this.recordAndDispatchTimelineItem(agent.id, item, agent.provider, options?.turnId, {
...(options?.providerMessageId ? { providerMessageId: options.providerMessageId } : {}),
onRecorded: () => {
this.touchUpdatedAt(agent);
if (item.type === "user_message") agent.lastUserMessageAt = new Date();
},
).then(() => undefined);
});
}
/** Returns whether the echo belongs to a prompt Paseo submitted, which it records only once. */
@@ -5969,7 +5917,6 @@ export class AgentManager {
agent: ActiveManagedAgent,
provider: AgentProvider,
message: string,
turnId: string,
options?: { fromHistory?: boolean },
): Promise<void> {
if (options?.fromHistory) {
@@ -5987,8 +5934,8 @@ export class AgentManager {
return;
}
const item: AgentTimelineItem = { type: "assistant_message", text, messageId: randomUUID() };
await this.recordAndDispatchTimelineItem(agent.id, item, provider, turnId);
const item: AgentTimelineItem = { type: "assistant_message", text };
await this.recordAndDispatchTimelineItem(agent.id, item, provider);
}
private formatTurnFailedMessage(
@@ -819,7 +819,7 @@ export interface AgentSession {
* (e.g. /goal pause) reach the provider without canceling the running turn.
*/
tryHandleOutOfBand?(prompt: AgentPromptInput): {
run(ctx: { emit: (event: AgentStreamEvent) => void; turnId?: string }): Promise<void>;
run(ctx: { emit: (event: AgentStreamEvent) => void }): Promise<void>;
} | null;
}
@@ -4,7 +4,6 @@ import type { AgentProvider, AgentStreamEvent } from "./agent-sdk-types.js";
import {
AGENT_STREAM_COALESCE_DEFAULT_WINDOW_MS,
AgentStreamCoalescer,
type LiveTimelineEvent,
type AgentStreamCoalescerFlush,
type AgentStreamCoalescerTimers,
} from "./agent-stream-coalescer.js";
@@ -50,12 +49,12 @@ function timeline(
provider?: AgentProvider;
turnId?: string;
},
): LiveTimelineEvent {
): Extract<AgentStreamEvent, { type: "timeline" }> {
return {
type: "timeline",
item,
provider: options?.provider ?? "codex",
turnId: options?.turnId ?? "turn",
...(options?.turnId !== undefined ? { turnId: options.turnId } : {}),
};
}
@@ -66,7 +65,7 @@ function assistant(
turnId?: string;
messageId?: string;
},
): LiveTimelineEvent {
): Extract<AgentStreamEvent, { type: "timeline" }> {
return timeline(
{
type: "assistant_message",
@@ -83,7 +82,7 @@ function reasoning(
provider?: AgentProvider;
turnId?: string;
},
): LiveTimelineEvent {
): Extract<AgentStreamEvent, { type: "timeline" }> {
return timeline({ type: "reasoning", text }, options);
}
@@ -94,7 +93,7 @@ function toolCall(options?: {
provider?: AgentProvider;
turnId?: string;
error?: unknown;
}): LiveTimelineEvent {
}): Extract<AgentStreamEvent, { type: "timeline" }> {
const status = options?.status ?? "running";
return timeline(
{
@@ -131,7 +130,6 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "hel" },
turnId: "turn",
provider: "codex",
},
]);
@@ -153,7 +151,6 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "hello" },
turnId: "turn",
provider: "codex",
},
]);
@@ -189,7 +186,6 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "fast" },
turnId: "turn",
provider: "codex",
},
]);
@@ -205,7 +201,6 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "before" },
turnId: "turn",
provider: "codex",
},
]);
@@ -214,10 +209,7 @@ describe("AgentStreamCoalescer", () => {
test("does not consume non-chunkable events", () => {
const { coalescer, flushes } = createHarness();
const nonChunkableEvents: (
| Exclude<AgentStreamEvent, { type: "timeline" }>
| LiveTimelineEvent
)[] = [
const nonChunkableEvents: AgentStreamEvent[] = [
timeline({ type: "todo", items: [{ text: "ship it", completed: false }] }),
timeline({ type: "user_message", text: "hi", messageId: "message-1" }),
timeline({ type: "error", message: "boom" }),
@@ -272,19 +264,16 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "a1" },
turnId: "turn",
provider: "codex",
},
{
agentId: "agent-1",
item: { type: "reasoning", text: "r1" },
turnId: "turn",
provider: "codex",
},
{
agentId: "agent-1",
item: { type: "assistant_message", text: "a2" },
turnId: "turn",
provider: "codex",
},
]);
@@ -318,13 +307,11 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "c" },
turnId: "turn",
provider: "codex",
},
{
agentId: "agent-1",
item: { type: "assistant_message", text: "o" },
turnId: "turn",
provider: "opencode",
},
]);
@@ -397,7 +384,6 @@ describe("AgentStreamCoalescer", () => {
type: "assistant_message",
text: " \n\t mixed \n\t whitespace ",
},
turnId: "turn",
provider: "codex",
},
]);
@@ -426,7 +412,6 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text },
turnId: "turn",
provider: "codex",
},
]);
@@ -447,13 +432,11 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "ab" },
turnId: "turn",
provider: "codex",
},
{
agentId: "agent-2",
item: { type: "assistant_message", text: "xy" },
turnId: "turn",
provider: "codex",
},
]);
@@ -472,13 +455,11 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "a" },
turnId: "turn",
provider: "codex",
},
{
agentId: "agent-2",
item: { type: "assistant_message", text: "b" },
turnId: "turn",
provider: "codex",
},
]);
@@ -495,7 +476,6 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "once" },
turnId: "turn",
provider: "codex",
},
]);
@@ -525,7 +505,6 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "first" },
turnId: "turn",
provider: "codex",
},
]);
@@ -535,13 +514,11 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "first" },
turnId: "turn",
provider: "codex",
},
{
agentId: "agent-1",
item: { type: "assistant_message", text: "second" },
turnId: "turn",
provider: "codex",
},
]);
@@ -558,7 +535,6 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "manual" },
turnId: "turn",
provider: "codex",
},
]);
@@ -575,7 +551,6 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "durable" },
turnId: "turn",
provider: "codex",
},
]);
@@ -613,13 +588,11 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "old" },
turnId: "turn",
provider: "codex",
},
{
agentId: "agent-1",
item: { type: "assistant_message", text: "new" },
turnId: "turn",
provider: "codex",
},
]);
@@ -646,7 +619,6 @@ describe("AgentStreamCoalescer", () => {
text: "hello",
futureOptionalField: { preserved: true },
},
turnId: "turn",
provider: "codex",
},
]);
@@ -677,7 +649,6 @@ describe("AgentStreamCoalescer", () => {
exitCode: null,
},
},
turnId: "turn",
provider: "codex",
},
]);
@@ -7,11 +7,7 @@ type CoalescableTextKind = "assistant_message" | "reasoning";
type CoalescableTimelineKind = CoalescableTextKind | "tool_call";
type CoalescableTextItem = Extract<AgentTimelineItem, { type: CoalescableTextKind }>;
type CoalescableTimelineItem = Extract<AgentTimelineItem, { type: CoalescableTimelineKind }>;
export type LiveTimelineEvent = Omit<Extract<AgentStreamEvent, { type: "timeline" }>, "turnId"> & {
turnId: string | null;
};
type CoalescerEvent = Exclude<AgentStreamEvent, { type: "timeline" }> | LiveTimelineEvent;
type CoalescableTimelineEvent = LiveTimelineEvent & {
type CoalescableTimelineEvent = Extract<AgentStreamEvent, { type: "timeline" }> & {
item: CoalescableTimelineItem;
};
@@ -24,7 +20,7 @@ export interface AgentStreamCoalescerFlush {
agentId: string;
item: CoalescableTimelineItem;
provider: AgentProvider;
turnId: string | null;
turnId?: string;
}
export interface AgentStreamCoalescerOptions {
@@ -39,14 +35,14 @@ interface PendingTextEntry {
item: CoalescableTextItem;
text: string;
provider: AgentProvider;
turnId: string | null;
turnId?: string;
}
interface PendingToolCallEntry {
kind: "tool_call";
item: Extract<AgentTimelineItem, { type: "tool_call" }>;
provider: AgentProvider;
turnId: string | null;
turnId?: string;
}
type PendingAgentStreamEntry = PendingTextEntry | PendingToolCallEntry;
@@ -60,7 +56,7 @@ interface PendingAgentStreamBuffer {
lastFlushAt: number | null;
}
function isCoalescableTimelineEvent(event: CoalescerEvent): event is CoalescableTimelineEvent {
function isCoalescableTimelineEvent(event: AgentStreamEvent): event is CoalescableTimelineEvent {
return (
event.type === "timeline" &&
(event.item.type === "assistant_message" ||
@@ -104,7 +100,7 @@ export class AgentStreamCoalescer {
this.onFlush = options.onFlush;
}
handle(agentId: string, event: CoalescerEvent): boolean {
handle(agentId: string, event: AgentStreamEvent): boolean {
if (!isCoalescableTimelineEvent(event)) {
return false;
}
@@ -182,13 +178,12 @@ export class AgentStreamCoalescer {
item: event.item,
text: event.item.text,
provider: event.provider,
turnId: event.turnId,
...(event.turnId !== undefined ? { turnId: event.turnId } : {}),
});
return;
}
const key = JSON.stringify([event.item.callId, event.turnId]);
const existingIndex = buffer.toolCallEntryIndexes.get(key);
const existingIndex = buffer.toolCallEntryIndexes.get(event.item.callId);
const existing = existingIndex !== undefined ? buffer.entries[existingIndex] : undefined;
// Merge rather than replace, so an update that carries less (an unknown detail after a
// labeled one) cannot erase what the timeline would have kept had both been flushed.
@@ -200,7 +195,7 @@ export class AgentStreamCoalescer {
kind: "tool_call",
item,
provider: event.provider,
turnId: event.turnId,
...(event.turnId !== undefined ? { turnId: event.turnId } : {}),
};
if (existingIndex !== undefined) {
@@ -208,7 +203,7 @@ export class AgentStreamCoalescer {
return;
}
buffer.toolCallEntryIndexes.set(key, buffer.entries.length);
buffer.toolCallEntryIndexes.set(event.item.callId, buffer.entries.length);
buffer.entries.push(entry);
}
@@ -263,7 +258,7 @@ export class AgentStreamCoalescer {
}
: entry.item,
provider: entry.provider,
turnId: entry.turnId,
...(entry.turnId !== undefined ? { turnId: entry.turnId } : {}),
});
}
} finally {
@@ -865,18 +865,17 @@ export class OmpAgentSession implements AgentSession {
options,
streamingBehavior,
announceTurn = false,
turnId = randomUUID(),
}: {
prompt: AgentPromptInput;
options?: AgentRunOptions;
streamingBehavior?: "steer" | "followUp";
announceTurn?: boolean;
turnId?: string;
}): Promise<StartTurnResult> {
if (this.activeTurnId) {
throw new Error("An OMP turn is already active");
}
const turnId = randomUUID();
this.live = true;
this.activeTurnId = turnId;
this.activeAssistantMessageId = null;
@@ -1268,7 +1267,7 @@ export class OmpAgentSession implements AgentSession {
tryHandleOutOfBand(
prompt: AgentPromptInput,
): ReturnType<NonNullable<AgentSession["tryHandleOutOfBand"]>> {
): { run(ctx: { emit: (event: AgentStreamEvent) => void }): Promise<void> } | null {
if (typeof prompt !== "string") {
return null;
}
@@ -1299,14 +1298,9 @@ export class OmpAgentSession implements AgentSession {
}
const streamingBehavior = commandName === "steer" ? "steer" : "followUp";
return {
run: async ({ turnId }) => {
run: async () => {
if (!this.activeTurnId && !this.activeTurnStarted) {
await this.startPrompt({
prompt: message,
streamingBehavior,
announceTurn: true,
turnId,
});
await this.startPrompt({ prompt: message, streamingBehavior, announceTurn: true });
} else {
await this.runtimeSession.prompt({ message, streamingBehavior });
}
@@ -1595,6 +1589,7 @@ export class OmpAgentSession implements AgentSession {
this.emit({
type: "timeline",
provider: this.provider,
turnId: this.currentTurnIdForEvent(),
item: {
type: "notification",
level:
@@ -1612,6 +1607,7 @@ export class OmpAgentSession implements AgentSession {
this.emit({
type: "timeline",
provider: this.provider,
turnId: this.currentTurnIdForEvent(),
item: sideEffectItem,
});
return;
@@ -2073,7 +2073,7 @@ export class PiRpcAgentSession implements AgentSession {
if (event.method === "notify" && message) {
const extensionMapping = this.extensionHost.mapRuntimeNotification(message);
if (extensionMapping) {
this.emitExtensionOutput(extensionMapping);
this.emitExtensionOutput(extensionMapping, this.currentTurnIdForEvent());
return;
}
if (
@@ -2086,6 +2086,7 @@ export class PiRpcAgentSession implements AgentSession {
this.emit({
type: "timeline",
provider: this.provider,
turnId: this.currentTurnIdForEvent(),
item: {
type: "notification",
level: toNotificationLevel(event.notifyType),
@@ -424,13 +424,6 @@ export class TimelineProjection {
this.spans.splice(index + 1, end - index - 1);
}
itemTurnId(item: AgentTimelineItem): string | undefined {
const identity = timelineItemIdentity(item);
const index = identity === null ? undefined : this.identities.get(identity);
const row = index === undefined ? undefined : this.rows[index];
return row?.item.type === item.type ? row.turnId : undefined;
}
getRows(): ProjectedTimelineRow[] {
return this.rows.map((row) => ({ ...row }));
}
@@ -1211,6 +1211,28 @@ describe.each(TIMELINE_CONTRACT_BACKENDS)("provider history over a $name backend
expect(tail).toMatchObject({ epoch: first.head.epoch, startSeq: 1, endSeq: 4 });
});
it("acknowledges provider prompts that replay with a client ID", async () => {
const timeline = new AgentTimeline(new DeferredTimelineBackend(create()));
const steer = (id: string): TimelineEntry => ({
item: { type: "user_message", messageId: id, clientMessageId: `client-${id}`, text: id },
});
const history = [prompt("a"), reply("A"), steer("b"), reply("B")];
await timeline.importHistory(scope, history);
expect(await timeline.reconcileProviderHistory(scope, history)).toEqual({ kind: "unchanged" });
const continued = [...history, steer("c"), reply("C")];
expect(await timeline.reconcileProviderHistory(scope, continued)).toMatchObject({
kind: "appended",
});
expect(await timeline.reconcileProviderHistory(scope, continued)).toEqual({
kind: "unchanged",
});
expect((await timeline.readRows(scope))[4]).toMatchObject({
item: { messageId: "c", clientMessageId: "client-c" },
providerMessageId: "c",
});
});
it("leaves existing history alone when asked to import", async () => {
const { timeline } = await owned([prompt("a"), reply("A")]);
@@ -182,7 +182,7 @@ export class AgentTimeline {
const existing = await this.backend.head(scope);
if (existing) return { kind: "present", head: existing };
const head = await this.backend.create(scope, {
entries: entries.map(boundEntry),
entries: entries.map(providerHistoryEntry),
timestamp: options.timestamp,
});
return { kind: "imported", head: this.track(scope, head) };
@@ -205,7 +205,7 @@ export class AgentTimeline {
const plan = planProviderHistory({
rows: await this.backend.readRows(scope),
prompts: await this.backend.prompts(scope),
provider: entries.map(boundEntry),
provider: entries.map(providerHistoryEntry),
});
if (plan.kind !== "append") return plan;
const commits = await this.commit(scope, plan.entries);
@@ -295,15 +295,6 @@ export class AgentTimeline {
}
}
if (await this.backend.isRetired(scope, entry)) return { kind: "dropped" };
// A root live upsert updates the item where it first appeared.
if (
scope.subagentId === undefined &&
entry.turnId !== undefined &&
(entry.item.type === "tool_call" || entry.item.type === "plugin")
) {
const originalTurnId = await this.backend.itemTurnId(scope, entry.item);
if (originalTurnId) entry = { ...entry, turnId: originalTurnId };
}
const [commit] = await this.commit(scope, [entry]);
const failure = publishCommitted(options?.publish, commit);
return failure
@@ -520,6 +511,15 @@ function boundEntry(entry: TimelineEntry): TimelineEntry {
return { ...entry, item: limitAgentTimelineItemContent(entry.item) };
}
/** Replay proves delivery even when the provider includes Paseo's original client ID. */
function providerHistoryEntry(entry: TimelineEntry): TimelineEntry {
const { item } = entry;
const providerMessageId =
entry.providerMessageId ??
(item.type === "user_message" && item.clientMessageId ? item.messageId : undefined);
return boundEntry({ ...entry, ...(providerMessageId ? { providerMessageId } : {}) });
}
interface PublishFailure {
error: unknown;
}
@@ -113,7 +113,6 @@ export interface AgentTimelineBackend {
scope: TimelineScope,
entries: readonly TimelineEntry[],
): MaybePromise<TimelineBackendAppendResult>;
itemTurnId(scope: TimelineScope, item: AgentTimelineItem): MaybePromise<string | undefined>;
/** Whether a new entry would land on retired history (see `TimelineProjection.isRetired`). */
isRetired(scope: TimelineScope, entry: TimelineEntry): MaybePromise<boolean>;
/** Active user prompts in display order. */
@@ -145,9 +145,6 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
return { rows: rows.map(cloneRow), head: this.describe(state) };
}
itemTurnId(scope: TimelineScope, item: AgentTimelineItem) {
return this.requireState(scope).projection.itemTurnId(item);
}
isRetired(scope: TimelineScope, entry: TimelineEntry): boolean {
return this.requireState(scope).projection.isRetired(entry);
}
@@ -82,9 +82,6 @@ export class DeferredTimelineBackend implements AgentTimelineBackend {
return result;
});
}
itemTurnId(scope: TimelineScope, item: AgentTimelineItem) {
return this.defer(() => this.inner.itemTurnId(scope, item));
}
isRetired(scope: TimelineScope, entry: TimelineEntry): Promise<boolean> {
return this.defer(() => this.inner.isRetired(scope, entry));
}
@@ -374,18 +374,11 @@ test.each(["agent", "workspace"] as const)(
clientMessageId: agent.clientMessageId,
messageId: agent.clientMessageId,
},
{
type: "assistant_message",
text: `[System Error] ${rejection}`,
messageId: expect.any(String),
},
{ type: "assistant_message", text: `[System Error] ${rejection}` },
];
const entries = (await client.fetchAgentTimeline(created.id)).entries;
expect(entries.map((entry) => entry.item)).toEqual(expectedTimeline);
expect(entries.map((entry) => entry.turnId)).toEqual([
expect.any(String),
entries[0]?.turnId,
]);
expect(
(await client.fetchAgentTimeline(created.id)).entries.map((entry) => entry.item),
).toEqual(expectedTimeline);
expect(streamed).toEqual(expectedTimeline);
expect((await submit()).id).toBe(created.id);
expect(
@@ -150,11 +150,13 @@ test("reconnect catches up committed rows without replaying a provisional seed",
expect(catchUp.startCursor).toEqual({ epoch, seq: 121 });
expect(catchUp.endCursor).toEqual({ epoch, seq: 121 });
expect(catchUp.projection).toBe("projected");
expect(catchUp.entries[0]?.seqStart).toBe(121);
expect(catchUp.entries[0]?.seqStart).toBe(1);
expect(catchUp.entries[0]?.seqEnd).toBe(121);
expect(catchUp.entries[0]?.item).toEqual({
type: "assistant_message",
text: "finalized while disconnected",
text:
Array.from({ length: 120 }, (_, index) => `committed row ${index + 1}`).join("") +
"finalized while disconnected",
});
} finally {
reconnectCollector.unsubscribe();
@@ -364,16 +364,11 @@ describe("daemon E2E - timeline window", () => {
title: "Timeline Projected Page Limit Test",
modeId: "full-access",
});
const tool = {
type: "tool_call",
callId: "page-tool",
name: "shell",
status: "running",
error: null,
detail: { type: "unknown", input: { cmd: "sleep 10" }, output: null },
} as const;
for (let seq = 1; seq <= 200; seq += 1) {
await ctx.daemon.daemon.agentManager.appendTimelineItem(agent.id, tool);
await ctx.daemon.daemon.agentManager.appendTimelineItem(agent.id, {
type: "assistant_message",
text: "x",
});
}
for (let seq = 201; seq <= 350; seq += 1) {
await ctx.daemon.daemon.agentManager.appendTimelineItem(agent.id, {
@@ -406,19 +401,17 @@ describe("daemon E2E - timeline window", () => {
entryCount: 100,
firstEntry: {
provider: "codex",
item: tool,
item: { type: "assistant_message", text: "x".repeat(200) },
timestamp: expect.any(String),
turnId: expect.any(String),
seqStart: 1,
seqEnd: 200,
sourceSeqRanges: [{ startSeq: 1, endSeq: 200 }],
collapsed: ["tool_lifecycle"],
collapsed: ["assistant_merge"],
},
lastEntry: {
provider: "codex",
item: { type: "user_message", text: "message 99" },
timestamp: expect.any(String),
turnId: expect.any(String),
seqStart: 299,
seqEnd: 299,
sourceSeqRanges: [{ startSeq: 299, endSeq: 299 }],
@@ -177,14 +177,10 @@ export default function contribute(server: PluginServerContext) {
await expect(
client.invokePluginRpc("paseo-api", "append", { agentId, status: "running" }),
).resolves.toEqual({ seq: expect.any(Number), epoch: expect.any(String) });
const first = await client.fetchAgentTimeline(agentId, { projection: "projected" });
const firstItem = first.entries.find((entry) => entry.item.type === "plugin");
expect(firstItem?.turnId).toEqual(expect.any(String));
await client.invokePluginRpc("paseo-api", "append", { agentId, status: "complete" });
const timeline = await client.fetchAgentTimeline(agentId, { projection: "projected" });
expect(timeline.entries.filter((entry) => entry.item.type === "plugin")).toEqual([
expect.objectContaining({
turnId: firstItem?.turnId,
item: expect.objectContaining({
type: "plugin",
id: "review-1",