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