Agent chat: an older page folds without folding the held log again (#20)
jonas, 2026-11-28 17:45 UTC · 1613b55e0c69827298539a3344dc270acfad2f55 · parent d7e74c9
2 files changed
M src/components/agent-chat/agent-events.test.ts
@@ -387,3 +387,38 @@ function input(offset: number) { return quiet(offset, `input ${String(offset)}`); } + +test("an older page folds without the held log: at every cut of a long log, page by page, the fold is the whole fold's, and the held chunks that began from the same state are kept", () => { + // 400 turns: a question, a request and its answer; every seventh turn is cut in two by the page + const log: ReturnType<typeof said>[] = []; + for (let turnAt = 0; turnAt < 400; turnAt += 1) { + const at = 1 + turnAt * 5; + log.push( + said(at, `question ${turnAt}`), + request(at + 1), + settled(at + 2, at + 1, succeeded("")), + sent(at + 3, `answer ${turnAt}`), + ); + } + const whole = foldAgentLog(undefined, log); + expect(whole.chunks!.length).toBeGreaterThan(4); + for (const cut of [1, 2, 3, 255, 256, 257, 700, 1001, 1598]) { + const newest = foldAgentLog(undefined, log.slice(cut)); + // the page in two parts, the second with a row that arrives at the end + const half = Math.floor(cut / 2); + const one = foldAgentLog(newest, log.slice(half)); + const two = foldAgentLog(one, log); + expect(two.items).toEqual(whole.items); + expect(two.state).toEqual(whole.state); + expect(two.events).toEqual(whole.events); + // what was held is not folded again: its chunks are the same objects, but the first ones + const kept = one.chunks!.filter((chunk) => newest.chunks!.includes(chunk)).length; + expect(kept).toBeGreaterThanOrEqual(newest.chunks!.length - 2); + // a row that says the same is the same object + const last = (fold: typeof whole) => fold.items.at(-1); + expect(last(two)).toBe(last(newest)); + } + // a page and a new row at the end in one step + const newest = foldAgentLog(undefined, log.slice(800, -1)); + expect(foldAgentLog(newest, log).items).toEqual(whole.items); +});
M src/components/agent-chat/agent-events.ts
@@ -43,6 +43,20 @@ "events.iterate.com/itx/version-ended", ]); +/** A stretch of the fold, kept so that an older page does not fold the held log again: the state + * it began from, the events it folded, the reducer's items for them (before the runs are joined) + * and the state it ended in. The reducer is a pure function of a state and an event, so a chunk + * that begins from an equal state gives these same items and this same end. */ +type FoldChunk = { + start: AgentUiState; + events: readonly StreamEvent[]; + items: readonly AgentUiItem[]; + end: AgentUiState; +}; + +/** How many events a chunk holds at most. */ +const CHUNK = 256; + /** The log folded so far, which the next call goes on from. */ export type AgentLogFold = { /** The rows folded, as the caller's array held them: how the next call tells what grew. */ @@ -54,6 +68,8 @@ /** The offset of the newest `itx/started-over` held, or null: the current version starts after * it, and the chat reads no page older than it. */ versionEndedAt: number | null; + /** The fold in stretches, for an older page (`FoldChunk`). */ + chunks?: readonly FoldChunk[]; }; const NOTHING_FOLDED: AgentLogFold = { @@ -62,10 +78,80 @@ state: initialAgentUiState(), items: [], versionEndedAt: null, + chunks: [], }; +/** `events` folded from `start`, in chunks. */ +function chunksOf(start: AgentUiState, events: readonly StreamEvent[]): FoldChunk[] { + const chunks: FoldChunk[] = []; + let state = start; + for (let at = 0; at < events.length; at += CHUNK) { + const own = events.slice(at, at + CHUNK); + const items: AgentUiItem[] = []; + const began = state; + for (const event of own) { + const reduced = reduceAgentUi(state, event); + state = reduced.endState; + items.push(...reduced.items); + } + chunks.push({ start: began, events: own, items, end: state }); + } + return chunks; +} + +/** Two states that the reducer cannot tell apart: plain data, compared as its text. */ +const sameState = (one: AgentUiState, other: AgentUiState) => + one === other || JSON.stringify(one) === JSON.stringify(other); + +/** AN OLDER PAGE, WITHOUT FOLDING THE HELD LOG AGAIN. The page is folded from the start, and then + * each held chunk again only until the state reaches what a held chunk began from: from that + * chunk on, the held items and the held end are the fold's own. In a log of turns that is the + * first held chunk or the second, since a turn that ended leaves the state as it began. Measured + * 28 Nov 2026 on the engineering manager's chat: each older page that landed folded the whole + * held log, 13 to 87 ms of a frame, more with each page. Null: the rows are no older page of + * what is held. */ +function withOlderPage(held: AgentLogFold, log: readonly unknown[]): AgentLogFold | null { + const chunks = held.chunks; + const added = log.length - held.log.length; + if ( + !chunks || + held.log.length === 0 || + added <= 0 || + log[added] !== held.log[0] || + log.at(-1) !== held.log.at(-1) + ) + return null; + // the held log is one version's from a border on: no page below the border is read + if (held.versionEndedAt !== null) return { ...held, log }; + const arrived = log.slice(0, added).flatMap((row) => toAgentEvent(row) ?? []); + const border = arrived.findLast((event) => STARTED_OVER.has(event.type)); + const older = border ? arrived.slice(arrived.indexOf(border) + 1) : arrived; + const fresh = chunksOf(initialAgentUiState(), older); + let state = fresh.at(-1)?.end ?? initialAgentUiState(); + let reused = 0; + for (; reused < chunks.length; reused += 1) { + const chunk = chunks[reused]!; + if (sameState(state, chunk.start)) break; + const [again] = chunksOf(state, chunk.events); + if (!again) continue; + fresh.push(again); + state = again.end; + } + const all = fresh.concat(chunks.slice(reused)); + const rows = inRuns(all.flatMap((chunk) => chunk.items)); + return { + log, + events: older.length > 0 ? older.concat(held.events) : held.events, + state: reused < chunks.length ? held.state : state, + items: keepingHeldMessages(rows, held.items), + versionEndedAt: border ? border.offset : null, + chunks: all, + }; +} + /** `log`, sorted by offset, folded through the reducer: on from `held` when the log only grew at its - * end, so a live tail costs what arrived; from the start otherwise (an older page). Either way a + * end, so a live tail costs what arrived; with an older page before what is held, only that page + * and the held chunks that it changes (`withOlderPage`); from the start otherwise. Either way a * settled row keeps its identity, so a memoised row skips the re-render that a streamed frame or an * older page would bring and its markdown is not parsed again. ONLY THE CURRENT VERSION is folded: * the events after the newest `itx/started-over` held. The feed, the live line and the traces @@ -79,20 +165,48 @@ held.log.length > 0 && log[0] === held.log[0] && log[held.log.length - 1] === held.log.at(-1); + if (held && !grewAtEnd) { + // an older page alone, or one with new rows at the end too: the page first, then the rows + const from = held.log.length > 0 ? log.indexOf(held.log[0]) : -1; + const through = from + held.log.length; + if (from > 0 && through <= log.length && log[through - 1] === held.log.at(-1)) { + const paged = withOlderPage(held, log.slice(0, through)); + if (paged) + return through === log.length + ? paged + : foldAgentLog({ ...paged, log: log.slice(0, through) }, log); + } + } const from = grewAtEnd ? held : NOTHING_FOLDED; const arrived = log.slice(from.log.length).flatMap((row) => toAgentEvent(row) ?? []); const border = arrived.findLast((event) => STARTED_OVER.has(event.type)); // a border starts the fold over after it: the facts at lower offsets are another version's const start = border ? { ...NOTHING_FOLDED, versionEndedAt: border.offset } : from; const fresh = border ? arrived.slice(arrived.indexOf(border) + 1) : arrived; - let { state } = start; - const items: AgentUiItem[] = []; - for (const event of fresh) { - const reduced = reduceAgentUi(state, event); - state = reduced.endState; - items.push(...reduced.items); - } - const rows = inRuns(items); + // what arrived goes on in the last chunk while that has room, so a live tail makes no chunk for + // each event; a fold with no chunks (an older caller's) keeps none + const before = start.chunks; + const last = before?.at(-1); + const joins = last && last.events.length + fresh.length <= CHUNK ? last : undefined; + const added = chunksOf(start.state, fresh); + const chunks = + before === undefined + ? undefined + : fresh.length === 0 + ? before + : joins + ? [ + ...before.slice(0, -1), + { + start: joins.start, + events: joins.events.concat(fresh), + items: joins.items.concat(added.flatMap((chunk) => chunk.items)), + end: added.at(-1)!.end, + }, + ] + : before.concat(added); + const state = added.at(-1)?.end ?? start.state; + const rows = inRuns(added.flatMap((chunk) => chunk.items)); return { log, events: fresh.length > 0 ? start.events.concat(fresh) : start.events, @@ -104,6 +218,7 @@ : keepingHeldMessages(rows, held?.items) : start.items, versionEndedAt: start.versionEndedAt, + chunks, }; } @@ -128,19 +243,17 @@ return [...held.slice(0, -1), grown, ...rest]; } -/** `items`, with each message that `held` has as the object `held` has. A message is one event, so - * the same id is the same words; an activity can gain steps from an older page, so it is new, and a - * run of inputs is the same only at the same length. */ +/** `items`, with each row that `held` has, and that says the same, as the object `held` has: a + * memoised row is then not drawn again. An activity can gain steps from an older page, so it is + * new. A message is the same only when it says the same: a message whose sender stands in an older + * page was drawn without the sender until that page came (the first row of a held log, found on a + * real log 28 Nov 2026: the id was the same and the words were not, and the earlier row stayed). */ function keepingHeldMessages(items: AgentUiItem[], held: readonly AgentUiItem[] = []) { const heldById = new Map(held.map((item) => [item.id, item])); return items.map((item) => { const kept = heldById.get(item.id); - if (!kept || item.kind === "activity") return item; - const grown = - item.kind === "background" && - kept.kind === "background" && - item.messages.length !== kept.messages.length; - return grown ? item : kept; + if (!kept || kept === item || item.kind === "activity" || kept.kind !== item.kind) return item; + return JSON.stringify(kept) === JSON.stringify(item) ? kept : item; }); }