Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 73af0870d7 fix(timeline): keep idle text streams and item updates together
Adjacent idle text shares a display turn across coalescer windows. Resolve tool and plugin updates inside timeline ingestion, after checking retirement and before publishing the committed association.
2026-11-18 15:07:34 +01:00
Mohamed Boudra bd1a8925df fix(timeline): keep idle plugin item updates together
Identify deltas of one provider item through live admission so a snapshot sent while idle retains its turn. Test OMP without requiring its executable on the runner.
2026-11-18 15:02:19 +01:00
Mohamed Boudra 5bc12c4ec7 fix(timeline): keep finished replies visible after a background wake
Give root live rows explicit turn membership so an idle notice cannot join two completed replies. Preserve the turn attached to an existing tool or plugin item when it is updated.
2026-11-18 15:02:19 +01:00
17 changed files with 534 additions and 165 deletions
@@ -12,6 +12,8 @@ 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,
@@ -424,6 +426,213 @@ 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();
@@ -533,6 +742,7 @@ 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"));
@@ -559,11 +769,13 @@ 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) },
},
]);
@@ -609,6 +821,7 @@ 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++) {
@@ -732,6 +945,7 @@ 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" })));
@@ -768,6 +982,7 @@ 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" })));
@@ -799,6 +1014,7 @@ 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"));
@@ -880,10 +1096,10 @@ describe("target coalesced behavior", () => {
workdir: secondWorkdir,
});
first.session.pushEvent(assistant("a"));
second.session.pushEvent(assistant("b"));
first.session.pushEvent(assistant("a"));
second.session.pushEvent(assistant("b"));
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"));
await waitForSessionEventQueue();
await vi.advanceTimersByTimeAsync(COALESCE_WINDOW_MS);
@@ -917,6 +1133,7 @@ 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"));
@@ -928,10 +1145,16 @@ 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", item: { type: "assistant_message", text: "codex" } },
{
type: "timeline",
provider: "codex",
turnId: "streaming-turn",
item: { type: "assistant_message", text: "codex" },
},
{
type: "timeline",
provider: "claude",
turnId: "streaming-turn",
item: { type: "assistant_message", text: "claude" },
},
]);
@@ -1256,6 +1479,7 @@ 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"));
@@ -1285,6 +1509,7 @@ 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) => {
@@ -1336,6 +1561,7 @@ 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,7 +800,10 @@ 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.getLastAssistantMessage(agent.id)).toBe("kept and next");
expect(await manager.getTimeline(agent.id)).toEqual([
{ type: "assistant_message", text: "kept" },
{ type: "assistant_message", text: " and next" },
]);
expect(logs).toContainEqual(
expect.objectContaining({
msg: "Failed to publish committed timeline item",
@@ -7206,17 +7209,13 @@ test("getTimelineRows falls back to the in-memory timeline when no durable store
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" },
},
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" } },
]);
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 () => {
@@ -9967,7 +9966,17 @@ 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`" },
{
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,
]);
await expect(manager.runAgent(agent.id, "second turn")).resolves.toEqual(
@@ -13227,6 +13236,7 @@ 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",
+165 -108
View File
@@ -499,6 +499,7 @@ type ActiveTurnTerminalDisposition = "closed_current" | "stale" | "untracked";
interface HandleStreamEventOptions {
fromHistory?: boolean;
displayTurnId?: string;
}
interface ManagedAgentBase {
@@ -624,9 +625,9 @@ type AgentMetadata = Record<string, JsonValue>;
function attachManagedTurnIdentity(
agent: ActiveManagedAgent,
event: AgentStreamEvent,
event: Exclude<AgentStreamEvent, { type: "timeline" }>,
fromHistory: boolean,
): { event: AgentStreamEvent; turnId: string | undefined } {
): { event: Exclude<AgentStreamEvent, { type: "timeline" }>; turnId: string | undefined } {
const existingTurnId = getAgentStreamEventTurnId(event);
if (fromHistory || existingTurnId !== undefined) {
return { event, turnId: existingTurnId };
@@ -643,12 +644,6 @@ 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 };
}
@@ -928,6 +923,10 @@ 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;
@@ -978,7 +977,7 @@ export class AgentManager {
onFlush: ({ agentId, item, provider, turnId }) => {
this.trackTimelineWrite(
agentId,
this.recordAndDispatchTimelineItem(agentId, item, provider, turnId, {
this.recordAndDispatchTimelineItem(agentId, item, provider, turnId ?? randomUUID(), {
notifyWaiters: true,
}),
);
@@ -3187,46 +3186,51 @@ export class AgentManager {
return false;
}
onAccepted?.();
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") {
await new Promise<void>((promptRecorded, reject) => {
void this.runForegroundMutation(agentId, async () => {
const turnId = this.liveTurnId(agent);
this.touchUpdatedAt(agent);
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}` },
});
}
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);
});
return true;
}
@@ -3238,16 +3242,11 @@ export class AgentManager {
const agent = this.requireAgent(agentId);
item = limitAgentTimelineItemContent(item);
this.touchUpdatedAt(agent);
const event: AgentStreamEvent = { type: "timeline", item, provider: agent.provider };
const result = await this.timeline.ingest(
{ agentId },
{ item },
{ publish: (commit) => this.publishTimelineEvent(agentId, event, commit) },
);
const turnId = this.liveTurnId(agent);
const result = await this.recordAndDispatchTimelineItem(agentId, item, agent.provider, turnId);
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 };
}
@@ -3259,6 +3258,7 @@ export class AgentManager {
type: "timeline",
item,
provider: agent.provider,
turnId: this.liveTurnId(agent),
});
}
@@ -3315,16 +3315,22 @@ 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,
});
await this.handleStreamEvent(
agent,
{
type: "turn_failed",
provider: agent.provider,
error: errorMsg,
},
{ displayTurnId: turnId },
);
this.finalizeForegroundTurn(agent);
} finally {
// A steer waiting on this start is released only once the run is cleared.
@@ -3591,6 +3597,7 @@ export class AgentManager {
}
private openActiveTurn(agent: ActiveManagedAgent, turnId: string, startedAt: Date): void {
this.idleTextTurns.delete(agent);
agent.activeTurnId = turnId;
agent.activeTurnStartedAt = startedAt;
}
@@ -5055,7 +5062,10 @@ export class AgentManager {
return;
}
const turnId = getAgentStreamEventTurnId(event);
const matchingWaiters = this.runs.getMatchingWaiters(agent, turnId);
const matchingWaiters = this.runs.getMatchingWaiters(
agent,
event.type === "timeline" ? (turnId ?? agent.activeForegroundTurnId ?? undefined) : turnId,
);
this.logger.trace(
{
agentId: agent.id,
@@ -5068,7 +5078,13 @@ export class AgentManager {
"agent.manager.dispatch_session_event",
);
const shouldNotifyWaiters = await this.handleStreamEvent(agent, event);
const shouldNotifyWaiters =
event.type === "timeline"
? await this.onLiveTimelineEvent(agent, {
...event,
item: limitAgentTimelineItemContent(event.item),
})
: await this.handleStreamEvent(agent, event);
if (!shouldNotifyWaiters) {
return;
@@ -5222,13 +5238,14 @@ export class AgentManager {
private async handleStreamEvent(
agent: ActiveManagedAgent,
event: AgentStreamEvent,
sourceEvent: Exclude<AgentStreamEvent, { type: "timeline" }>,
options?: HandleStreamEventOptions,
): Promise<boolean> {
event = limitAgentStreamEventContent(event);
const identified = attachManagedTurnIdentity(agent, event, options?.fromHistory === true);
event = identified.event;
const eventTurnId = identified.turnId;
const { event, turnId: eventTurnId } = attachManagedTurnIdentity(
agent,
sourceEvent,
options?.fromHistory === true,
);
const isForegroundEvent = agent.activeForegroundTurnId === eventTurnId;
this.traceHandleStreamEventStart(agent, event, eventTurnId, isForegroundEvent);
if (
@@ -5243,10 +5260,6 @@ 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 });
@@ -5371,7 +5384,7 @@ export class AgentManager {
private dispatchStreamEventByType(params: {
agent: ActiveManagedAgent;
event: AgentStreamEvent;
event: Exclude<AgentStreamEvent, { type: "timeline" }>;
options: HandleStreamEventOptions | undefined;
isForegroundEvent: boolean;
eventTurnId: string | undefined;
@@ -5423,8 +5436,6 @@ 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,
@@ -5483,36 +5494,43 @@ export class AgentManager {
}
}
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;
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 });
flags.shouldDispatchEvent = false;
flags.shouldNotifyWaiters = false;
const resolvedTurnId = turnId ?? randomUUID();
let notifyWaiters = false;
for (const item of projectAgentMessages(event.item)) {
if (
item.type === "user_message" &&
item.clientMessageId &&
(await this.reconcileSubmittedPromptEcho(agent, item, event.turnId))
(await this.reconcileSubmittedPromptEcho(agent, item, resolvedTurnId))
)
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);
const result = await this.recordAndDispatchTimelineItem(
agent.id,
item,
event.provider,
resolvedTurnId,
);
if (result.kind === "dropped") continue;
if (item.type === "user_message") {
agent.lastUserMessageAt = new Date();
this.emitState(agent);
}
flags.shouldNotifyWaiters = true;
notifyWaiters = true;
}
return notifyWaiters;
}
private onStreamTurnCompleted(params: {
@@ -5559,7 +5577,7 @@ export class AgentManager {
eventTurnId: string | undefined;
isForegroundEvent: boolean;
terminalDisposition: ActiveTurnTerminalDisposition;
options: { fromHistory?: boolean } | undefined;
options: HandleStreamEventOptions | undefined;
}): Promise<void> {
const { agent, event, eventTurnId, isForegroundEvent, terminalDisposition, options } = params;
this.logger.warn(
@@ -5586,6 +5604,7 @@ export class AgentManager {
agent,
event.provider,
this.formatTurnFailedMessage(event),
this.liveTurnId(agent, options?.displayTurnId ?? eventTurnId),
options,
);
this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Turn failed");
@@ -5711,35 +5730,64 @@ 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<void> {
): Promise<TimelineIngestResult> {
const event: AgentStreamEvent = {
type: "timeline",
item,
provider,
...(turnId !== undefined ? { turnId } : {}),
turnId,
};
const result = await this.timeline.ingest(
{ agentId },
{
item,
...(turnId !== undefined ? { turnId } : {}),
turnId,
...(options?.providerMessageId ? { providerMessageId: options.providerMessageId } : {}),
},
{
publish: (commit) => {
options?.onRecorded?.();
this.publishTimelineEvent(agentId, event, commit);
if (options?.notifyWaiters) this.notifyForegroundTurnWaiters(agentId, event);
const committedEvent = { ...event, turnId: commit.row.turnId };
this.publishTimelineEvent(agentId, committedEvent, commit);
if (options?.notifyWaiters) this.notifyForegroundTurnWaiters(agentId, committedEvent);
if (
item.type === "tool_call" &&
item.status === "completed" &&
@@ -5755,6 +5803,7 @@ export class AgentManager {
},
);
this.reportUnpublished(agentId, result);
return result;
}
private publishTimelineEvent(agentId: string, event: AgentStreamEvent, commit: TimelineCommit) {
@@ -5857,11 +5906,12 @@ 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));
writes.push(this.recordSubmittedPromptItem(agent, item, { ...options, turnId }));
}
await Promise.all(writes);
}
@@ -5872,13 +5922,19 @@ export class AgentManager {
item: AgentTimelineItem,
options?: { providerMessageId?: string; turnId?: string },
): Promise<void> {
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();
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();
},
},
});
).then(() => undefined);
}
/** Returns whether the echo belongs to a prompt Paseo submitted, which it records only once. */
@@ -5913,6 +5969,7 @@ export class AgentManager {
agent: ActiveManagedAgent,
provider: AgentProvider,
message: string,
turnId: string,
options?: { fromHistory?: boolean },
): Promise<void> {
if (options?.fromHistory) {
@@ -5930,8 +5987,8 @@ export class AgentManager {
return;
}
const item: AgentTimelineItem = { type: "assistant_message", text };
await this.recordAndDispatchTimelineItem(agent.id, item, provider);
const item: AgentTimelineItem = { type: "assistant_message", text, messageId: randomUUID() };
await this.recordAndDispatchTimelineItem(agent.id, item, provider, turnId);
}
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 }): Promise<void>;
run(ctx: { emit: (event: AgentStreamEvent) => void; turnId?: string }): Promise<void>;
} | null;
}
@@ -4,6 +4,7 @@ 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";
@@ -49,12 +50,12 @@ function timeline(
provider?: AgentProvider;
turnId?: string;
},
): Extract<AgentStreamEvent, { type: "timeline" }> {
): LiveTimelineEvent {
return {
type: "timeline",
item,
provider: options?.provider ?? "codex",
...(options?.turnId !== undefined ? { turnId: options.turnId } : {}),
turnId: options?.turnId ?? "turn",
};
}
@@ -65,7 +66,7 @@ function assistant(
turnId?: string;
messageId?: string;
},
): Extract<AgentStreamEvent, { type: "timeline" }> {
): LiveTimelineEvent {
return timeline(
{
type: "assistant_message",
@@ -82,7 +83,7 @@ function reasoning(
provider?: AgentProvider;
turnId?: string;
},
): Extract<AgentStreamEvent, { type: "timeline" }> {
): LiveTimelineEvent {
return timeline({ type: "reasoning", text }, options);
}
@@ -93,7 +94,7 @@ function toolCall(options?: {
provider?: AgentProvider;
turnId?: string;
error?: unknown;
}): Extract<AgentStreamEvent, { type: "timeline" }> {
}): LiveTimelineEvent {
const status = options?.status ?? "running";
return timeline(
{
@@ -130,6 +131,7 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "hel" },
turnId: "turn",
provider: "codex",
},
]);
@@ -151,6 +153,7 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "hello" },
turnId: "turn",
provider: "codex",
},
]);
@@ -186,6 +189,7 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "fast" },
turnId: "turn",
provider: "codex",
},
]);
@@ -201,6 +205,7 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "before" },
turnId: "turn",
provider: "codex",
},
]);
@@ -209,7 +214,10 @@ describe("AgentStreamCoalescer", () => {
test("does not consume non-chunkable events", () => {
const { coalescer, flushes } = createHarness();
const nonChunkableEvents: AgentStreamEvent[] = [
const nonChunkableEvents: (
| Exclude<AgentStreamEvent, { type: "timeline" }>
| LiveTimelineEvent
)[] = [
timeline({ type: "todo", items: [{ text: "ship it", completed: false }] }),
timeline({ type: "user_message", text: "hi", messageId: "message-1" }),
timeline({ type: "error", message: "boom" }),
@@ -264,16 +272,19 @@ 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",
},
]);
@@ -307,11 +318,13 @@ 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",
},
]);
@@ -384,6 +397,7 @@ describe("AgentStreamCoalescer", () => {
type: "assistant_message",
text: " \n\t mixed \n\t whitespace ",
},
turnId: "turn",
provider: "codex",
},
]);
@@ -412,6 +426,7 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text },
turnId: "turn",
provider: "codex",
},
]);
@@ -432,11 +447,13 @@ 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",
},
]);
@@ -455,11 +472,13 @@ 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",
},
]);
@@ -476,6 +495,7 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "once" },
turnId: "turn",
provider: "codex",
},
]);
@@ -505,6 +525,7 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "first" },
turnId: "turn",
provider: "codex",
},
]);
@@ -514,11 +535,13 @@ 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",
},
]);
@@ -535,6 +558,7 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "manual" },
turnId: "turn",
provider: "codex",
},
]);
@@ -551,6 +575,7 @@ describe("AgentStreamCoalescer", () => {
{
agentId: "agent-1",
item: { type: "assistant_message", text: "durable" },
turnId: "turn",
provider: "codex",
},
]);
@@ -588,11 +613,13 @@ 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",
},
]);
@@ -619,6 +646,7 @@ describe("AgentStreamCoalescer", () => {
text: "hello",
futureOptionalField: { preserved: true },
},
turnId: "turn",
provider: "codex",
},
]);
@@ -649,6 +677,7 @@ describe("AgentStreamCoalescer", () => {
exitCode: null,
},
},
turnId: "turn",
provider: "codex",
},
]);
@@ -7,7 +7,11 @@ type CoalescableTextKind = "assistant_message" | "reasoning";
type CoalescableTimelineKind = CoalescableTextKind | "tool_call";
type CoalescableTextItem = Extract<AgentTimelineItem, { type: CoalescableTextKind }>;
type CoalescableTimelineItem = Extract<AgentTimelineItem, { type: CoalescableTimelineKind }>;
type CoalescableTimelineEvent = Extract<AgentStreamEvent, { type: "timeline" }> & {
export type LiveTimelineEvent = Omit<Extract<AgentStreamEvent, { type: "timeline" }>, "turnId"> & {
turnId: string | null;
};
type CoalescerEvent = Exclude<AgentStreamEvent, { type: "timeline" }> | LiveTimelineEvent;
type CoalescableTimelineEvent = LiveTimelineEvent & {
item: CoalescableTimelineItem;
};
@@ -20,7 +24,7 @@ export interface AgentStreamCoalescerFlush {
agentId: string;
item: CoalescableTimelineItem;
provider: AgentProvider;
turnId?: string;
turnId: string | null;
}
export interface AgentStreamCoalescerOptions {
@@ -35,14 +39,14 @@ interface PendingTextEntry {
item: CoalescableTextItem;
text: string;
provider: AgentProvider;
turnId?: string;
turnId: string | null;
}
interface PendingToolCallEntry {
kind: "tool_call";
item: Extract<AgentTimelineItem, { type: "tool_call" }>;
provider: AgentProvider;
turnId?: string;
turnId: string | null;
}
type PendingAgentStreamEntry = PendingTextEntry | PendingToolCallEntry;
@@ -56,7 +60,7 @@ interface PendingAgentStreamBuffer {
lastFlushAt: number | null;
}
function isCoalescableTimelineEvent(event: AgentStreamEvent): event is CoalescableTimelineEvent {
function isCoalescableTimelineEvent(event: CoalescerEvent): event is CoalescableTimelineEvent {
return (
event.type === "timeline" &&
(event.item.type === "assistant_message" ||
@@ -100,7 +104,7 @@ export class AgentStreamCoalescer {
this.onFlush = options.onFlush;
}
handle(agentId: string, event: AgentStreamEvent): boolean {
handle(agentId: string, event: CoalescerEvent): boolean {
if (!isCoalescableTimelineEvent(event)) {
return false;
}
@@ -178,12 +182,13 @@ export class AgentStreamCoalescer {
item: event.item,
text: event.item.text,
provider: event.provider,
...(event.turnId !== undefined ? { turnId: event.turnId } : {}),
turnId: event.turnId,
});
return;
}
const existingIndex = buffer.toolCallEntryIndexes.get(event.item.callId);
const key = JSON.stringify([event.item.callId, event.turnId]);
const existingIndex = buffer.toolCallEntryIndexes.get(key);
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.
@@ -195,7 +200,7 @@ export class AgentStreamCoalescer {
kind: "tool_call",
item,
provider: event.provider,
...(event.turnId !== undefined ? { turnId: event.turnId } : {}),
turnId: event.turnId,
};
if (existingIndex !== undefined) {
@@ -203,7 +208,7 @@ export class AgentStreamCoalescer {
return;
}
buffer.toolCallEntryIndexes.set(event.item.callId, buffer.entries.length);
buffer.toolCallEntryIndexes.set(key, buffer.entries.length);
buffer.entries.push(entry);
}
@@ -258,7 +263,7 @@ export class AgentStreamCoalescer {
}
: entry.item,
provider: entry.provider,
...(entry.turnId !== undefined ? { turnId: entry.turnId } : {}),
turnId: entry.turnId,
});
}
} finally {
@@ -865,17 +865,18 @@ 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;
@@ -1267,7 +1268,7 @@ export class OmpAgentSession implements AgentSession {
tryHandleOutOfBand(
prompt: AgentPromptInput,
): { run(ctx: { emit: (event: AgentStreamEvent) => void }): Promise<void> } | null {
): ReturnType<NonNullable<AgentSession["tryHandleOutOfBand"]>> {
if (typeof prompt !== "string") {
return null;
}
@@ -1298,9 +1299,14 @@ export class OmpAgentSession implements AgentSession {
}
const streamingBehavior = commandName === "steer" ? "steer" : "followUp";
return {
run: async () => {
run: async ({ turnId }) => {
if (!this.activeTurnId && !this.activeTurnStarted) {
await this.startPrompt({ prompt: message, streamingBehavior, announceTurn: true });
await this.startPrompt({
prompt: message,
streamingBehavior,
announceTurn: true,
turnId,
});
} else {
await this.runtimeSession.prompt({ message, streamingBehavior });
}
@@ -1589,7 +1595,6 @@ export class OmpAgentSession implements AgentSession {
this.emit({
type: "timeline",
provider: this.provider,
turnId: this.currentTurnIdForEvent(),
item: {
type: "notification",
level:
@@ -1607,7 +1612,6 @@ 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.currentTurnIdForEvent());
this.emitExtensionOutput(extensionMapping);
return;
}
if (
@@ -2086,7 +2086,6 @@ export class PiRpcAgentSession implements AgentSession {
this.emit({
type: "timeline",
provider: this.provider,
turnId: this.currentTurnIdForEvent(),
item: {
type: "notification",
level: toNotificationLevel(event.notifyType),
@@ -424,6 +424,13 @@ 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 }));
}
@@ -295,6 +295,15 @@ 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
@@ -113,6 +113,7 @@ 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,6 +145,9 @@ 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,6 +82,9 @@ 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,11 +374,18 @@ test.each(["agent", "workspace"] as const)(
clientMessageId: agent.clientMessageId,
messageId: agent.clientMessageId,
},
{ type: "assistant_message", text: `[System Error] ${rejection}` },
{
type: "assistant_message",
text: `[System Error] ${rejection}`,
messageId: expect.any(String),
},
];
expect(
(await client.fetchAgentTimeline(created.id)).entries.map((entry) => entry.item),
).toEqual(expectedTimeline);
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(streamed).toEqual(expectedTimeline);
expect((await submit()).id).toBe(created.id);
expect(
@@ -150,13 +150,11 @@ 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(1);
expect(catchUp.entries[0]?.seqStart).toBe(121);
expect(catchUp.entries[0]?.seqEnd).toBe(121);
expect(catchUp.entries[0]?.item).toEqual({
type: "assistant_message",
text:
Array.from({ length: 120 }, (_, index) => `committed row ${index + 1}`).join("") +
"finalized while disconnected",
text: "finalized while disconnected",
});
} finally {
reconnectCollector.unsubscribe();
@@ -364,11 +364,16 @@ 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, {
type: "assistant_message",
text: "x",
});
await ctx.daemon.daemon.agentManager.appendTimelineItem(agent.id, tool);
}
for (let seq = 201; seq <= 350; seq += 1) {
await ctx.daemon.daemon.agentManager.appendTimelineItem(agent.id, {
@@ -401,17 +406,19 @@ describe("daemon E2E - timeline window", () => {
entryCount: 100,
firstEntry: {
provider: "codex",
item: { type: "assistant_message", text: "x".repeat(200) },
item: tool,
timestamp: expect.any(String),
turnId: expect.any(String),
seqStart: 1,
seqEnd: 200,
sourceSeqRanges: [{ startSeq: 1, endSeq: 200 }],
collapsed: ["assistant_merge"],
collapsed: ["tool_lifecycle"],
},
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,10 +177,14 @@ 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",