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

threadHistoryMerge.ts

218 lines7.2 KB

1import type {
2 OrchestrationV2ProjectedTurnItem,
3 OrchestrationV2ThreadProjection,
4} from "@t3tools/contracts";
5import { isOrchestrationV2TurnItemVisible } from "@t3tools/shared/orchestrationV2Timeline";
6​
7export type ThreadHistoryMeta = {
8 readonly historyCursor: string | null;
9 readonly hasMoreHistory: boolean;
10 readonly loading: boolean;
11 readonly error: string | null;
12 readonly expanded: boolean;
13 readonly latestLocalTurnOrdinal: number | null;
14};
15​
16export const EMPTY_THREAD_HISTORY_META: ThreadHistoryMeta = {
17 historyCursor: null,
18 hasMoreHistory: false,
19 loading: false,
20 error: null,
21 expanded: false,
22 latestLocalTurnOrdinal: null,
23};
24​
25export function isActiveHistoryRequestCursor(
26 requestCursor: string,
27 history: { readonly historyCursor: string | null },
28): boolean {
29 return history.historyCursor === requestCursor;
31​
32export function clearActiveHistoryLoading(
33 requestCursor: string,
34 history: ThreadHistoryMeta,
35): ThreadHistoryMeta {
36 if (!isActiveHistoryRequestCursor(requestCursor, history) || !history.loading) {
37 return history;
38 }
39 return { ...history, loading: false };
41​
42function projectedItemKey(row: OrchestrationV2ProjectedTurnItem): string {
43 return `${row.sourceThreadId}:${row.sourceItemId}`;
45​
46function renumberVisible(
47 rows: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
48): OrchestrationV2ProjectedTurnItem[] {
49 return rows.map((row, position) => (row.position === position ? row : { ...row, position }));
51​
52// A page is a contiguous history range, so current rows before its first
53// visible row are older than the page start and new page rows sit just
54// before the next row both lists share.
55function interleavePage(
56 current: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
57 page: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
58 pageKeys: ReadonlySet<string>,
59): OrchestrationV2ProjectedTurnItem[] {
60 const currentIndex = new Map(current.map((row, index) => [projectedItemKey(row), index]));
61 const merged: OrchestrationV2ProjectedTurnItem[] = [];
62 let pending: OrchestrationV2ProjectedTurnItem[] = [];
63 let next = 0;
64 const emitCurrentThrough = (end: number) => {
65 for (; next < end; next += 1) {
66 const row = current[next]!;
67 if (!pageKeys.has(projectedItemKey(row))) merged.push(row);
68 }
69 };
70 for (const row of page) {
71 const index = currentIndex.get(projectedItemKey(row));
72 if (index === undefined) {
73 pending.push(row);
74 continue;
75 }
76 emitCurrentThrough(index + 1);
77 merged.push(...pending, row);
78 pending = [];
79 }
80 merged.push(...pending);
81 emitCurrentThrough(current.length);
82 return merged;
84​
85export function mergeOlderHistoryIntoProjection(
86 projection: OrchestrationV2ThreadProjection,
87 olderItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
88 work?: { readonly anchorId: string; readonly nextCursor: string | null },
89): OrchestrationV2ThreadProjection {
90 if (olderItems.length === 0 && work === undefined) {
91 return projection;
92 }
93​
94 const start =
95 work === undefined
96 ? -1
97 : projection.visibleTurnItems.findIndex((row) => row.sourceItemId === work.anchorId);
98 const anchor = projection.visibleTurnItems[start];
99 const deferred = anchor?.item.deferredWork;
100 if (work !== undefined && deferred === undefined) return projection;
101 const currentByKey = new Map(
102 projection.visibleTurnItems.map((row) => [projectedItemKey(row), row]),
103 );
104 const turnItemById = new Map(projection.turnItems.map((item) => [String(item.id), item]));
105 const pageKeys = new Set<string>();
106 const page: OrchestrationV2ProjectedTurnItem[] = [];
107 for (const pageRow of olderItems) {
108 if (
109 work &&
110 anchor &&
111 deferred &&
112 (pageRow.sourceThreadId !== anchor.sourceThreadId ||
113 pageRow.item.ordinal < anchor.item.ordinal ||
114 pageRow.item.ordinal > deferred.lastOrdinal)
115 )
116 continue;
117 const key = projectedItemKey(pageRow);
118 if (pageKeys.has(key)) continue;
119 let row = currentByKey.get(key) ?? pageRow;
120 if (
121 !currentByKey.has(key) &&
122 (row.visibility === "local" || row.sourceThreadId === projection.thread.id)
123 ) {
124 const currentItem = turnItemById.get(String(row.sourceItemId));
125 // Hidden live items stay hidden. Snapshots also retain interrupt requests and
126 // pending request cards outside the visible window; their history page shows them.
127 if (currentItem !== undefined) {
128 if (
129 (currentItem.type !== "run_interrupt_request" &&
130 currentItem.type !== "approval_request" &&
131 currentItem.type !== "user_input_request") ||
132 !isOrchestrationV2TurnItemVisible({
133 item: currentItem,
134 runs: projection.runs,
135 attempts: projection.attempts,
136 items: projection.turnItems,
137 })
138 )
139 continue;
140 row = { ...row, item: currentItem };
141 }
142 }
143 pageKeys.add(key);
144 page.push(row);
145 if (
146 (row.visibility === "local" || row.sourceThreadId === projection.thread.id) &&
147 !turnItemById.has(String(row.sourceItemId))
148 )
149 turnItemById.set(String(row.sourceItemId), row.item);
150 }
151 if (page.length === 0 && work === undefined) return projection;
152 let visible: OrchestrationV2ProjectedTurnItem[];
153 if (work && anchor && deferred) {
154 let end = start + 1;
155 while (end < projection.visibleTurnItems.length) {
156 const row = projection.visibleTurnItems[end]!;
157 if (
158 row.sourceThreadId !== anchor.sourceThreadId ||
159 row.visibility === "synthetic" ||
160 row.item.ordinal > deferred.lastOrdinal
161 )
162 break;
163 end += 1;
164 }
165 const item = { ...anchor.item };
166 if (work.nextCursor === null) delete item.deferredWork;
167 else item.deferredWork = { ...deferred, cursor: work.nextCursor };
168 const updated = { ...anchor, item };
169 const section = [
170 ...page,
171 ...projection.visibleTurnItems
172 .slice(start, end)
173 .filter((row) => !pageKeys.has(projectedItemKey(row))),
174 ];
175 const ordered = section
176 .map((row) => (row.sourceItemId === anchor.sourceItemId ? updated : row))
177 .sort((left, right) => left.item.ordinal - right.item.ordinal);
178 visible = [
179 ...projection.visibleTurnItems.slice(0, start),
180 ...ordered,
181 ...projection.visibleTurnItems.slice(end),
182 ];
183 if (anchor.visibility === "local") turnItemById.set(String(updated.item.id), updated.item);
184 } else {
185 visible = interleavePage(projection.visibleTurnItems, page, pageKeys);
186 }
187 if (
188 visible.length === projection.visibleTurnItems.length &&
189 visible.every((row, index) => row === projection.visibleTurnItems[index])
190 )
191 return projection;
192 return {
193 ...projection,
194 turnItems: [...turnItemById.values()],
195 visibleTurnItems: renumberVisible(visible),
196 };
198​
199export function applyHistoryPageMeta(
200 current: ThreadHistoryMeta,
201 page: {
202 readonly nextCursor: string | null;
203 readonly hasMoreHistory: boolean;
204 },
205): ThreadHistoryMeta {
206 return {
207 historyCursor: page.nextCursor,
208 hasMoreHistory: page.hasMoreHistory,
209 loading: false,
210 error: null,
211 expanded: true,
212 latestLocalTurnOrdinal: current.latestLocalTurnOrdinal,
213 };
215​
216export function shouldShowLoadEarlierControl(history: ThreadHistoryMeta): boolean {
217 return history.hasMoreHistory || history.error !== null;