refactor timeline loading to cursor-based fetch API

This commit is contained in:
Mohamed Boudra
2026-02-14 01:03:36 +07:00
parent c41815dcb7
commit 8169134ac3
22 changed files with 1567 additions and 504 deletions
@@ -1,4 +1,3 @@
import { readFileSync } from "node:fs";
import { afterEach, describe, expect, expectTypeOf, test, vi } from "vitest";
import { DaemonClient, type DaemonTransport } from "./daemon-client";
import {
@@ -60,11 +59,6 @@ function createMockTransport() {
};
}
function loadLegacySnapshotFixture(): unknown {
const url = new URL("../shared/__fixtures__/legacy-agent-stream-snapshot-inProgress.json", import.meta.url);
return JSON.parse(readFileSync(url, "utf8"));
}
function wrapSessionMessage(message: unknown): string {
return JSON.stringify({
type: "session",
@@ -930,7 +924,7 @@ describe("DaemonClient", () => {
expect(logger.warn).toHaveBeenCalled();
});
test("parses canonical agent_stream_snapshot tool_call payloads without crashing", async () => {
test("parses canonical fetch_agent_timeline_response payloads without crashing", async () => {
const logger = createMockLogger();
const mock = createMockTransport();
@@ -947,35 +941,49 @@ describe("DaemonClient", () => {
await connectPromise;
const received: unknown[] = [];
const unsubscribe = client.on("agent_stream_snapshot", (msg) => {
const unsubscribe = client.on("fetch_agent_timeline_response", (msg) => {
received.push(msg);
});
mock.triggerMessage(
wrapSessionMessage({
type: "agent_stream_snapshot",
type: "fetch_agent_timeline_response",
payload: {
requestId: "req-1",
agentId: "agent_cli",
events: [
direction: "tail",
projection: "projected",
epoch: "epoch-1",
reset: false,
staleCursor: false,
gap: false,
window: { minSeq: 1, maxSeq: 1, nextSeq: 2 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 1 },
hasOlder: false,
hasNewer: false,
entries: [
{
timestamp: "2026-02-08T20:20:00.000Z",
event: {
type: "timeline",
provider: "codex",
item: {
type: "tool_call",
callId: "call_cli_snapshot",
name: "shell",
status: "running",
detail: {
type: "shell",
command: "pwd",
},
error: null,
provider: "codex",
seqStart: 1,
seqEnd: 1,
sourceSeqRanges: [{ startSeq: 1, endSeq: 1 }],
collapsed: [],
item: {
type: "tool_call",
callId: "call_cli_snapshot",
name: "shell",
status: "running",
detail: {
type: "shell",
command: "pwd",
},
error: null,
},
},
],
error: null,
},
})
);
@@ -983,35 +991,32 @@ describe("DaemonClient", () => {
unsubscribe();
expect(received).toHaveLength(1);
const snapshotMsg = received[0] as {
const timelineMsg = received[0] as {
payload: {
events: Array<{
event: {
type: "timeline";
item: {
type: "tool_call";
status: string;
error: unknown;
detail: {
type: string;
};
entries: Array<{
item: {
type: "tool_call";
status: string;
error: unknown;
detail: {
type: string;
};
};
}>;
};
};
const firstTimeline = snapshotMsg.payload.events[0]?.event;
expect(firstTimeline?.type).toBe("timeline");
if (firstTimeline?.type === "timeline" && firstTimeline.item.type === "tool_call") {
expect(firstTimeline.item.status).toBe("running");
expect(firstTimeline.item.error).toBeNull();
expect(firstTimeline.item.detail.type).toBe("shell");
const firstEntry = timelineMsg.payload.entries[0];
expect(firstEntry?.item.type).toBe("tool_call");
if (firstEntry?.item.type === "tool_call") {
expect(firstEntry.item.status).toBe("running");
expect(firstEntry.item.error).toBeNull();
expect(firstEntry.item.detail.type).toBe("shell");
}
expect(logger.warn).not.toHaveBeenCalled();
});
test("drops legacy agent_stream_snapshot tool_call payloads and logs validation warning", async () => {
test("drops invalid fetch_agent_timeline_response tool_call payloads and logs validation warning", async () => {
const logger = createMockLogger();
const mock = createMockTransport();
@@ -1028,12 +1033,52 @@ describe("DaemonClient", () => {
await connectPromise;
const received: unknown[] = [];
const unsubscribe = client.on("agent_stream_snapshot", (msg) => {
const unsubscribe = client.on("fetch_agent_timeline_response", (msg) => {
received.push(msg);
});
const snapshot = loadLegacySnapshotFixture();
mock.triggerMessage(wrapSessionMessage(snapshot));
mock.triggerMessage(
wrapSessionMessage({
type: "fetch_agent_timeline_response",
payload: {
requestId: "req-invalid",
agentId: "agent_cli",
direction: "tail",
projection: "projected",
epoch: "epoch-1",
reset: false,
staleCursor: false,
gap: false,
window: { minSeq: 1, maxSeq: 1, nextSeq: 2 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 1 },
hasOlder: false,
hasNewer: false,
entries: [
{
timestamp: "2026-02-08T20:20:00.000Z",
provider: "codex",
seqStart: 1,
seqEnd: 1,
sourceSeqRanges: [{ startSeq: 1, endSeq: 1 }],
collapsed: [],
item: {
type: "tool_call",
callId: "call_cli_invalid",
name: "shell",
status: "inProgress",
detail: {
type: "unknown",
input: { command: "pwd" },
output: null,
},
},
},
],
error: null,
},
})
);
unsubscribe();
+34 -12
View File
@@ -15,6 +15,7 @@ import type {
CreateAgentRequestMessage,
FileDownloadTokenResponse,
FileExplorerResponse,
FetchAgentTimelineResponseMessage,
GitSetupOptions,
CheckoutStatusResponse,
CheckoutCommitResponse,
@@ -139,6 +140,8 @@ export type DaemonEvent =
agentId: string;
event: AgentStreamEventPayload;
timestamp: string;
seq?: number;
epoch?: string;
}
| { type: "status"; payload: { status: string } & Record<string, unknown> }
| { type: "agent_deleted"; agentId: string }
@@ -235,6 +238,20 @@ type TerminalOutputPayload = TerminalOutput["payload"];
type KillTerminalPayload = KillTerminalResponse["payload"];
type AttachTerminalStreamPayload = AttachTerminalStreamResponse["payload"];
type DetachTerminalStreamPayload = DetachTerminalStreamResponse["payload"];
export type FetchAgentTimelinePayload = FetchAgentTimelineResponseMessage["payload"];
export type FetchAgentTimelineDirection = FetchAgentTimelinePayload["direction"];
export type FetchAgentTimelineProjection = FetchAgentTimelinePayload["projection"];
export type FetchAgentTimelineCursor = NonNullable<
FetchAgentTimelinePayload["startCursor"]
>;
export type FetchAgentTimelineOptions = {
direction?: FetchAgentTimelineDirection;
cursor?: FetchAgentTimelineCursor;
limit?: number;
projection?: FetchAgentTimelineProjection;
requestId?: string;
};
export type TerminalStreamChunk = {
streamId: number;
@@ -1244,23 +1261,28 @@ export class DaemonClient {
});
}
async initializeAgent(
async fetchAgentTimeline(
agentId: string,
requestId?: string
): Promise<AgentSnapshotPayload> {
const resolvedRequestId = this.createRequestId(requestId);
options: FetchAgentTimelineOptions = {}
): Promise<FetchAgentTimelinePayload> {
const resolvedRequestId = this.createRequestId(options.requestId);
const message = SessionInboundMessageSchema.parse({
type: "initialize_agent_request",
type: "fetch_agent_timeline_request",
agentId,
requestId: resolvedRequestId,
...(options.direction ? { direction: options.direction } : {}),
...(options.cursor ? { cursor: options.cursor } : {}),
...(typeof options.limit === "number" ? { limit: options.limit } : {}),
...(options.projection ? { projection: options.projection } : {}),
});
const payload = await this.sendRequest({
requestId: resolvedRequestId,
message,
timeout: 10000,
timeout: 15000,
options: { skipQueue: true },
select: (msg) => {
if (msg.type !== "initialize_agent_request") {
if (msg.type !== "fetch_agent_timeline_response") {
return null;
}
if (msg.payload.requestId !== resolvedRequestId) {
@@ -1269,14 +1291,12 @@ export class DaemonClient {
return msg.payload;
},
});
if (payload.error) {
throw new Error(payload.error);
}
const agent = await this.fetchAgent(agentId);
if (!agent) {
throw new Error(`Agent not found after initialize: ${agentId}`);
}
return agent;
return payload;
}
// ============================================================================
@@ -3079,6 +3099,8 @@ export class DaemonClient {
agentId: msg.payload.agentId,
event: msg.payload.event,
timestamp: msg.payload.timestamp,
...(typeof msg.payload.seq === "number" ? { seq: msg.payload.seq } : {}),
...(typeof msg.payload.epoch === "string" ? { epoch: msg.payload.epoch } : {}),
};
case "status":
return { type: "status", payload: msg.payload };