The best way to control Claude Code, Codex and more from any computer or phone

main
ts 480 lines 16.8 KB
Raw
1 import { applyThreadPullRequestLinkUpdate } from "../threadPullRequests.ts";
2 import {
3 applyOrchestrationV2ThreadVisit,
4 isQueuedProviderThreadPlaceholder,
5 } from "@t3tools/contracts";
6 import type {
7 OrchestrationV2DomainEvent,
8 OrchestrationV2Run,
9 OrchestrationV2ThreadProjection,
10 OrchestrationV2TurnItem,
11 } from "@t3tools/contracts";
12 import {
13 restoreSubagentBodies,
14 restoreTurnItemBodies,
15 type DedupedBodySource,
16 } from "@t3tools/shared/orchestrationV2DedupedBodies";
17 import {
18 createOrchestrationV2TurnItemVisibility,
19 isOrchestrationV2TurnItemVisible,
20 } from "@t3tools/shared/orchestrationV2Timeline";
21
22 export type ApplyOrchestrationV2ProjectionEventOptions = {
23 readonly partialTimeline?: boolean;
24 readonly latestLocalTurnOrdinal?: number | null;
25 };
26
27 // Only this exact pair differs at one index. Both keys are weak so hints
28 // neither retain streaming history nor apply to replacement snapshots.
29 const arrayReplacements = new WeakMap<
30 ReadonlyArray<unknown>,
31 WeakMap<ReadonlyArray<unknown>, number>
32 >();
33
34 export function getProjectionArrayReplacementIndex(
35 previous: ReadonlyArray<unknown>,
36 next: ReadonlyArray<unknown>,
37 ): number | undefined {
38 return arrayReplacements.get(previous)?.get(next);
39 }
40
41 function replaceProjectionArrayItem<T>(
42 items: ReadonlyArray<T>,
43 index: number,
44 item: T,
45 ): ReadonlyArray<T> {
46 const next = items.slice();
47 next[index] = item;
48 let replacements = arrayReplacements.get(items);
49 if (replacements === undefined) {
50 replacements = new WeakMap();
51 arrayReplacements.set(items, replacements);
52 }
53 replacements.set(next, index);
54 return next;
55 }
56
57 function upsertEntity<T extends { readonly id: unknown }>(
58 items: ReadonlyArray<T>,
59 item: T,
60 ): ReadonlyArray<T> {
61 const index = items.findIndex((candidate) => candidate.id === item.id);
62 if (index === -1) return [...items, item];
63 const next = [...items];
64 next[index] = item;
65 return next;
66 }
67
68 // A deduped item repeats a record the stream just sent, so search newest first.
69 function latestBodies(projection: OrchestrationV2ThreadProjection): DedupedBodySource {
70 return {
71 messageText: (id) => projection.messages.findLast((message) => message.id === id)?.text,
72 checkpointFiles: (id) =>
73 projection.checkpoints.findLast((checkpoint) => checkpoint.id === id)?.files,
74 subagent: (id) => projection.subagents.findLast((subagent) => subagent.id === id),
75 };
76 }
77
78 function removeVisibleItem(
79 rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
80 sourceItemId: OrchestrationV2TurnItem["id"],
81 ): OrchestrationV2ThreadProjection["visibleTurnItems"] {
82 const index = rows.findIndex((row) => row.sourceItemId === sourceItemId);
83 if (index === -1) return rows;
84 return renumberVisibleItems([...rows.slice(0, index), ...rows.slice(index + 1)]);
85 }
86
87 function renumberVisibleItems(
88 rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
89 ): OrchestrationV2ThreadProjection["visibleTurnItems"] {
90 return rows.map((row, position) => (row.position === position ? row : { ...row, position }));
91 }
92
93 function shouldShowLocalTurnItem(
94 projection: OrchestrationV2ThreadProjection,
95 item: OrchestrationV2TurnItem,
96 ): boolean {
97 return isOrchestrationV2TurnItemVisible({
98 item,
99 runs: projection.runs,
100 attempts: projection.attempts,
101 items: projection.turnItems,
102 });
103 }
104
105 function activeVisibleTurnItems(
106 projection: OrchestrationV2ThreadProjection,
107 ): OrchestrationV2ThreadProjection["visibleTurnItems"] {
108 const rows = projection.visibleTurnItems;
109 const isVisible = createOrchestrationV2TurnItemVisibility({
110 runs: projection.runs,
111 attempts: projection.attempts,
112 items: projection.turnItems,
113 });
114 let next: Array<(typeof rows)[number]> | null = null;
115 for (let index = 0; index < rows.length; index += 1) {
116 const row = rows[index]!;
117 const keep = row.visibility !== "local" || isVisible(row.item);
118 if (!keep) {
119 next ??= rows.slice(0, index);
120 continue;
121 }
122 next?.push(row);
123 }
124 return next === null ? rows : renumberVisibleItems(next);
125 }
126
127 function oldestLocalTurnOrdinal(
128 rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
129 ): number | null {
130 let oldest: number | null = null;
131 for (const row of rows) {
132 if (row.visibility !== "local") continue;
133 if (oldest === null || row.item.ordinal < oldest) {
134 oldest = row.item.ordinal;
135 }
136 }
137 return oldest;
138 }
139
140 const UNFINISHED_RUN_STATUSES: ReadonlySet<OrchestrationV2Run["status"]> = new Set([
141 "preparing",
142 "queued",
143 "starting",
144 "running",
145 "waiting",
146 ]);
147
148 function shouldDropMissingPartialTurnItem(
149 projection: OrchestrationV2ThreadProjection,
150 item: OrchestrationV2TurnItem,
151 latestLocalTurnOrdinal: number | null | undefined,
152 ): boolean {
153 if (projection.visibleTurnItems.some((row) => row.sourceItemId === item.id)) {
154 return false;
155 }
156 if (item.runId === null) {
157 return isBelowPartialWindow(projection, item, latestLocalTurnOrdinal);
158 }
159 // A queued run keeps the ordinal it got when queued, so a steer sent later
160 // can raise the watermark past it. Items of a run that has not finished are
161 // new, not unloaded history: the first lands while the run is still queued,
162 // and a bounded window can start after the ones before it.
163 if (
164 projection.runs.some((run) => run.id === item.runId && UNFINISHED_RUN_STATUSES.has(run.status))
165 ) {
166 return false;
167 }
168 if (
169 projection.visibleTurnItems.some(
170 (row) =>
171 row.visibility === "local" &&
172 row.item.runId === item.runId &&
173 row.item.ordinal <= item.ordinal,
174 )
175 ) {
176 return false;
177 }
178 return isBelowPartialWindow(projection, item, latestLocalTurnOrdinal);
179 }
180
181 function isBelowPartialWindow(
182 projection: OrchestrationV2ThreadProjection,
183 item: OrchestrationV2TurnItem,
184 latestLocalTurnOrdinal: number | null | undefined,
185 ): boolean {
186 if (
187 latestLocalTurnOrdinal !== null &&
188 latestLocalTurnOrdinal !== undefined &&
189 item.ordinal <= latestLocalTurnOrdinal
190 ) {
191 return true;
192 }
193 const oldest = oldestLocalTurnOrdinal(projection.visibleTurnItems);
194 return oldest !== null && item.ordinal < oldest;
195 }
196
197 function upsertVisibleTurnItem(
198 projection: OrchestrationV2ThreadProjection,
199 item: OrchestrationV2TurnItem,
200 partialTimeline: boolean,
201 latestLocalTurnOrdinal: number | null | undefined,
202 ): OrchestrationV2ThreadProjection["visibleTurnItems"] {
203 const rows = projection.visibleTurnItems;
204 // Streamed updates land on the newest rows. Item ids are unique, so the
205 // search can start there.
206 let index = rows.length - 1;
207 while (index >= 0 && rows[index]!.sourceItemId !== item.id) index -= 1;
208 const next = {
209 position: 0,
210 visibility: "local" as const,
211 sourceThreadId: item.threadId,
212 sourceItemId: item.id,
213 item,
214 };
215 const previous = index === -1 ? undefined : rows[index]!;
216 if (
217 previous !== undefined &&
218 previous.visibility === next.visibility &&
219 previous.sourceThreadId === next.sourceThreadId
220 ) {
221 if (previous.item === item) return rows;
222 if (previous.item.ordinal === item.ordinal) {
223 return replaceProjectionArrayItem(rows, index, { ...next, position: previous.position });
224 }
225 }
226 if (
227 index === -1 &&
228 partialTimeline &&
229 shouldDropMissingPartialTurnItem(projection, item, latestLocalTurnOrdinal)
230 ) {
231 return rows;
232 }
233 // The item goes before the first later local row, as if its old row were
234 // removed first. Inserts, reorders, and inherited-to-local changes need
235 // this ordering pass; replacements above preserve every other row.
236 let insertion = rows.length;
237 for (let candidate = 0; candidate < rows.length; candidate += 1) {
238 const row = rows[candidate]!;
239 if (
240 candidate !== index &&
241 row.visibility === "local" &&
242 (row.item.ordinal > item.ordinal ||
243 (row.item.ordinal === item.ordinal &&
244 String(row.item.id).localeCompare(String(item.id)) > 0))
245 ) {
246 insertion = candidate;
247 break;
248 }
249 }
250 const updated: Array<(typeof rows)[number]> = [];
251 for (let source = 0; source < rows.length; source += 1) {
252 if (source === insertion) updated.push(next);
253 if (source !== index) updated.push(rows[source]!);
254 }
255 if (insertion === rows.length) updated.push(next);
256 for (let position = 0; position < updated.length; position += 1) {
257 const row = updated[position]!;
258 if (row.position !== position) updated[position] = { ...row, position };
259 }
260 return updated;
261 }
262
263 // A user item retained for a queued run stays hidden until the run leaves the
264 // queue, and its update can arrive before or after that run update. Items in
265 // `turnItems` were loaded or streamed, so they skip the partial-window check;
266 // items never received stay absent.
267 function restoreQueuedUserItems(
268 projection: OrchestrationV2ThreadProjection,
269 runId: OrchestrationV2Run["id"],
270 ): OrchestrationV2ThreadProjection["visibleTurnItems"] {
271 let visibleTurnItems = projection.visibleTurnItems;
272 for (const item of projection.turnItems) {
273 if (item.runId !== runId || item.type !== "user_message" || item.inputIntent !== "queued_turn")
274 continue;
275 if (!shouldShowLocalTurnItem(projection, item)) continue;
276 visibleTurnItems = upsertVisibleTurnItem(
277 { ...projection, visibleTurnItems },
278 item,
279 false,
280 null,
281 );
282 }
283 return visibleTurnItems;
284 }
285
286 export function applyOrchestrationV2ProjectionEvent(
287 projection: OrchestrationV2ThreadProjection | null,
288 event: OrchestrationV2DomainEvent,
289 options?: ApplyOrchestrationV2ProjectionEventOptions,
290 ): OrchestrationV2ThreadProjection | null {
291 if (projection === null || event.threadId !== projection.thread.id) return projection;
292
293 const partialTimeline = options?.partialTimeline === true;
294 const latestLocalTurnOrdinal = options?.latestLocalTurnOrdinal;
295 const base = { ...projection, updatedAt: event.occurredAt };
296 switch (event.type) {
297 case "thread.pull-request-link-updated":
298 return {
299 ...base,
300 thread: applyThreadPullRequestLinkUpdate(projection.thread, event.payload),
301 };
302 case "thread.created":
303 case "thread.archived":
304 case "thread.unarchived":
305 case "thread.deleted":
306 case "thread.settled":
307 case "thread.unsettled":
308 case "thread.snoozed":
309 case "thread.unsnoozed":
310 case "thread.auto-settle-set":
311 case "thread.pinned":
312 case "thread.unpinned":
313 case "thread.pin-reordered":
314 case "thread.active-reordered":
315 case "thread.metadata-updated":
316 case "thread.pull-request-synced":
317 case "thread.issue-synced":
318 case "thread.runtime-mode-updated":
319 case "thread.interaction-mode-updated":
320 case "thread.model-selection-updated":
321 case "thread.provider-switched":
322 case "thread.guest-share-updated":
323 return { ...base, thread: event.payload };
324 // Visited tracking and tags are not activity: skip the updatedAt bump.
325 case "thread.visited":
326 case "thread.tags-updated":
327 case "thread.marked-unread":
328 return { ...projection, thread: event.payload };
329 case "thread.visit-recorded":
330 return {
331 ...projection,
332 thread: applyOrchestrationV2ThreadVisit(projection.thread, event.payload),
333 };
334 case "run.created":
335 case "run.updated": {
336 // Lifecycle updates carry the run as it was when the turn started. What the run returned
337 // is written by its own event, and an update without it must not take it away.
338 const known = base.runs.find((run) => run.id === event.payload.id);
339 const run =
340 event.payload.output === undefined && known?.output !== undefined
341 ? { ...event.payload, output: known.output }
342 : event.payload;
343 const next = { ...base, runs: upsertEntity(base.runs, run) };
344 const visible = { ...next, visibleTurnItems: activeVisibleTurnItems(next) };
345 const wasQueued = known?.status === "queued";
346 return wasQueued && event.payload.status !== "queued"
347 ? { ...visible, visibleTurnItems: restoreQueuedUserItems(visible, event.payload.id) }
348 : visible;
349 }
350 case "run.background-work-cancelled":
351 return {
352 ...base,
353 runs: base.runs.map((run) =>
354 run.id === event.payload.runId
355 ? {
356 ...run,
357 restartCancelledBackgroundWork: event.payload.restartCancelledBackgroundWork,
358 }
359 : run,
360 ),
361 };
362 case "run.output-submitted":
363 return {
364 ...base,
365 runs: base.runs.map((run) =>
366 run.id === event.payload.runId ? { ...run, output: event.payload.output } : run,
367 ),
368 };
369 case "run-attempt.created":
370 case "run-attempt.updated": {
371 const next = { ...base, attempts: upsertEntity(base.attempts, event.payload) };
372 return { ...next, visibleTurnItems: activeVisibleTurnItems(next) };
373 }
374 case "node.updated":
375 return { ...base, nodes: upsertEntity(base.nodes, event.payload) };
376 case "subagent.updated":
377 return {
378 ...base,
379 subagents: upsertEntity(
380 base.subagents,
381 restoreSubagentBodies(
382 event.payload,
383 base.subagents.find((subagent) => subagent.id === event.payload.id),
384 ),
385 ),
386 };
387 case "provider-session.attached":
388 case "provider-session.updated":
389 return {
390 ...base,
391 providerSessions: upsertEntity(base.providerSessions, event.payload),
392 };
393 case "provider-session.detached":
394 return {
395 ...base,
396 providerSessions: base.providerSessions.filter(
397 (session) => session.id !== event.payload.providerSessionId,
398 ),
399 };
400 case "provider-thread.updated":
401 return {
402 ...base,
403 thread:
404 event.payload.appThreadId === base.thread.id &&
405 !isQueuedProviderThreadPlaceholder(event.payload)
406 ? { ...base.thread, activeProviderThreadId: event.payload.id }
407 : base.thread,
408 providerThreads: upsertEntity(base.providerThreads, event.payload),
409 };
410 case "provider-turn.updated":
411 return {
412 ...base,
413 providerTurns: upsertEntity(base.providerTurns, {
414 ...event.payload,
415 ...((event.payload.tokenUsage ??
416 base.providerTurns.find((turn) => turn.id === event.payload.id)?.tokenUsage) ===
417 undefined
418 ? {}
419 : {
420 tokenUsage:
421 event.payload.tokenUsage ??
422 base.providerTurns.find((turn) => turn.id === event.payload.id)?.tokenUsage,
423 }),
424 }),
425 };
426 case "runtime-request.updated":
427 return { ...base, runtimeRequests: upsertEntity(base.runtimeRequests, event.payload) };
428 case "message.updated":
429 return { ...base, messages: upsertEntity(base.messages, event.payload) };
430 case "plan.updated":
431 return { ...base, plans: upsertEntity(base.plans, event.payload) };
432 case "turn-item.updated": {
433 let payload = restoreTurnItemBodies(event.payload, latestBodies(projection));
434 // Streamed updates land on the newest items, so search from the end.
435 let itemIndex = projection.turnItems.length - 1;
436 while (itemIndex >= 0 && projection.turnItems[itemIndex]!.id !== payload.id) {
437 itemIndex -= 1;
438 }
439 const deferredWork =
440 itemIndex === -1 ? undefined : projection.turnItems[itemIndex]?.deferredWork;
441 if (deferredWork !== undefined) payload = { ...payload, deferredWork };
442 if (
443 partialTimeline &&
444 itemIndex === -1 &&
445 shouldDropMissingPartialTurnItem(projection, payload, latestLocalTurnOrdinal)
446 ) {
447 return projection;
448 }
449 const turnItems =
450 itemIndex === -1
451 ? [...projection.turnItems, payload]
452 : replaceProjectionArrayItem(projection.turnItems, itemIndex, payload);
453 const next = { ...base, turnItems };
454 // Only interrupt requests can change another item's visibility. Streaming
455 // text/tool updates must not recheck every row against every run.
456 const previous = itemIndex === -1 ? undefined : projection.turnItems[itemIndex];
457 const visible =
458 payload.type === "run_interrupt_request" || previous?.type === "run_interrupt_request"
459 ? { ...next, visibleTurnItems: activeVisibleTurnItems(next) }
460 : next;
461 return {
462 ...next,
463 visibleTurnItems: shouldShowLocalTurnItem(next, payload)
464 ? upsertVisibleTurnItem(visible, payload, partialTimeline, latestLocalTurnOrdinal)
465 : removeVisibleItem(visible.visibleTurnItems, payload.id),
466 };
467 }
468 case "checkpoint-scope.created":
469 return { ...base, checkpointScopes: upsertEntity(base.checkpointScopes, event.payload) };
470 case "checkpoint.captured":
471 return { ...base, checkpoints: upsertEntity(base.checkpoints, event.payload) };
472 case "checkpoint.rollback-requested":
473 return base;
474 case "context-handoff.updated":
475 return { ...base, contextHandoffs: upsertEntity(base.contextHandoffs, event.payload) };
476 case "context-transfer.created":
477 case "context-transfer.updated":
478 return { ...base, contextTransfers: upsertEntity(base.contextTransfers, event.payload) };
479 }
480 }