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

threadReducer.ts

861 lines30.4 KB

1import { pipe } from "effect/Function";
2import * as Arr from "effect/Array";
3import * as O from "effect/Order";
4import type {
5 MessageId,
6 OrchestrationCheckpointSummary,
7 OrchestrationEvent,
8 OrchestrationLatestTurn,
9 OrchestrationMessage,
10 OrchestrationSession,
11 OrchestrationThread,
12 OrchestrationThreadActivity,
13 ThreadPullRequestLink,
14 TurnId,
15} from "@t3tools/contracts";
16import { threadPullRequestKeysEqual } from "@t3tools/shared/threadPullRequests";
17import { isImportedAgentSessionMessageId } from "@t3tools/contracts";
18import { compareDateTimeStrings } from "@t3tools/shared/dateTime";
19​
20export type ThreadDetailReducerResult =
21 | { readonly kind: "updated"; readonly thread: OrchestrationThread }
22 | { readonly kind: "deleted" }
23 | { readonly kind: "unchanged" };
24​
25/** Keep only a legacy route supplied by the server; detail events cannot resolve project hosts. */
26function withPullRequests(
27 thread: OrchestrationThread,
28 pullRequests: ReadonlyArray<ThreadPullRequestLink>,
29 updatedAt: string,
30): ThreadDetailReducerResult {
31 return {
32 kind: "updated",
33 thread: {
34 ...thread,
35 pullRequests,
36 linkedPullRequest:
37 thread.linkedPullRequest &&
38 pullRequests.some(
39 (link) => link.source !== "stack-dismissed" && link.url === thread.linkedPullRequest?.url,
40 )
41 ? thread.linkedPullRequest
42 : null,
43 updatedAt,
44 },
45 };
47​
48const proposedPlanOrder = O.combine<OrchestrationThread["proposedPlans"][number]>(
49 O.mapInput(O.String, (p) => p.createdAt),
50 O.mapInput(O.String, (p) => p.id),
51);
52​
53const checkpointOrder = O.mapInput(
54 O.Number,
55 (cp: OrchestrationThread["checkpoints"][number]) =>
56 cp.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER,
57);
58​
59const activityOrder = O.combineAll<OrchestrationThreadActivity>([
60 O.mapInput(O.Number, (a) => a.sequence ?? Number.MAX_SAFE_INTEGER),
61 O.mapInput(O.String, (a) => a.createdAt),
62 O.mapInput(O.String, (a) => a.id),
63]);
64​
65// Per-array id index so the streaming append path can reject a re-delivered
66// id without rescanning the history. Only arrays this reducer produced are
67// indexed: presence also proves the array is activityOrder-sorted, which
68// snapshot-loaded arrays (DB order, null sequences first) are not.
69const activityIdIndex = new WeakMap<
70 ReadonlyArray<OrchestrationThreadActivity>,
71 Set<OrchestrationThreadActivity["id"]>
72>();
73​
74/**
75 * Matches the validity rule in `deriveLatestContextWindowSnapshot` (and the
76 * server's snapshot-side `dropStaleContextWindowActivities`): rows without a
77 * finite, non-negative `usedTokens` are skipped during the consumer's backward
78 * walk, so they must not replace an earlier resolvable row here.
79 */
80function isResolvableContextWindowActivity(activity: OrchestrationThreadActivity): boolean {
81 if (activity.kind !== "context-window.updated") {
82 return false;
83 }
84 const payload =
85 activity.payload && typeof activity.payload === "object"
86 ? (activity.payload as Record<string, unknown>)
87 : null;
88 const usedTokens = payload?.usedTokens;
89 return typeof usedTokens === "number" && Number.isFinite(usedTokens) && usedTokens >= 0;
91​
92/**
93 * Apply a single orchestration event to an `OrchestrationThread`, returning
94 * the updated thread, a deletion signal, or an "unchanged" marker when the
95 * event doesn't affect this thread.
96 *
97 * This is a pure reducer operating on contract types. UI-specific mapping
98 * (e.g. resolving attachment preview URLs, normalising model slugs, adding
99 * scoped fields like `environmentId`) is the caller's responsibility.
100 */
101export function applyThreadDetailEvent(
102 thread: OrchestrationThread,
103 event: OrchestrationEvent,
104): ThreadDetailReducerResult {
105 switch (event.type) {
106 // ── Project events (irrelevant to thread detail) ────────────────
107 case "project.created":
108 case "project.meta-updated":
109 case "project.deleted":
110 return { kind: "unchanged" };
111​
112 // ── Thread lifecycle ────────────────────────────────────────────
113 case "thread.created":
114 return {
115 kind: "updated",
116 thread: {
117 id: event.payload.threadId,
118 projectId: event.payload.projectId,
119 title: event.payload.title,
120 modelSelection: event.payload.modelSelection,
121 runtimeMode: event.payload.runtimeMode,
122 interactionMode: event.payload.interactionMode,
123 branch: event.payload.branch,
124 worktreePath: event.payload.worktreePath,
125 branchPullRequest: null,
126 latestTurn: null,
127 createdAt: event.payload.createdAt,
128 updatedAt: event.payload.updatedAt,
129 archivedAt: null,
130 settledOverride: null,
131 settledAt: null,
132 unsettledAt: null,
133 activeOrderKey: null,
134 snoozedUntil: null,
135 snoozedAt: null,
136 deletedAt: null,
137 pullRequests: [],
138 messages: [],
139 proposedPlans: [],
140 activities: [],
141 checkpoints: [],
142 session: null,
143 },
144 };
145​
146 case "thread.deleted":
147 return { kind: "deleted" };
148​
149 case "thread.archived":
150 return {
151 kind: "updated",
152 thread: {
153 ...thread,
154 archivedAt: event.payload.archivedAt,
155 titleRegeneration: null,
156 updatedAt: event.payload.updatedAt,
157 },
158 };
159​
160 case "thread.unarchived":
161 return {
162 kind: "updated",
163 thread: { ...thread, archivedAt: null, updatedAt: event.payload.updatedAt },
164 };
165​
166 case "thread.settled":
167 return {
168 kind: "updated",
169 thread: {
170 ...thread,
171 settledOverride: "settled",
172 settledAt: event.payload.settledAt,
173 unsettledAt: null,
174 activeOrderKey: null,
175 updatedAt: event.payload.updatedAt,
176 },
177 };
178​
179 case "thread.unsettled":
180 return {
181 kind: "updated",
182 thread: {
183 ...thread,
184 settledOverride: event.payload.reason === "user" ? "active" : null,
185 settledAt: null,
186 // A thread already pinned active keeps its re-entry stamp: the
187 // activity reset that clears the pin must not reorder the list.
188 unsettledAt:
189 thread.settledOverride === "active"
190 ? (thread.unsettledAt ?? null)
191 : event.payload.updatedAt,
192 updatedAt: event.payload.updatedAt,
193 },
194 };
195​
196 case "thread.snoozed":
197 return {
198 kind: "updated",
199 thread: {
200 ...thread,
201 snoozedUntil: event.payload.snoozedUntil,
202 snoozedAt: event.payload.snoozedAt,
203 updatedAt: event.payload.updatedAt,
204 },
205 };
206​
207 case "thread.unsnoozed":
208 return {
209 kind: "updated",
210 thread: {
211 ...thread,
212 snoozedUntil: null,
213 snoozedAt: null,
214 updatedAt: event.payload.updatedAt,
215 },
216 };
217​
218 case "thread.pinned":
219 return {
220 kind: "updated",
221 thread: {
222 ...thread,
223 pinnedAt: event.payload.pinnedAt,
224 ...(event.payload.pinOrderKey !== undefined
225 ? { pinOrderKey: event.payload.pinOrderKey }
226 : {}),
227 updatedAt: event.payload.updatedAt,
228 },
229 };
230​
231 case "thread.unpinned":
232 return {
233 kind: "updated",
234 thread: {
235 ...thread,
236 pinnedAt: null,
237 pinOrderKey: null,
238 updatedAt: event.payload.updatedAt,
239 },
240 };
241​
242 case "thread.pin-reordered":
243 return {
244 kind: "updated",
245 thread: {
246 ...thread,
247 pinOrderKey: event.payload.orderKey,
248 updatedAt: event.payload.updatedAt,
249 },
250 };
251​
252 // ── Thread metadata ─────────────────────────────────────────────
253 case "thread.meta-updated":
254 return {
255 kind: "updated",
256 thread: {
257 ...thread,
258 ...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
259 ...(event.payload.titleRegeneration !== undefined
260 ? { titleRegeneration: event.payload.titleRegeneration }
261 : {}),
262 ...(event.payload.modelSelection !== undefined
263 ? { modelSelection: event.payload.modelSelection }
264 : {}),
265 ...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
266 ...(event.payload.worktreePath !== undefined
267 ? { worktreePath: event.payload.worktreePath }
268 : {}),
269 ...(event.payload.linkedPullRequest !== undefined
270 ? { linkedPullRequest: event.payload.linkedPullRequest }
271 : {}),
272 ...(event.payload.branchPullRequest !== undefined
273 ? { branchPullRequest: event.payload.branchPullRequest }
274 : {}),
275 ...(event.payload.activeOrderKey !== undefined
276 ? { activeOrderKey: event.payload.activeOrderKey }
277 : {}),
278 updatedAt: event.payload.updatedAt,
279 },
280 };
281​
282 case "thread.pull-request-linked": {
283 const link = event.payload.link;
284 const others = thread.pullRequests.filter(
285 (existing) => !threadPullRequestKeysEqual(existing, link),
286 );
287 return withPullRequests(thread, [...others, link], event.payload.updatedAt);
288 }
289​
290 case "thread.pull-request-unlinked":
291 return withPullRequests(
292 thread,
293 thread.pullRequests.filter(
294 (existing) => !threadPullRequestKeysEqual(existing, event.payload),
295 ),
296 event.payload.updatedAt,
297 );
298​
299 case "thread.pull-request-synced": {
300 if (
301 !thread.pullRequests.some((existing) => threadPullRequestKeysEqual(existing, event.payload))
302 ) {
303 return { kind: "unchanged" };
304 }
305 return withPullRequests(
306 thread,
307 thread.pullRequests.map((existing) =>
308 threadPullRequestKeysEqual(existing, event.payload)
309 ? { ...existing, snapshot: event.payload.snapshot, stack: event.payload.stack }
310 : existing,
311 ),
312 event.payload.updatedAt,
313 );
314 }
315​
316 case "thread.runtime-mode-set":
317 return {
318 kind: "updated",
319 thread: {
320 ...thread,
321 runtimeMode: event.payload.runtimeMode,
322 updatedAt: event.payload.updatedAt,
323 },
324 };
325​
326 case "thread.interaction-mode-set":
327 return {
328 kind: "updated",
329 thread: {
330 ...thread,
331 interactionMode: event.payload.interactionMode,
332 updatedAt: event.payload.updatedAt,
333 },
334 };
335​
336 // ── Turn lifecycle ──────────────────────────────────────────────
337 case "thread.turn-start-requested":
338 return {
339 kind: "updated",
340 thread: {
341 ...thread,
342 ...(event.payload.modelSelection !== undefined
343 ? { modelSelection: event.payload.modelSelection }
344 : {}),
345 runtimeMode: event.payload.runtimeMode,
346 interactionMode: event.payload.interactionMode,
347 updatedAt: event.occurredAt,
348 },
349 };
350​
351 case "thread.turn-interrupt-requested": {
352 if (event.payload.turnId === undefined) {
353 return { kind: "unchanged" };
354 }
355 const latestTurn = thread.latestTurn;
356 if (latestTurn === null || latestTurn.turnId !== event.payload.turnId) {
357 return { kind: "unchanged" };
358 }
359 return {
360 kind: "updated",
361 thread: {
362 ...thread,
363 latestTurn: {
364 ...latestTurn,
365 state: "interrupted",
366 startedAt: latestTurn.startedAt ?? event.payload.createdAt,
367 completedAt: latestTurn.completedAt ?? event.payload.createdAt,
368 },
369 updatedAt: event.occurredAt,
370 },
371 };
372 }
373​
374 // ── Messages ────────────────────────────────────────────────────
375 case "thread.message-sent": {
376 const message: OrchestrationMessage = {
377 id: event.payload.messageId,
378 role: event.payload.role,
379 text: event.payload.text,
380 ...(event.payload.attachments !== undefined
381 ? { attachments: event.payload.attachments }
382 : {}),
383 ...(event.payload.context !== undefined ? { context: event.payload.context } : {}),
384 turnId: event.payload.turnId,
385 streaming: event.payload.streaming,
386 createdAt: event.payload.createdAt,
387 updatedAt: event.payload.updatedAt,
388 };
389​
390 let found = false;
391 const messages = thread.messages.map((entry) => {
392 if (entry.id !== message.id) return entry;
393 found = true;
394 return {
395 ...entry,
396 text: message.streaming
397 ? `${entry.text}${message.text}`
398 : message.text.length > 0
399 ? message.text
400 : entry.text,
401 streaming: message.streaming,
402 ...(message.turnId !== undefined ? { turnId: message.turnId } : {}),
403 ...(message.streaming ? {} : { updatedAt: message.updatedAt }),
404 ...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
405 ...(message.context !== undefined ? { context: message.context } : {}),
406 };
407 });
408 if (!found) messages.push(message);
409 // Update latestTurn for assistant messages bound to a turn. A completed
410 // assistant message only settles the turn once the session is no longer
411 // running it — providers may emit several assistant messages per turn
412 // (commentary between tool calls), and the turn must stay unsettled
413 // until the provider reports turn end. Streaming deltas recompute the
414 // same record, so the previous reference is kept when nothing changed.
415 const turnStillRunning =
416 event.payload.turnId !== null &&
417 thread.session?.status === "running" &&
418 thread.session.activeTurnId === event.payload.turnId;
419 const settlesTurn = !event.payload.streaming && !turnStillRunning;
420 const latestTurn = reuseLatestTurn(
421 thread.latestTurn,
422 event.payload.role === "assistant" &&
423 event.payload.turnId !== null &&
424 (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
425 ? {
426 turnId: event.payload.turnId,
427 state: settlesTurn
428 ? thread.latestTurn?.state === "interrupted"
429 ? "interrupted"
430 : thread.latestTurn?.state === "error"
431 ? "error"
432 : "completed"
433 : "running",
434 requestedAt:
435 thread.latestTurn?.turnId === event.payload.turnId
436 ? thread.latestTurn.requestedAt
437 : event.payload.createdAt,
438 startedAt:
439 thread.latestTurn?.turnId === event.payload.turnId
440 ? (thread.latestTurn.startedAt ?? event.payload.createdAt)
441 : event.payload.createdAt,
442 completedAt: settlesTurn
443 ? event.payload.updatedAt
444 : thread.latestTurn?.turnId === event.payload.turnId
445 ? (thread.latestTurn.completedAt ?? null)
446 : null,
447 assistantMessageId: event.payload.messageId,
448 }
449 : thread.latestTurn,
450 );
451​
452 // Rebind checkpoint assistant message IDs for assistant messages. The
453 // helper hands back the same array when the entry is already bound.
454 const checkpoints =
455 event.payload.role === "assistant" && event.payload.turnId !== null
456 ? rebindCheckpointAssistantMessage(
457 thread.checkpoints,
458 event.payload.turnId,
459 event.payload.messageId,
460 )
461 : thread.checkpoints;
462​
463 return {
464 kind: "updated",
465 thread: {
466 ...thread,
467 messages,
468 checkpoints,
469 latestTurn,
470 updatedAt: event.occurredAt,
471 },
472 };
473 }
474​
475 // ── Session ─────────────────────────────────────────────────────
476 case "thread.session-set": {
477 // Leaving the "running" session status is the turn-end signal: settle a
478 // still-running latest turn so its duration reflects the whole turn.
479 const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
480 const latestTurn = reuseLatestTurn(
481 thread.latestTurn,
482 event.payload.session.status === "running" && event.payload.session.activeTurnId !== null
483 ? {
484 turnId: event.payload.session.activeTurnId,
485 state: "running",
486 requestedAt:
487 thread.latestTurn?.turnId === event.payload.session.activeTurnId
488 ? thread.latestTurn.requestedAt
489 : event.payload.session.updatedAt,
490 startedAt:
491 thread.latestTurn?.turnId === event.payload.session.activeTurnId
492 ? (thread.latestTurn.startedAt ?? event.payload.session.updatedAt)
493 : event.payload.session.updatedAt,
494 completedAt: null,
495 assistantMessageId:
496 thread.latestTurn?.turnId === event.payload.session.activeTurnId
497 ? thread.latestTurn.assistantMessageId
498 : null,
499 }
500 : thread.latestTurn !== null &&
501 thread.latestTurn.state === "running" &&
502 settledTurnState !== null
503 ? {
504 ...thread.latestTurn,
505 state: settledTurnState,
506 // A running turn's completedAt can only hold a mid-turn
507 // placeholder checkpoint timestamp — the session leaving
508 // "running" is the authoritative turn end.
509 completedAt: event.payload.session.updatedAt,
510 }
511 : thread.latestTurn,
512 );
513​
514 return {
515 kind: "updated",
516 thread: {
517 ...thread,
518 session: event.payload.session,
519 latestTurn,
520 updatedAt: event.occurredAt,
521 },
522 };
523 }
524​
525 case "thread.session-stop-requested":
526 return thread.session === null
527 ? { kind: "unchanged" }
528 : {
529 kind: "updated",
530 thread: {
531 ...thread,
532 session: {
533 ...thread.session,
534 status: "stopped",
535 activeTurnId: null,
536 updatedAt: event.payload.createdAt,
537 },
538 updatedAt: event.occurredAt,
539 },
540 };
541​
542 // ── Proposed plans ──────────────────────────────────────────────
543 case "thread.proposed-plan-upserted": {
544 const proposedPlan = event.payload.proposedPlan;
545​
546 const proposedPlans = pipe(
547 thread.proposedPlans,
548 Arr.filter((entry) => entry.id !== proposedPlan.id),
549 Arr.append(proposedPlan),
550 Arr.sort(proposedPlanOrder),
551 );
552​
553 return {
554 kind: "updated",
555 thread: { ...thread, proposedPlans, updatedAt: event.occurredAt },
556 };
557 }
558​
559 // ── Checkpoints / turn diffs ────────────────────────────────────
560 case "thread.turn-diff-completed": {
561 const checkpoint: OrchestrationCheckpointSummary = {
562 turnId: event.payload.turnId,
563 checkpointTurnCount: event.payload.checkpointTurnCount,
564 checkpointRef: event.payload.checkpointRef,
565 status: event.payload.status,
566 files: event.payload.files,
567 assistantMessageId: event.payload.assistantMessageId,
568 completedAt: event.payload.completedAt,
569 };
570​
571 const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId);
572 // Don't overwrite a non-missing checkpoint with a missing one.
573 if (existing && existing.status !== "missing" && checkpoint.status === "missing") {
574 return { kind: "unchanged" };
575 }
576​
577 const checkpoints = pipe(
578 thread.checkpoints,
579 Arr.filter((entry) => entry.turnId !== checkpoint.turnId),
580 Arr.append(checkpoint),
581 Arr.sort(checkpointOrder),
582 );
583​
584 // Mid-turn diff updates produce placeholder checkpoints; record the
585 // checkpoint, but don't settle a turn its session is still running.
586 const diffTurnStillRunning =
587 thread.session?.status === "running" &&
588 thread.session.activeTurnId === event.payload.turnId;
589 const latestTurn =
590 !diffTurnStillRunning &&
591 (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
592 ? {
593 turnId: event.payload.turnId,
594 state:
595 thread.latestTurn?.state === "interrupted"
596 ? "interrupted"
597 : checkpointStatusToTurnState(event.payload.status),
598 requestedAt: thread.latestTurn?.requestedAt ?? event.payload.completedAt,
599 startedAt: thread.latestTurn?.startedAt ?? event.payload.completedAt,
600 completedAt: event.payload.completedAt,
601 assistantMessageId: event.payload.assistantMessageId,
602 }
603 : thread.latestTurn;
604​
605 return {
606 kind: "updated",
607 thread: { ...thread, checkpoints, latestTurn, updatedAt: event.occurredAt },
608 };
609 }
610​
611 // ── Revert ──────────────────────────────────────────────────────
612 case "thread.reverted": {
613 const checkpoints = pipe(
614 thread.checkpoints,
615 Arr.filter(
616 (entry) =>
617 entry.checkpointTurnCount !== undefined &&
618 entry.checkpointTurnCount <= event.payload.turnCount,
619 ),
620 Arr.sort(checkpointOrder),
621 );
622​
623 const retainedTurnIds = new Set(Arr.map(checkpoints, (entry) => entry.turnId));
624 const messages = retainMessagesAfterRevert(
625 thread.messages,
626 retainedTurnIds,
627 event.payload.turnCount,
628 );
629 const proposedPlans = pipe(
630 thread.proposedPlans,
631 Arr.filter((plan) => plan.turnId === null || retainedTurnIds.has(plan.turnId)),
632 );
633 const activities = pipe(
634 thread.activities,
635 Arr.filter((activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId)),
636 );
637 const latestCheckpoint = checkpoints.at(-1) ?? null;
638​
639 return {
640 kind: "updated",
641 thread: {
642 ...thread,
643 checkpoints,
644 messages,
645 proposedPlans,
646 activities,
647 latestTurn:
648 latestCheckpoint === null
649 ? null
650 : {
651 turnId: latestCheckpoint.turnId,
652 state: checkpointStatusToTurnState(
653 latestCheckpoint.status as "ready" | "missing" | "error",
654 ),
655 requestedAt: latestCheckpoint.completedAt,
656 startedAt: latestCheckpoint.completedAt,
657 completedAt: latestCheckpoint.completedAt,
658 assistantMessageId: latestCheckpoint.assistantMessageId ?? null,
659 },
660 updatedAt: event.occurredAt,
661 },
662 };
663 }
664​
665 // ── Activities ──────────────────────────────────────────────────
666 case "thread.activity-appended": {
667 const activity = event.payload.activity;
668 // A resolvable context-window update supersedes earlier resolvable ones
669 // for the same turn: consumers only read the latest value (walking the
670 // array backwards), and providers stream these updates continuously, so
671 // retaining the history grows the thread by thousands of rows over a
672 // long session. Mirrors the server-side snapshot rule in
673 // dropStaleContextWindowActivities; retention stays per turn so a
674 // thread.reverted that discards turns can still resolve a value from
675 // the turns that survive.
676 const supersedesContextWindow = isResolvableContextWindowActivity(activity);
677 // Live streams append in order: an unseen id sorting at/after the tail
678 // of a known-sorted array appends without re-filtering and re-sorting
679 // the whole history on every event. The id set moves forward to the new
680 // array; a superseded array falls back to the sorting path.
681 const ids = activityIdIndex.get(thread.activities);
682 const lastActivity = thread.activities.at(-1);
683 if (
684 !supersedesContextWindow &&
685 ids !== undefined &&
686 (lastActivity === undefined || activityOrder(lastActivity, activity) <= 0) &&
687 !ids.has(activity.id)
688 ) {
689 const activities = Arr.append(thread.activities, activity);
690 activityIdIndex.delete(thread.activities);
691 ids.add(activity.id);
692 activityIdIndex.set(activities, ids);
693 return {
694 kind: "updated",
695 thread: {
696 ...thread,
697 activities,
698 updatedAt: event.occurredAt,
699 },
700 };
701 }
702 const activities = pipe(
703 thread.activities,
704 Arr.filter(
705 (entry) =>
706 entry.id !== activity.id &&
707 !(
708 supersedesContextWindow &&
709 entry.turnId === activity.turnId &&
710 isResolvableContextWindowActivity(entry)
711 ),
712 ),
713 Arr.append(activity),
714 Arr.sort(activityOrder),
715 );
716 activityIdIndex.set(activities, new Set(activities.map((entry) => entry.id)));
717​
718 return {
719 kind: "updated",
720 thread: { ...thread, activities, updatedAt: event.occurredAt },
721 };
722 }
723​
724 // ── Events that don't mutate thread state directly ──────────────
725 case "thread.approval-response-requested":
726 case "thread.user-input-response-requested":
727 case "thread.checkpoint-revert-requested":
728 return { kind: "unchanged" };
729 }
730​
731 // Forward-compatible: ignore unrecognized event types.
732 return { kind: "unchanged" };
734​
735// ── Helpers ──────────────────────────────────────────────────────────
736​
737/**
738 * Turn state to settle a still-running latest turn with when its session
739 * leaves the "running" status, or null while the session is (re)starting or
740 * running and the turn must stay unsettled.
741 */
742function settledTurnStateForSessionStatus(
743 status: OrchestrationSession["status"],
744): "completed" | "interrupted" | "error" | null {
745 switch (status) {
746 case "idle":
747 case "ready":
748 return "completed";
749 case "error":
750 return "error";
751 case "interrupted":
752 case "stopped":
753 return "interrupted";
754 case "starting":
755 case "running":
756 return null;
757 }
759​
760function checkpointStatusToTurnState(
761 status: "ready" | "missing" | "error",
762): OrchestrationLatestTurn["state"] {
763 switch (status) {
764 case "ready":
765 return "completed";
766 case "error":
767 return "error";
768 case "missing":
769 return "completed";
770 }
772​
773/**
774 * Returns `previous` when `next` matches it field for field, otherwise `next`.
775 * Streaming cases recompute the latest turn on every delta, and keeping the
776 * old reference lets selectors and memos keyed on `latestTurn` skip work.
777 */
778function reuseLatestTurn(
779 previous: OrchestrationLatestTurn | null,
780 next: OrchestrationLatestTurn | null,
781): OrchestrationLatestTurn | null {
782 if (previous === null || next === null) {
783 return next;
784 }
785 return previous.turnId === next.turnId &&
786 previous.state === next.state &&
787 previous.requestedAt === next.requestedAt &&
788 previous.startedAt === next.startedAt &&
789 previous.completedAt === next.completedAt &&
790 previous.assistantMessageId === next.assistantMessageId &&
791 previous.sourceProposedPlan?.threadId === next.sourceProposedPlan?.threadId &&
792 previous.sourceProposedPlan?.planId === next.sourceProposedPlan?.planId
793 ? previous
794 : next;
796​
797/**
798 * Points the checkpoint for `turnId` at `messageId`. Returns the input array
799 * untouched when no checkpoint needs rebinding, so streaming deltas for an
800 * already-bound message do not allocate a new `checkpoints` reference.
801 */
802function rebindCheckpointAssistantMessage(
803 checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
804 turnId: TurnId,
805 messageId: MessageId,
806): ReadonlyArray<OrchestrationCheckpointSummary> {
807 const needsRebind = checkpoints.some(
808 (entry) => entry.turnId === turnId && entry.assistantMessageId !== messageId,
809 );
810 if (!needsRebind) {
811 return checkpoints;
812 }
813 return Arr.map(checkpoints, (entry) =>
814 entry.turnId === turnId ? { ...entry, assistantMessageId: messageId } : entry,
815 );
817​
818function retainMessagesAfterRevert(
819 messages: ReadonlyArray<OrchestrationMessage>,
820 retainedTurnIds: ReadonlySet<string>,
821 turnCount: number,
822): OrchestrationMessage[] {
823 const retainedMessageIds = new Set<string>();
824 for (const message of messages) {
825 if (message.role === "system" || isImportedAgentSessionMessageId(message.id)) {
826 retainedMessageIds.add(message.id);
827 } else if (message.turnId !== null && retainedTurnIds.has(message.turnId)) {
828 retainedMessageIds.add(message.id);
829 }
830 }
831​
832 for (const role of ["user", "assistant"] as const) {
833 const retainedCount = messages.filter(
834 (message) =>
835 message.role === role &&
836 !isImportedAgentSessionMessageId(message.id) &&
837 retainedMessageIds.has(message.id),
838 ).length;
839 const missingCount = Math.max(0, turnCount - retainedCount);
840 const fallbackMessages = messages
841 .filter(
842 (message) =>
843 message.role === role &&
844 !retainedMessageIds.has(message.id) &&
845 (message.turnId === null || retainedTurnIds.has(message.turnId)),
846 )
847 // `.sort()`, not `.toSorted()`: `.filter()` above already returned a fresh array, and
848 // this is shared with mobile, which runs on Hermes and has no ES2023 array methods.
849 .sort(
850 (left, right) =>
851 compareDateTimeStrings(left.createdAt, right.createdAt) ||
852 left.id.localeCompare(right.id),
853 )
854 .slice(0, missingCount);
855 for (const message of fallbackMessages) {
856 retainedMessageIds.add(message.id);
857 }
858 }
859​
860 return Arr.filter(messages, (message) => retainedMessageIds.has(message.id));