Open History to see the last commit
1import type {
2 OrchestrationV2ProjectedTurnItem,
3 OrchestrationV2Subagent,
4 OrchestrationV2ThreadHistoryPage,
5 OrchestrationV2ThreadProjection,
6 OrchestrationV2TurnItem,
7} from "@t3tools/contracts";
8import { isOrchestrationV2TurnItemVisible } from "@t3tools/shared/orchestrationV2Timeline";
9
10export type ThreadHistoryGapSeam = {
11 readonly seamItemId: string;
12 readonly ordinal: number;
13};
14
15/** The skipped rows strictly between `afterOrdinal` and the seam, loaded from the newest back. */
16export type ThreadHistoryGap = ThreadHistoryGapSeam & {
17 readonly afterOrdinal: number;
18 readonly cursor: string;
19};
20
21export type ThreadHistoryMeta = {
22 readonly historyCursor: string | null;
23 readonly topSeam?: ThreadHistoryGapSeam;
24 readonly hasMoreHistory: boolean;
25 readonly loading: boolean;
26 readonly error: string | null;
27 readonly expanded: boolean;
28 readonly latestLocalTurnOrdinal: number | null;
29 /** In timeline order. Only a thread of its own rows has any: their ordinals place a page. */
30 readonly gaps?: ReadonlyArray<ThreadHistoryGap>;
31};
32
33export function oldestHistorySeam(
34 items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
35): ThreadHistoryGapSeam | undefined {
36 const first = items.find((row) => row.item.type !== "run_interrupt_request");
37 return first && { seamItemId: first.sourceItemId, ordinal: first.item.ordinal };
38}
39
40/** Whether `cursor` still loads rows the timeline lacks: its top, or one of its gaps. */
41export function holdsHistoryCursor(history: ThreadHistoryMeta, cursor: string): boolean {
42 return (
43 history.historyCursor === cursor || (history.gaps ?? []).some((gap) => gap.cursor === cursor)
44 );
45}
46
47export const EMPTY_THREAD_HISTORY_META: ThreadHistoryMeta = {
48 historyCursor: null,
49 hasMoreHistory: false,
50 loading: false,
51 error: null,
52 expanded: false,
53 latestLocalTurnOrdinal: null,
54};
55
56export function clearActiveHistoryLoading(
57 requestCursor: string,
58 history: ThreadHistoryMeta,
59): ThreadHistoryMeta {
60 if (!holdsHistoryCursor(history, requestCursor) || !history.loading) {
61 return history;
62 }
63 return { ...history, loading: false };
64}
65
66function projectedItemKey(row: OrchestrationV2ProjectedTurnItem): string {
67 return `${row.sourceThreadId}:${row.sourceItemId}`;
68}
69
70function renumberVisible(
71 rows: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
72): OrchestrationV2ProjectedTurnItem[] {
73 return rows.map((row, position) => (row.position === position ? row : { ...row, position }));
74}
75
76// A page that can land between rows the timeline holds goes where its ordinals say.
77function placeByOrdinal(
78 current: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
79 page: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
80): OrchestrationV2ProjectedTurnItem[] {
81 const held = new Set(current.map(projectedItemKey));
82 const fresh = page.filter((row) => !held.has(projectedItemKey(row)));
83 const merged: OrchestrationV2ProjectedTurnItem[] = [];
84 let next = 0;
85 for (const row of current) {
86 while (next < fresh.length && fresh[next]!.item.ordinal < row.item.ordinal)
87 merged.push(fresh[next++]!);
88 merged.push(row);
89 }
90 merged.push(...fresh.slice(next));
91 return merged;
92}
93
94// A page is a contiguous history range, so current rows before its first
95// visible row are older than the page start and new page rows sit just
96// before the next row both lists share.
97function interleavePage(
98 current: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
99 page: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
100 pageKeys: ReadonlySet<string>,
101): OrchestrationV2ProjectedTurnItem[] {
102 const currentIndex = new Map(current.map((row, index) => [projectedItemKey(row), index]));
103 const merged: OrchestrationV2ProjectedTurnItem[] = [];
104 let pending: OrchestrationV2ProjectedTurnItem[] = [];
105 let next = 0;
106 const emitCurrentThrough = (end: number) => {
107 for (; next < end; next += 1) {
108 const row = current[next]!;
109 if (!pageKeys.has(projectedItemKey(row))) merged.push(row);
110 }
111 };
112 for (const row of page) {
113 const index = currentIndex.get(projectedItemKey(row));
114 if (index === undefined) {
115 pending.push(row);
116 continue;
117 }
118 emitCurrentThrough(index + 1);
119 merged.push(...pending, row);
120 pending = [];
121 }
122 merged.push(...pending);
123 emitCurrentThrough(current.length);
124 return merged;
125}
126
127export function mergeOlderHistoryIntoProjection(
128 projection: OrchestrationV2ThreadProjection,
129 olderItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
130 work?: { readonly anchorId: string; readonly nextCursor: string | null },
131 /** The page may sit between rows already held, as one beside a gap does. */
132 detached = false,
133): OrchestrationV2ThreadProjection {
134 if (olderItems.length === 0 && work === undefined) {
135 return projection;
136 }
137
138 const start =
139 work === undefined
140 ? -1
141 : projection.visibleTurnItems.findIndex((row) => row.sourceItemId === work.anchorId);
142 const anchor = projection.visibleTurnItems[start];
143 const deferred = anchor?.item.deferredWork;
144 if (work !== undefined && deferred === undefined) return projection;
145 const currentByKey = new Map(
146 projection.visibleTurnItems.map((row) => [projectedItemKey(row), row]),
147 );
148 const rolledBackRuns = new Set(
149 projection.runs.filter((run) => run.status === "rolled_back").map((run) => run.id),
150 );
151 const turnItemById = new Map(projection.turnItems.map((item) => [String(item.id), item]));
152 const pageKeys = new Set<string>();
153 const page: OrchestrationV2ProjectedTurnItem[] = [];
154 for (const pageRow of olderItems) {
155 if (
156 work &&
157 anchor &&
158 deferred &&
159 (pageRow.sourceThreadId !== anchor.sourceThreadId ||
160 pageRow.item.ordinal < anchor.item.ordinal ||
161 pageRow.item.ordinal > deferred.lastOrdinal)
162 )
163 continue;
164 const key = projectedItemKey(pageRow);
165 if (pageKeys.has(key)) continue;
166 let row = currentByKey.get(key) ?? pageRow;
167 if (
168 !currentByKey.has(key) &&
169 (row.visibility === "local" || row.sourceThreadId === projection.thread.id)
170 ) {
171 const currentItem = turnItemById.get(String(row.sourceItemId));
172 // Hidden live items stay hidden. Snapshots also retain interrupt requests and
173 // pending request cards outside the visible window; their history page shows them.
174 if (currentItem !== undefined) {
175 if (
176 (currentItem.type !== "run_interrupt_request" &&
177 currentItem.type !== "approval_request" &&
178 currentItem.type !== "user_input_request") ||
179 !isOrchestrationV2TurnItemVisible({
180 item: currentItem,
181 runs: projection.runs,
182 attempts: projection.attempts,
183 items: projection.turnItems,
184 })
185 )
186 continue;
187 row = { ...row, item: currentItem };
188 }
189 // A rollback can arrive before a history page for rows outside the loaded window.
190 if (row.item.runId !== null && rolledBackRuns.has(row.item.runId)) continue;
191 }
192 pageKeys.add(key);
193 page.push(row);
194 if (
195 (row.visibility === "local" || row.sourceThreadId === projection.thread.id) &&
196 !turnItemById.has(String(row.sourceItemId))
197 )
198 turnItemById.set(String(row.sourceItemId), row.item);
199 }
200 if (page.length === 0 && work === undefined) return projection;
201 let visible: OrchestrationV2ProjectedTurnItem[];
202 if (work && anchor && deferred) {
203 let end = start + 1;
204 while (end < projection.visibleTurnItems.length) {
205 const row = projection.visibleTurnItems[end]!;
206 if (
207 row.sourceThreadId !== anchor.sourceThreadId ||
208 row.visibility === "synthetic" ||
209 row.item.ordinal > deferred.lastOrdinal
210 )
211 break;
212 end += 1;
213 }
214 const item = { ...anchor.item };
215 if (work.nextCursor === null) delete item.deferredWork;
216 else item.deferredWork = { ...deferred, cursor: work.nextCursor };
217 const updated = { ...anchor, item };
218 const section = [
219 ...page,
220 ...projection.visibleTurnItems
221 .slice(start, end)
222 .filter((row) => !pageKeys.has(projectedItemKey(row))),
223 ];
224 const ordered = section
225 .map((row) => (row.sourceItemId === anchor.sourceItemId ? updated : row))
226 .sort((left, right) => left.item.ordinal - right.item.ordinal);
227 visible = [
228 ...projection.visibleTurnItems.slice(0, start),
229 ...ordered,
230 ...projection.visibleTurnItems.slice(end),
231 ];
232 if (anchor.visibility === "local") turnItemById.set(String(updated.item.id), updated.item);
233 } else {
234 visible = detached
235 ? placeByOrdinal(projection.visibleTurnItems, page)
236 : interleavePage(projection.visibleTurnItems, page, pageKeys);
237 }
238 if (
239 visible.length === projection.visibleTurnItems.length &&
240 visible.every((row, index) => row === projection.visibleTurnItems[index])
241 )
242 return projection;
243 return {
244 ...projection,
245 turnItems: [...turnItemById.values()],
246 visibleTurnItems: renumberVisible(visible),
247 };
248}
249
250/** Adds the records of older subagents; a record already held is newer and stays. */
251export function mergeOlderSubagentsIntoProjection(
252 projection: OrchestrationV2ThreadProjection,
253 olderSubagents: ReadonlyArray<OrchestrationV2Subagent> | undefined,
254): OrchestrationV2ThreadProjection {
255 const held = new Set(projection.subagents.map((agent) => agent.id));
256 const added = olderSubagents?.filter((agent) => !held.has(agent.id)) ?? [];
257 if (added.length === 0) return projection;
258 return { ...projection, subagents: [...added, ...projection.subagents] };
259}
260
261export function applyHistoryPageMeta(
262 current: ThreadHistoryMeta,
263 page: {
264 readonly items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
265 readonly nextCursor: string | null;
266 readonly hasMoreHistory: boolean;
267 },
268): ThreadHistoryMeta {
269 const topSeam =
270 page.nextCursor === null ? undefined : (oldestHistorySeam(page.items) ?? current.topSeam);
271 return {
272 historyCursor: page.nextCursor,
273 ...(topSeam === undefined ? {} : { topSeam }),
274 hasMoreHistory: page.hasMoreHistory,
275 loading: false,
276 error: null,
277 expanded: true,
278 latestLocalTurnOrdinal: current.latestLocalTurnOrdinal,
279 ...(current.gaps === undefined ? {} : { gaps: current.gaps }),
280 };
281}
282
283/**
284 * History meta after a page placed by ordinal; `visible` is the timeline before it. The
285 * top of the history and each gap are unloaded stretches. One the page lands in keeps what
286 * the page left of it: rows above behind the page's cursor, rows below behind its own.
287 */
288export function applyHistoryRangeMeta(
289 current: ThreadHistoryMeta,
290 visible: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
291 page: {
292 readonly items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
293 readonly nextCursor: string | null;
294 readonly hasMoreHistory: boolean;
295 readonly detached?: true | undefined;
296 },
297 requestCursor: string,
298): ThreadHistoryMeta {
299 // A page carries the stop requests its results need from outside its range. They are
300 // rows to show, and say nothing of where the page starts.
301 const range = page.items.filter((row) => row.item.type !== "run_interrupt_request");
302 const reachesStart = !page.hasMoreHistory || page.nextCursor === null;
303 let historyCursor = current.historyCursor;
304 let topSeam = current.topSeam;
305 let hasMoreHistory = current.hasMoreHistory;
306 const gaps: ThreadHistoryGap[] = [];
307 const first = topSeam ?? oldestHistorySeam(visible);
308 const stretches = [
309 ...(current.hasMoreHistory && current.historyCursor !== null && first !== undefined
310 ? [
311 {
312 top: true,
313 cursor: current.historyCursor,
314 ...first,
315 afterOrdinal: -1,
316 },
317 ]
318 : []),
319 ...(current.gaps ?? []).map((gap) => ({ ...gap, top: false })),
320 ];
321 for (const { top, cursor, seamItemId, ordinal, afterOrdinal } of stretches) {
322 const inside = (row: OrchestrationV2ProjectedTurnItem) =>
323 row.item.ordinal > afterOrdinal && row.item.ordinal < ordinal;
324 const firstCovered = range.find(inside);
325 const lastCovered = range.findLast(inside);
326 const requested = cursor === requestCursor && page.detached !== true;
327 const coversStart = reachesStart || range.some((row) => row.item.ordinal <= afterOrdinal);
328 const coversEnd = requested || range.some((row) => row.item.ordinal >= ordinal);
329
330 if (top) {
331 if (reachesStart || requested || firstCovered !== undefined) {
332 historyCursor = reachesStart ? null : page.nextCursor;
333 hasMoreHistory = !reachesStart;
334 if (reachesStart) topSeam = undefined;
335 else if (firstCovered !== undefined) {
336 topSeam = { seamItemId: firstCovered.sourceItemId, ordinal: firstCovered.item.ordinal };
337 }
338 }
339 } else if (firstCovered !== undefined) {
340 if (!coversStart && page.nextCursor !== null) {
341 gaps.push({
342 cursor: page.nextCursor,
343 seamItemId: firstCovered.sourceItemId,
344 ordinal: firstCovered.item.ordinal,
345 afterOrdinal,
346 });
347 }
348 } else if (!coversStart || !coversEnd) {
349 // An older positional cursor can land above its seam after new activity.
350 gaps.push({
351 cursor: requested ? (page.nextCursor ?? cursor) : cursor,
352 seamItemId,
353 ordinal,
354 afterOrdinal,
355 });
356 }
357 if (!coversEnd && lastCovered !== undefined) {
358 gaps.push({
359 cursor,
360 seamItemId,
361 ordinal,
362 afterOrdinal: lastCovered.item.ordinal,
363 });
364 }
365 }
366 return {
367 historyCursor,
368 ...(topSeam === undefined ? {} : { topSeam }),
369 hasMoreHistory,
370 loading: false,
371 error: null,
372 expanded: true,
373 latestLocalTurnOrdinal: current.latestLocalTurnOrdinal,
374 ...(gaps.length === 0 ? {} : { gaps }),
375 };
376}
377
378/** A folded row can cover multiple seams. A seam past the last rendered item goes in the footer. */
379export function historyGapSeamsByRow<Row extends { readonly id: string }>(
380 seams: ReadonlyArray<ThreadHistoryGapSeam> | undefined,
381 rows: ReadonlyArray<Row>,
382 endOrdinal: (row: Row) => number | undefined,
383): ReadonlyMap<string | null, ReadonlyArray<string>> {
384 const byRow = new Map<string | null, string[]>();
385 if (!seams?.length) return byRow;
386 const ordinals = rows.map(endOrdinal);
387 for (const seam of seams) {
388 const index = ordinals.findIndex((ordinal) => ordinal !== undefined && ordinal >= seam.ordinal);
389 const key = rows[index]?.id ?? null;
390 const existing = byRow.get(key);
391 if (existing) existing.push(seam.seamItemId);
392 else byRow.set(key, [seam.seamItemId]);
393 }
394 return byRow;
395}
396
397export function shouldShowLoadEarlierControl(history: ThreadHistoryMeta): boolean {
398 return history.hasMoreHistory || history.error !== null;
399}
400
401// Steers join a running turn; every other user message opens one. The timeline shows every
402// notification as a response boundary, whether it opened its run or arrived mid-run.
403function startsTurn(item: OrchestrationV2TurnItem): boolean {
404 return (
405 item.type === "notification" ||
406 (item.type === "user_message" &&
407 item.inputIntent !== "steer" &&
408 item.inputIntent !== "promoted_queued_to_steer")
409 );
410}
411
412/** Per-click bounds on automatic "Load earlier" continuation to protect memory and host load. */
413export const MAX_AUTO_CONTINUE_HISTORY_PAGES = 16;
414export const MAX_AUTO_CONTINUE_HISTORY_ITEMS = 4_000;
415export const MAX_AUTO_CONTINUE_HISTORY_BYTES = 8 * 1_048_576;
416
417export interface EarlierHistoryContinuationBudget {
418 readonly pages: number;
419 readonly items: number;
420 readonly bytes: number;
421}
422
423export const EMPTY_EARLIER_HISTORY_CONTINUATION_BUDGET: EarlierHistoryContinuationBudget = {
424 pages: 0,
425 items: 0,
426 bytes: 0,
427};
428
429/**
430 * Advances the per-click continuation budget with `page` and returns the next budget when
431 * "Load earlier" should fetch another page to reach the preceding user message (or, when none
432 * exists earlier, a human steer, agent turn or notification boundary), or `null` when it should stop.
433 */
434export function nextEarlierHistoryContinuationBudget(
435 page: Pick<
436 OrchestrationV2ThreadHistoryPage,
437 "items" | "hasMoreHistory" | "detached" | "hasEarlierUserMessage"
438 >,
439 budget: EarlierHistoryContinuationBudget,
440): EarlierHistoryContinuationBudget | null {
441 if (page.detached === true || !page.hasMoreHistory) {
442 return null;
443 }
444 const wantsMore =
445 page.hasEarlierUserMessage === true ||
446 !page.items.some(
447 ({ item }) => startsTurn(item) || (item.type === "user_message" && item.createdBy === "user"),
448 );
449 if (!wantsMore) {
450 return null;
451 }
452 const pages = budget.pages + 1;
453 const items = budget.items + page.items.length;
454 if (pages >= MAX_AUTO_CONTINUE_HISTORY_PAGES || items >= MAX_AUTO_CONTINUE_HISTORY_ITEMS) {
455 return null;
456 }
457 const bytes = budget.bytes + JSON.stringify(page.items).length;
458 if (bytes >= MAX_AUTO_CONTINUE_HISTORY_BYTES) {
459 return null;
460 }
461 return { pages, items, bytes };
462}