Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadHistoryMerge.ts

397 lines14.4 KB

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