chore: commit all local changes

This commit is contained in:
Mohamed Boudra
2026-02-25 13:53:23 +07:00
parent a060ae1256
commit c4523c70b5
18 changed files with 1818 additions and 67 deletions
@@ -789,6 +789,46 @@ describe("AgentManager", () => {
expect(result.rows[1]?.seq).toBe(4);
});
test("does not trim timeline by default", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-timeline-unbounded-"));
const storagePath = join(workdir, "agents");
const storage = new AgentStorage(storagePath, logger);
const manager = new AgentManager({
clients: {
codex: new TestAgentClient(),
},
registry: storage,
logger,
idFactory: () => "00000000-0000-4000-8000-000000000120",
});
const snapshot = await manager.createAgent({
provider: "codex",
cwd: workdir,
});
await manager.appendTimelineItem(snapshot.id, {
type: "assistant_message",
text: "first",
});
await manager.appendTimelineItem(snapshot.id, {
type: "assistant_message",
text: "second",
});
await manager.appendTimelineItem(snapshot.id, {
type: "assistant_message",
text: "third",
});
const fetched = manager.fetchTimeline(snapshot.id, {
direction: "tail",
limit: 0,
});
expect(fetched.rows).toHaveLength(3);
expect(fetched.window.minSeq).toBe(1);
expect(fetched.window.maxSeq).toBe(3);
});
test("createAgent fails when generated agent ID is not a UUID", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
const storagePath = join(workdir, "agents");
@@ -242,7 +242,6 @@ type LiveEventStreamingSession = AgentSession & {
streamLiveEvents: () => AsyncGenerator<AgentStreamEvent>;
};
const DEFAULT_MAX_TIMELINE_ITEMS = 2000;
const DEFAULT_TIMELINE_FETCH_LIMIT = 200;
const LIVE_BACKLOG_TERMINAL_REPLAY_DELAY_MS = 300;
const BUSY_STATUSES: AgentLifecycleStatus[] = [
@@ -307,7 +306,7 @@ export class AgentManager {
private readonly clients = new Map<AgentProvider, AgentClient>();
private readonly agents = new Map<string, ActiveManagedAgent>();
private readonly subscribers = new Set<SubscriptionRecord>();
private readonly maxTimelineItems: number;
private readonly maxTimelineItems: number | null;
private readonly idFactory: () => string;
private readonly registry?: AgentStorage;
private readonly previousStatuses = new Map<string, AgentLifecycleStatus>();
@@ -322,8 +321,13 @@ export class AgentManager {
private logger: Logger;
constructor(options: AgentManagerOptions) {
const maxTimelineItems = options?.maxTimelineItems;
this.maxTimelineItems =
options?.maxTimelineItems ?? DEFAULT_MAX_TIMELINE_ITEMS;
typeof maxTimelineItems === "number" &&
Number.isFinite(maxTimelineItems) &&
maxTimelineItems >= 0
? Math.floor(maxTimelineItems)
: null;
this.idFactory = options?.idFactory ?? (() => randomUUID());
this.registry = options?.registry;
this.onAgentAttention = options?.onAgentAttention;
@@ -1852,7 +1856,10 @@ export class AgentManager {
agent.timelineNextSeq = timelineState.nextSeq + 1;
agent.timeline.push(item);
timelineState.rows.push(row);
if (agent.timeline.length > this.maxTimelineItems) {
if (
typeof this.maxTimelineItems === "number" &&
agent.timeline.length > this.maxTimelineItems
) {
const removeCount = agent.timeline.length - this.maxTimelineItems;
agent.timeline.splice(0, removeCount);
timelineState.rows.splice(0, removeCount);
@@ -1,7 +1,10 @@
import { describe, expect, test } from "vitest";
import type { AgentTimelineRow } from "./agent-manager.js";
import { projectTimelineRows } from "./timeline-projection.js";
import {
projectTimelineRows,
selectTimelineWindowByProjectedLimit,
} from "./timeline-projection.js";
describe("projectTimelineRows", () => {
test("merges adjacent assistant chunks in projected mode", () => {
@@ -116,3 +119,302 @@ describe("projectTimelineRows", () => {
expect(projected[1]?.collapsed).toEqual([]);
});
});
describe("selectTimelineWindowByProjectedLimit", () => {
test("tail limit selects canonical rows for the latest projected entries", () => {
const rows: AgentTimelineRow[] = [
{
seq: 1,
timestamp: "2026-02-13T00:00:00.000Z",
item: { type: "assistant_message", text: "Hel" },
},
{
seq: 2,
timestamp: "2026-02-13T00:00:00.010Z",
item: { type: "assistant_message", text: "lo" },
},
{
seq: 3,
timestamp: "2026-02-13T00:00:00.020Z",
item: { type: "user_message", text: "next" },
},
{
seq: 4,
timestamp: "2026-02-13T00:00:00.030Z",
item: { type: "assistant_message", text: "Wor" },
},
{
seq: 5,
timestamp: "2026-02-13T00:00:00.040Z",
item: { type: "assistant_message", text: "ld" },
},
];
const selected = selectTimelineWindowByProjectedLimit({
rows,
provider: "codex",
direction: "tail",
limit: 1,
});
expect(selected.minSeq).toBe(4);
expect(selected.maxSeq).toBe(5);
expect(selected.selectedRows.map((row) => row.seq)).toEqual([4, 5]);
expect(selected.projectedEntries).toHaveLength(1);
expect(selected.projectedEntries[0]?.item).toEqual({
type: "assistant_message",
text: "World",
});
});
test("after limit selects canonical rows for the earliest projected entries", () => {
const rows: AgentTimelineRow[] = [
{
seq: 10,
timestamp: "2026-02-13T00:00:00.000Z",
item: { type: "assistant_message", text: "A" },
},
{
seq: 11,
timestamp: "2026-02-13T00:00:00.010Z",
item: { type: "assistant_message", text: "B" },
},
{
seq: 12,
timestamp: "2026-02-13T00:00:00.020Z",
item: { type: "user_message", text: "u1" },
},
{
seq: 13,
timestamp: "2026-02-13T00:00:00.030Z",
item: { type: "user_message", text: "u2" },
},
];
const selected = selectTimelineWindowByProjectedLimit({
rows,
provider: "claude",
direction: "after",
limit: 2,
});
expect(selected.minSeq).toBe(10);
expect(selected.maxSeq).toBe(12);
expect(selected.selectedRows.map((row) => row.seq)).toEqual([10, 11, 12]);
expect(selected.projectedEntries).toHaveLength(2);
});
test("uses max seqEnd across selected projected entries when tool lifecycle seqEnd is non-monotonic", () => {
const rows: AgentTimelineRow[] = [
{
seq: 1,
timestamp: "2026-02-13T00:00:00.000Z",
item: {
type: "tool_call",
callId: "call_1",
name: "shell",
status: "running",
error: null,
detail: {
type: "unknown",
input: { cmd: "pwd" },
output: null,
},
},
},
{
seq: 2,
timestamp: "2026-02-13T00:00:00.100Z",
item: { type: "assistant_message", text: "working" },
},
{
seq: 3,
timestamp: "2026-02-13T00:00:00.200Z",
item: {
type: "tool_call",
callId: "call_1",
name: "shell",
status: "completed",
error: null,
detail: {
type: "unknown",
input: { cmd: "pwd" },
output: { stdout: "/tmp" },
},
},
},
];
const selected = selectTimelineWindowByProjectedLimit({
rows,
provider: "codex",
direction: "tail",
limit: 2,
});
expect(selected.projectedEntries).toHaveLength(2);
expect(selected.minSeq).toBe(1);
expect(selected.maxSeq).toBe(3);
expect(selected.selectedRows.map((row) => row.seq)).toEqual([1, 2, 3]);
});
test("expands projected entries for overlapping seq ranges", () => {
const rows: AgentTimelineRow[] = [
{
seq: 1,
timestamp: "2026-02-13T00:00:00.000Z",
item: {
type: "tool_call",
callId: "call_1",
name: "shell",
status: "running",
error: null,
detail: {
type: "unknown",
input: { cmd: "pwd" },
output: null,
},
},
},
{
seq: 2,
timestamp: "2026-02-13T00:00:00.100Z",
item: { type: "assistant_message", text: "work" },
},
{
seq: 3,
timestamp: "2026-02-13T00:00:00.200Z",
item: { type: "assistant_message", text: "ing" },
},
{
seq: 4,
timestamp: "2026-02-13T00:00:00.300Z",
item: {
type: "tool_call",
callId: "call_1",
name: "shell",
status: "completed",
error: null,
detail: {
type: "unknown",
input: { cmd: "pwd" },
output: { stdout: "/tmp" },
},
},
},
];
const selected = selectTimelineWindowByProjectedLimit({
rows,
provider: "codex",
direction: "after",
limit: 1,
});
expect(selected.minSeq).toBe(1);
expect(selected.maxSeq).toBe(4);
expect(selected.selectedRows.map((row) => row.seq)).toEqual([1, 2, 3, 4]);
expect(selected.projectedEntries).toHaveLength(2);
expect(selected.projectedEntries.map((entry) => entry.item.type)).toEqual([
"tool_call",
"assistant_message",
]);
});
test("before direction selects the latest projected entries from the earlier window", () => {
const rows: AgentTimelineRow[] = [
{
seq: 1,
timestamp: "2026-02-13T00:00:00.000Z",
item: { type: "assistant_message", text: "a" },
},
{
seq: 2,
timestamp: "2026-02-13T00:00:00.100Z",
item: { type: "assistant_message", text: "b" },
},
{
seq: 3,
timestamp: "2026-02-13T00:00:00.200Z",
item: { type: "user_message", text: "u1" },
},
{
seq: 4,
timestamp: "2026-02-13T00:00:00.300Z",
item: { type: "user_message", text: "u2" },
},
];
const selected = selectTimelineWindowByProjectedLimit({
rows,
provider: "claude",
direction: "before",
limit: 1,
});
expect(selected.minSeq).toBe(4);
expect(selected.maxSeq).toBe(4);
expect(selected.selectedRows.map((row) => row.seq)).toEqual([4]);
expect(selected.projectedEntries).toHaveLength(1);
expect(selected.projectedEntries[0]?.item).toEqual({
type: "user_message",
text: "u2",
});
});
test("can enforce a hard projected limit when tool lifecycle collapsing is disabled", () => {
const rows: AgentTimelineRow[] = [
{
seq: 1,
timestamp: "2026-02-13T00:00:00.000Z",
item: {
type: "tool_call",
callId: "call_1",
name: "shell",
status: "running",
error: null,
detail: {
type: "unknown",
input: { cmd: "pwd" },
output: null,
},
},
},
{
seq: 2,
timestamp: "2026-02-13T00:00:00.100Z",
item: { type: "assistant_message", text: "work" },
},
{
seq: 3,
timestamp: "2026-02-13T00:00:00.200Z",
item: {
type: "tool_call",
callId: "call_1",
name: "shell",
status: "completed",
error: null,
detail: {
type: "unknown",
input: { cmd: "pwd" },
output: { stdout: "/tmp" },
},
},
},
];
const selected = selectTimelineWindowByProjectedLimit({
rows,
provider: "codex",
direction: "tail",
limit: 1,
collapseToolLifecycle: false,
});
expect(selected.minSeq).toBe(3);
expect(selected.maxSeq).toBe(3);
expect(selected.selectedRows.map((row) => row.seq)).toEqual([3]);
expect(selected.projectedEntries).toHaveLength(1);
expect(selected.projectedEntries[0]?.item.type).toBe("tool_call");
});
});
@@ -9,6 +9,7 @@ export type TimelineSeqRange = {
};
export type TimelineProjectionKind = "assistant_merge" | "tool_lifecycle";
export type TimelineLimitDirection = "tail" | "before" | "after";
export type TimelineProjectionEntry = {
provider: AgentProvider;
@@ -21,6 +22,12 @@ export type TimelineProjectionEntry = {
};
type WorkingEntry = TimelineProjectionEntry;
type ProjectedWindowSelection = {
projectedEntries: TimelineProjectionEntry[];
selectedRows: AgentTimelineRow[];
minSeq: number | null;
maxSeq: number | null;
};
function appendSeqToRanges(ranges: TimelineSeqRange[], seq: number): TimelineSeqRange[] {
if (ranges.length === 0) {
@@ -207,3 +214,98 @@ export function projectTimelineRows(
const toolCollapsed = collapseToolLifecycle(canonical);
return mergeAssistantChunks(toolCollapsed);
}
/**
* Select a timeline window based on projected-entry count, then map it back to
* contiguous canonical rows. This avoids cutting through merged assistant
* chunks when callers request canonical rows with a bounded limit.
*/
export function selectTimelineWindowByProjectedLimit(input: {
rows: readonly AgentTimelineRow[];
provider: AgentProvider;
direction: TimelineLimitDirection;
limit: number;
collapseToolLifecycle?: boolean;
}): ProjectedWindowSelection {
const { rows, provider, direction } = input;
const limit = Math.max(0, Math.floor(input.limit));
const collapseTools = input.collapseToolLifecycle ?? true;
const canonical = makeCanonicalEntries(rows, provider);
const projectedAll = mergeAssistantChunks(
collapseTools ? collapseToolLifecycle(canonical) : canonical
);
if (projectedAll.length === 0) {
return {
projectedEntries: [],
selectedRows: [],
minSeq: null,
maxSeq: null,
};
}
const projectedEntries =
limit === 0 || limit >= projectedAll.length
? projectedAll
: direction === "after"
? projectedAll.slice(0, limit)
: projectedAll.slice(projectedAll.length - limit);
if (projectedEntries.length === 0) {
return {
projectedEntries: [],
selectedRows: [],
minSeq: null,
maxSeq: null,
};
}
const computeWindowBounds = (entries: readonly TimelineProjectionEntry[]) => {
let minSeq = Number.POSITIVE_INFINITY;
let maxSeq = Number.NEGATIVE_INFINITY;
for (const entry of entries) {
if (entry.seqStart < minSeq) {
minSeq = entry.seqStart;
}
if (entry.seqEnd > maxSeq) {
maxSeq = entry.seqEnd;
}
}
return { minSeq, maxSeq };
};
let { minSeq, maxSeq } = computeWindowBounds(projectedEntries);
let expandedEntries = projectedEntries;
if (collapseTools) {
// Expand to include any projected entries that overlap the selected
// canonical range. Tool lifecycle collapse can produce non-monotonic
// seqEnd values, which would otherwise create cursor gaps.
for (let iteration = 0; iteration < projectedAll.length + 1; iteration += 1) {
const overlapping = projectedAll.filter(
(entry) => entry.seqStart <= maxSeq && entry.seqEnd >= minSeq
);
const nextBounds = computeWindowBounds(overlapping);
if (
overlapping.length === expandedEntries.length &&
nextBounds.minSeq === minSeq &&
nextBounds.maxSeq === maxSeq
) {
expandedEntries = overlapping;
break;
}
expandedEntries = overlapping;
minSeq = nextBounds.minSeq;
maxSeq = nextBounds.maxSeq;
}
}
const selectedRows = rows.filter((row) => row.seq >= minSeq && row.seq <= maxSeq);
return {
projectedEntries: expandedEntries,
selectedRows,
minSeq: Number.isFinite(minSeq) ? minSeq : null,
maxSeq: Number.isFinite(maxSeq) ? maxSeq : null,
};
}
@@ -0,0 +1,98 @@
import { describe, test, expect, beforeEach, afterEach } from "vitest";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { createDaemonTestContext, type DaemonTestContext } from "../test-utils/index.js";
function tmpCwd(): string {
return mkdtempSync(path.join(tmpdir(), "daemon-e2e-"));
}
describe("daemon E2E - timeline window", () => {
let ctx: DaemonTestContext;
beforeEach(async () => {
ctx = await createDaemonTestContext();
});
afterEach(async () => {
await ctx.cleanup();
}, 60_000);
test(
"canonical tail limit keeps assistant chunks intact at the window boundary",
async () => {
const cwd = tmpCwd();
try {
const agent = await ctx.client.createAgent({
provider: "codex",
cwd,
title: "Timeline Window Boundary Test",
modeId: "full-access",
});
const expected = "1234567890ABCDEFGHIJ";
await ctx.client.sendMessage(agent.id, `Respond with exactly: ${expected}`);
const finalState = await ctx.client.waitForFinish(agent.id, 5_000);
expect(finalState.status).toBe("idle");
const timeline = await ctx.client.fetchAgentTimeline(agent.id, {
direction: "tail",
limit: 1,
projection: "canonical",
});
const assistantTexts = timeline.entries
.filter((entry) => entry.item.type === "assistant_message")
.map((entry) => entry.item.text);
expect(assistantTexts).toHaveLength(2);
expect(assistantTexts.join("")).toBe(expected);
expect(timeline.startCursor?.seq).toBeLessThan(timeline.endCursor?.seq ?? 0);
} finally {
rmSync(cwd, { recursive: true, force: true });
}
},
30_000
);
test(
"canonical tail limit does not widen to full history once boundary is resolved",
async () => {
const cwd = tmpCwd();
try {
const agent = await ctx.client.createAgent({
provider: "codex",
cwd,
title: "Timeline Window Scope Test",
modeId: "full-access",
});
await ctx.client.sendMessage(agent.id, "Respond with exactly: FIRST-RESPONSE");
expect((await ctx.client.waitForFinish(agent.id, 5_000)).status).toBe("idle");
const expected = "SECOND-RESPONSE";
await ctx.client.sendMessage(agent.id, `Respond with exactly: ${expected}`);
expect((await ctx.client.waitForFinish(agent.id, 5_000)).status).toBe("idle");
const timeline = await ctx.client.fetchAgentTimeline(agent.id, {
direction: "tail",
limit: 1,
projection: "canonical",
});
const assistantTexts = timeline.entries
.filter((entry) => entry.item.type === "assistant_message")
.map((entry) => entry.item.text);
expect(assistantTexts.join("")).toBe(expected);
expect(timeline.hasOlder).toBe(true);
expect(timeline.startCursor?.seq).toBeGreaterThan(1);
} finally {
rmSync(cwd, { recursive: true, force: true });
}
},
30_000
);
});
+93 -12
View File
@@ -68,7 +68,11 @@ import {
appendTimelineItemIfAgentKnown,
emitLiveTimelineItemIfAgentKnown,
} from './agent/timeline-append.js'
import { projectTimelineRows, type TimelineProjectionMode } from './agent/timeline-projection.js'
import {
projectTimelineRows,
selectTimelineWindowByProjectedLimit,
type TimelineProjectionMode,
} from './agent/timeline-projection.js'
import {
DEFAULT_STRUCTURED_GENERATION_PROVIDERS,
StructuredAgentFallbackError,
@@ -5279,7 +5283,13 @@ export class Session {
): Promise<void> {
const direction: AgentTimelineFetchDirection = msg.direction ?? (msg.cursor ? 'after' : 'tail')
const projection: TimelineProjectionMode = msg.projection ?? 'projected'
const limit = msg.limit ?? (direction === 'after' ? 0 : undefined)
const requestedLimit = msg.limit
const limit = requestedLimit ?? (direction === 'after' ? 0 : undefined)
const shouldLimitByProjectedWindow =
projection === 'canonical' &&
direction === 'tail' &&
typeof requestedLimit === 'number' &&
requestedLimit > 0
const cursor: AgentTimelineCursor | undefined = msg.cursor
? {
epoch: msg.cursor.epoch,
@@ -5290,18 +5300,89 @@ export class Session {
try {
const snapshot = await this.ensureAgentLoaded(msg.agentId)
const timeline = this.agentManager.fetchTimeline(msg.agentId, {
let timeline = this.agentManager.fetchTimeline(msg.agentId, {
direction,
cursor,
limit,
limit:
shouldLimitByProjectedWindow && typeof requestedLimit === 'number'
? Math.max(1, Math.floor(requestedLimit))
: limit,
})
const projected = projectTimelineRows(timeline.rows, snapshot.provider, projection)
let hasOlder = timeline.hasOlder
let hasNewer = timeline.hasNewer
let startCursor: { epoch: string; seq: number } | null = null
let endCursor: { epoch: string; seq: number } | null = null
let entries: ReturnType<typeof projectTimelineRows>
const firstRow = timeline.rows[0]
const lastRow = timeline.rows[timeline.rows.length - 1]
const startCursor = firstRow ? { epoch: timeline.epoch, seq: firstRow.seq } : null
const endCursor = lastRow ? { epoch: timeline.epoch, seq: lastRow.seq } : null
if (shouldLimitByProjectedWindow) {
const projectedLimit = Math.max(1, Math.floor(requestedLimit))
let fetchLimit = projectedLimit
let projectedWindow = selectTimelineWindowByProjectedLimit({
rows: timeline.rows,
provider: snapshot.provider,
direction,
limit: projectedLimit,
collapseToolLifecycle: false,
})
while (timeline.hasOlder) {
const needsMoreProjectedEntries =
projectedWindow.projectedEntries.length < projectedLimit
const firstLoadedRow = timeline.rows[0]
const firstSelectedRow = projectedWindow.selectedRows[0]
const startsAtLoadedBoundary =
firstLoadedRow != null &&
firstSelectedRow != null &&
firstSelectedRow.seq === firstLoadedRow.seq
const boundaryIsAssistantChunk =
startsAtLoadedBoundary && firstLoadedRow.item.type === 'assistant_message'
if (!needsMoreProjectedEntries && !boundaryIsAssistantChunk) {
break
}
const maxRows = Math.max(
0,
timeline.window.maxSeq - timeline.window.minSeq + 1
)
const nextFetchLimit = Math.min(maxRows, fetchLimit * 2)
if (nextFetchLimit <= fetchLimit) {
break
}
fetchLimit = nextFetchLimit
timeline = this.agentManager.fetchTimeline(msg.agentId, {
direction,
cursor,
limit: fetchLimit,
})
projectedWindow = selectTimelineWindowByProjectedLimit({
rows: timeline.rows,
provider: snapshot.provider,
direction,
limit: projectedLimit,
collapseToolLifecycle: false,
})
}
const selectedRows = projectedWindow.selectedRows
entries = projectTimelineRows(selectedRows, snapshot.provider, projection)
if (projectedWindow.minSeq !== null && projectedWindow.maxSeq !== null) {
startCursor = { epoch: timeline.epoch, seq: projectedWindow.minSeq }
endCursor = { epoch: timeline.epoch, seq: projectedWindow.maxSeq }
hasOlder = projectedWindow.minSeq > timeline.window.minSeq
hasNewer = false
}
} else {
const firstRow = timeline.rows[0]
const lastRow = timeline.rows[timeline.rows.length - 1]
startCursor = firstRow ? { epoch: timeline.epoch, seq: firstRow.seq } : null
endCursor = lastRow ? { epoch: timeline.epoch, seq: lastRow.seq } : null
entries = projectTimelineRows(timeline.rows, snapshot.provider, projection)
}
this.emit({
type: 'fetch_agent_timeline_response',
@@ -5317,9 +5398,9 @@ export class Session {
window: timeline.window,
startCursor,
endCursor,
hasOlder: timeline.hasOlder,
hasNewer: timeline.hasNewer,
entries: projected,
hasOlder,
hasNewer,
entries,
error: null,
},
})