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

orchestrationV2Projection.ts

342 lines12.0 KB

1import { applyThreadPullRequestLinkUpdate } from "@t3tools/shared/threadPullRequests";
2import type {
3 OrchestrationV2DomainEvent,
4 OrchestrationV2Run,
5 OrchestrationV2ThreadProjection,
6 OrchestrationV2TurnItem,
7} from "@t3tools/contracts";
8import {
9 createOrchestrationV2TurnItemVisibility,
10 isOrchestrationV2TurnItemVisible,
11} from "@t3tools/shared/orchestrationV2Timeline";
12import { applyThreadPullRequestLinkSync } from "@t3tools/shared/threadPullRequests";
13​
14export type ApplyOrchestrationV2ProjectionEventOptions = {
15 readonly partialTimeline?: boolean;
16 readonly latestLocalTurnOrdinal?: number | null;
17};
18​
19function upsertEntity<T extends { readonly id: unknown }>(
20 items: ReadonlyArray<T>,
21 item: T,
22): ReadonlyArray<T> {
23 const index = items.findIndex((candidate) => candidate.id === item.id);
24 if (index === -1) return [...items, item];
25 const next = [...items];
26 next[index] = item;
27 return next;
29​
30function removeVisibleItem(
31 rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
32 sourceItemId: OrchestrationV2TurnItem["id"],
33): OrchestrationV2ThreadProjection["visibleTurnItems"] {
34 const index = rows.findIndex((row) => row.sourceItemId === sourceItemId);
35 if (index === -1) return rows;
36 return renumberVisibleItems([...rows.slice(0, index), ...rows.slice(index + 1)]);
38​
39function renumberVisibleItems(
40 rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
41): OrchestrationV2ThreadProjection["visibleTurnItems"] {
42 return rows.map((row, position) => (row.position === position ? row : { ...row, position }));
44​
45function shouldShowLocalTurnItem(
46 projection: OrchestrationV2ThreadProjection,
47 item: OrchestrationV2TurnItem,
48): boolean {
49 return isOrchestrationV2TurnItemVisible({
50 item,
51 runs: projection.runs,
52 attempts: projection.attempts,
53 items: projection.turnItems,
54 });
56​
57function activeVisibleTurnItems(
58 projection: OrchestrationV2ThreadProjection,
59): OrchestrationV2ThreadProjection["visibleTurnItems"] {
60 const rows = projection.visibleTurnItems;
61 const isVisible = createOrchestrationV2TurnItemVisibility({
62 runs: projection.runs,
63 attempts: projection.attempts,
64 items: projection.turnItems,
65 });
66 let next: Array<(typeof rows)[number]> | null = null;
67 for (let index = 0; index < rows.length; index += 1) {
68 const row = rows[index]!;
69 const keep = row.visibility !== "local" || isVisible(row.item);
70 if (!keep) {
71 next ??= rows.slice(0, index);
72 continue;
73 }
74 next?.push(row);
75 }
76 return next === null ? rows : renumberVisibleItems(next);
78​
79function oldestLocalTurnOrdinal(
80 rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
81): number | null {
82 let oldest: number | null = null;
83 for (const row of rows) {
84 if (row.visibility !== "local") continue;
85 if (oldest === null || row.item.ordinal < oldest) {
86 oldest = row.item.ordinal;
87 }
88 }
89 return oldest;
91​
92const UNFINISHED_RUN_STATUSES: ReadonlySet<OrchestrationV2Run["status"]> = new Set([
93 "preparing",
94 "queued",
95 "starting",
96 "running",
97 "waiting",
98]);
99​
100function shouldDropMissingPartialTurnItem(
101 projection: OrchestrationV2ThreadProjection,
102 item: OrchestrationV2TurnItem,
103 latestLocalTurnOrdinal: number | null | undefined,
104): boolean {
105 if (projection.visibleTurnItems.some((row) => row.sourceItemId === item.id)) {
106 return false;
107 }
108 if (item.runId === null) {
109 return isBelowPartialWindow(projection, item, latestLocalTurnOrdinal);
110 }
111 // A queued run keeps the ordinal it got when queued, so a steer sent later
112 // can raise the watermark past it. Items of a run that has not finished are
113 // new, not unloaded history: the first lands while the run is still queued,
114 // and a bounded window can start after the ones before it.
115 if (
116 projection.runs.some((run) => run.id === item.runId && UNFINISHED_RUN_STATUSES.has(run.status))
117 ) {
118 return false;
119 }
120 if (
121 projection.visibleTurnItems.some(
122 (row) =>
123 row.visibility === "local" &&
124 row.item.runId === item.runId &&
125 row.item.ordinal <= item.ordinal,
126 )
127 ) {
128 return false;
129 }
130 return isBelowPartialWindow(projection, item, latestLocalTurnOrdinal);
132​
133function isBelowPartialWindow(
134 projection: OrchestrationV2ThreadProjection,
135 item: OrchestrationV2TurnItem,
136 latestLocalTurnOrdinal: number | null | undefined,
137): boolean {
138 if (
139 latestLocalTurnOrdinal !== null &&
140 latestLocalTurnOrdinal !== undefined &&
141 item.ordinal <= latestLocalTurnOrdinal
142 ) {
143 return true;
144 }
145 const oldest = oldestLocalTurnOrdinal(projection.visibleTurnItems);
146 return oldest !== null && item.ordinal < oldest;
148​
149function upsertVisibleTurnItem(
150 projection: OrchestrationV2ThreadProjection,
151 item: OrchestrationV2TurnItem,
152 partialTimeline: boolean,
153 latestLocalTurnOrdinal: number | null | undefined,
154): OrchestrationV2ThreadProjection["visibleTurnItems"] {
155 const rows = projection.visibleTurnItems;
156 const index = rows.findIndex((row) => row.sourceItemId === item.id);
157 const next = {
158 position: 0,
159 visibility: "local" as const,
160 sourceThreadId: item.threadId,
161 sourceItemId: item.id,
162 item,
163 };
164 const previous = index === -1 ? undefined : rows[index]!;
165 if (
166 previous !== undefined &&
167 previous.visibility === next.visibility &&
168 previous.sourceThreadId === next.sourceThreadId &&
169 previous.sourceItemId === next.sourceItemId &&
170 previous.item === item
171 ) {
172 return rows;
173 }
174 if (
175 index === -1 &&
176 partialTimeline &&
177 shouldDropMissingPartialTurnItem(projection, item, latestLocalTurnOrdinal)
178 ) {
179 return rows;
180 }
181 const updated = index === -1 ? [...rows] : [...rows.slice(0, index), ...rows.slice(index + 1)];
182 const insertionIndex = updated.findIndex(
183 (row) =>
184 row.visibility === "local" &&
185 (row.item.ordinal > item.ordinal ||
186 (row.item.ordinal === item.ordinal &&
187 String(row.item.id).localeCompare(String(item.id)) > 0)),
188 );
189 updated.splice(insertionIndex === -1 ? updated.length : insertionIndex, 0, next);
190 return renumberVisibleItems(updated);
192​
193export function applyOrchestrationV2ProjectionEvent(
194 projection: OrchestrationV2ThreadProjection | null,
195 event: OrchestrationV2DomainEvent,
196 options?: ApplyOrchestrationV2ProjectionEventOptions,
197): OrchestrationV2ThreadProjection | null {
198 if (projection === null || event.threadId !== projection.thread.id) return projection;
199​
200 const partialTimeline = options?.partialTimeline === true;
201 const latestLocalTurnOrdinal = options?.latestLocalTurnOrdinal;
202 const base = { ...projection, updatedAt: event.occurredAt };
203 switch (event.type) {
204 case "thread.pull-request-link-updated":
205 return {
206 ...base,
207 thread: applyThreadPullRequestLinkUpdate(projection.thread, event.payload),
208 };
209 case "thread.created":
210 case "thread.archived":
211 case "thread.unarchived":
212 case "thread.deleted":
213 case "thread.settled":
214 case "thread.unsettled":
215 case "thread.snoozed":
216 case "thread.unsnoozed":
217 case "thread.auto-settle-set":
218 case "thread.pinned":
219 case "thread.unpinned":
220 case "thread.pin-reordered":
221 case "thread.active-reordered":
222 case "thread.metadata-updated":
223 case "thread.pull-request-synced":
224 case "thread.runtime-mode-updated":
225 case "thread.interaction-mode-updated":
226 case "thread.model-selection-updated":
227 case "thread.provider-switched":
228 return { ...base, thread: event.payload };
229 // A host refresh is not activity, matching the server projection.
230 case "thread.pull-request-link-synced":
231 return {
232 ...projection,
233 thread: applyThreadPullRequestLinkSync(projection.thread, event.payload),
234 };
235 // Visited tracking is read state, not activity: skip the updatedAt bump.
236 case "thread.visited":
237 case "thread.marked-unread":
238 return { ...projection, thread: event.payload };
239 case "thread.visit-recorded":
240 return {
241 ...projection,
242 thread: { ...projection.thread, lastVisitedAt: event.payload.lastVisitedAt },
243 };
244 case "run.created":
245 case "run.updated": {
246 const next = { ...base, runs: upsertEntity(base.runs, event.payload) };
247 return { ...next, visibleTurnItems: activeVisibleTurnItems(next) };
248 }
249 case "run.background-work-cancelled":
250 return {
251 ...base,
252 runs: base.runs.map((run) =>
253 run.id === event.payload.runId
254 ? {
255 ...run,
256 restartCancelledBackgroundWork: event.payload.restartCancelledBackgroundWork,
257 }
258 : run,
259 ),
260 };
261 case "run-attempt.created":
262 case "run-attempt.updated": {
263 const next = { ...base, attempts: upsertEntity(base.attempts, event.payload) };
264 return { ...next, visibleTurnItems: activeVisibleTurnItems(next) };
265 }
266 case "node.updated":
267 return { ...base, nodes: upsertEntity(base.nodes, event.payload) };
268 case "subagent.updated":
269 return { ...base, subagents: upsertEntity(base.subagents, event.payload) };
270 case "provider-session.attached":
271 case "provider-session.updated":
272 return {
273 ...base,
274 providerSessions: upsertEntity(base.providerSessions, event.payload),
275 };
276 case "provider-session.detached":
277 return {
278 ...base,
279 providerSessions: base.providerSessions.filter(
280 (session) => session.id !== event.payload.providerSessionId,
281 ),
282 };
283 case "provider-thread.updated":
284 return { ...base, providerThreads: upsertEntity(base.providerThreads, event.payload) };
285 case "provider-turn.updated":
286 return {
287 ...base,
288 providerTurns: upsertEntity(base.providerTurns, {
289 ...event.payload,
290 ...((event.payload.tokenUsage ??
291 base.providerTurns.find((turn) => turn.id === event.payload.id)?.tokenUsage) ===
292 undefined
293 ? {}
294 : {
295 tokenUsage:
296 event.payload.tokenUsage ??
297 base.providerTurns.find((turn) => turn.id === event.payload.id)?.tokenUsage,
298 }),
299 }),
300 };
301 case "runtime-request.updated":
302 return { ...base, runtimeRequests: upsertEntity(base.runtimeRequests, event.payload) };
303 case "message.updated":
304 return { ...base, messages: upsertEntity(base.messages, event.payload) };
305 case "plan.updated":
306 return { ...base, plans: upsertEntity(base.plans, event.payload) };
307 case "turn-item.updated": {
308 if (
309 partialTimeline &&
310 !projection.turnItems.some((candidate) => candidate.id === event.payload.id) &&
311 shouldDropMissingPartialTurnItem(projection, event.payload, latestLocalTurnOrdinal)
312 ) {
313 return projection;
314 }
315 const next = { ...base, turnItems: upsertEntity(base.turnItems, event.payload) };
316 // Only interrupt requests can change another item's visibility. Streaming
317 // text/tool updates must not recheck every row against every run.
318 const previous = projection.turnItems.find((item) => item.id === event.payload.id);
319 const visible =
320 event.payload.type === "run_interrupt_request" || previous?.type === "run_interrupt_request"
321 ? { ...next, visibleTurnItems: activeVisibleTurnItems(next) }
322 : next;
323 return {
324 ...next,
325 visibleTurnItems: shouldShowLocalTurnItem(next, event.payload)
326 ? upsertVisibleTurnItem(visible, event.payload, partialTimeline, latestLocalTurnOrdinal)
327 : removeVisibleItem(visible.visibleTurnItems, event.payload.id),
328 };
329 }
330 case "checkpoint-scope.created":
331 return { ...base, checkpointScopes: upsertEntity(base.checkpointScopes, event.payload) };
332 case "checkpoint.captured":
333 return { ...base, checkpoints: upsertEntity(base.checkpoints, event.payload) };
334 case "checkpoint.rollback-requested":
335 return base;
336 case "context-handoff.updated":
337 return { ...base, contextHandoffs: upsertEntity(base.contextHandoffs, event.payload) };
338 case "context-transfer.created":
339 case "context-transfer.updated":
340 return { ...base, contextTransfers: upsertEntity(base.contextTransfers, event.payload) };
341 }