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

threadHistoryMerge.ts

156 lines5.0 KB

1import type {
2 OrchestrationV2ProjectedTurnItem,
3 OrchestrationV2ThreadProjection,
4 OrchestrationV2TurnItem,
5} from "@t3tools/contracts";
6import { isOrchestrationV2TurnItemVisible } from "@t3tools/shared/orchestrationV2Timeline";
7​
8export type ThreadHistoryMeta = {
9 readonly historyCursor: string | null;
10 readonly hasMoreHistory: boolean;
11 readonly loading: boolean;
12 readonly error: string | null;
13 /** True after at least one older page was merged; skip monolithic cache growth. */
14 readonly expanded: boolean;
15 /**
16 * Max local turn ordinal known for partial progressive windows. Null when
17 * unknown (legacy cache) or when history meta is cleared for a full snapshot.
18 */
19 readonly latestLocalTurnOrdinal: number | null;
20};
21​
22export const EMPTY_THREAD_HISTORY_META: ThreadHistoryMeta = {
23 historyCursor: null,
24 hasMoreHistory: false,
25 loading: false,
26 error: null,
27 expanded: false,
28 latestLocalTurnOrdinal: null,
29};
30​
31/** Whether a history-page response still matches the cursor that started it. */
32export function isActiveHistoryRequestCursor(
33 requestCursor: string,
34 history: { readonly historyCursor: string | null },
35): boolean {
36 return history.historyCursor === requestCursor;
38​
39/**
40 * Clear history loading after an interrupted load-earlier only when the
41 * request cursor is still active. Does not touch stream/status/error.
42 */
43export function clearActiveHistoryLoading(
44 requestCursor: string,
45 history: ThreadHistoryMeta,
46): ThreadHistoryMeta {
47 if (!isActiveHistoryRequestCursor(requestCursor, history) || !history.loading) {
48 return history;
49 }
50 return { ...history, loading: false };
52​
53function projectedItemKey(row: OrchestrationV2ProjectedTurnItem): string {
54 return `${row.sourceThreadId}:${row.sourceItemId}`;
56​
57function renumberVisible(
58 rows: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
59): OrchestrationV2ProjectedTurnItem[] {
60 return rows.map((row, position) => (row.position === position ? row : { ...row, position }));
62​
63/**
64 * Merge an older history page into the live projection. Dedupes by
65 * sourceThreadId + sourceItemId, keeps chronological order (older first), and
66 * preserves newer live rows already present in state.
67 */
68export function mergeOlderHistoryIntoProjection(
69 projection: OrchestrationV2ThreadProjection,
70 olderItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
71): OrchestrationV2ThreadProjection {
72 if (olderItems.length === 0) {
73 return projection;
74 }
75​
76 const existingKeys = new Set(projection.visibleTurnItems.map(projectedItemKey));
77 const turnItemById = new Map<string, OrchestrationV2TurnItem>();
78 for (const item of projection.turnItems) {
79 turnItemById.set(String(item.id), item);
80 }
81 const prepended: OrchestrationV2ProjectedTurnItem[] = [];
82 for (const pageRow of olderItems) {
83 let row = pageRow;
84 const key = projectedItemKey(row);
85 if (existingKeys.has(key)) {
86 continue;
87 }
88 if (row.visibility === "local" || row.sourceThreadId === projection.thread.id) {
89 const currentItem = turnItemById.get(String(row.sourceItemId));
90 if (currentItem !== undefined) {
91 // A live event may have hidden this item while the page was in flight.
92 // Do not resurrect the stale page copy. Retained interrupt requests are
93 // the exception: they intentionally exist outside the bounded visible
94 // window and should become visible when their history page arrives.
95 if (currentItem.type !== "run_interrupt_request") {
96 continue;
97 }
98 if (
99 !isOrchestrationV2TurnItemVisible({
100 item: currentItem,
101 runs: projection.runs,
102 attempts: projection.attempts,
103 items: projection.turnItems,
104 })
105 ) {
106 continue;
107 }
108 row = { ...row, item: currentItem };
109 }
110 }
111 existingKeys.add(key);
112 prepended.push(row);
113 }
114 if (prepended.length === 0) {
115 return projection;
116 }
117​
118 const visibleTurnItems = renumberVisible([...prepended, ...projection.visibleTurnItems]);
119​
120 for (const row of prepended) {
121 if (row.visibility === "local" || row.sourceThreadId === projection.thread.id) {
122 if (!turnItemById.has(String(row.sourceItemId))) {
123 turnItemById.set(String(row.sourceItemId), row.item);
124 }
125 }
126 }
127​
128 return {
129 ...projection,
130 turnItems: [...turnItemById.values()],
131 visibleTurnItems,
132 };
134​
135export function applyHistoryPageMeta(
136 current: ThreadHistoryMeta,
137 page: {
138 readonly nextCursor: string | null;
139 readonly hasMoreHistory: boolean;
140 },
141): ThreadHistoryMeta {
142 return {
143 historyCursor: page.nextCursor,
144 hasMoreHistory: page.hasMoreHistory,
145 loading: false,
146 error: null,
147 expanded: true,
148 // Preserve the partial-timeline watermark across load-earlier pages.
149 latestLocalTurnOrdinal: current.latestLocalTurnOrdinal,
150 };
152​
153/** Whether a client timeline should render its load-earlier control. */
154export function shouldShowLoadEarlierControl(history: ThreadHistoryMeta): boolean {
155 return history.hasMoreHistory || history.error !== null;