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

threadReducer.ts

860 lines30.3 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 turnId: event.payload.turnId,
384 streaming: event.payload.streaming,
385 createdAt: event.payload.createdAt,
386 updatedAt: event.payload.updatedAt,
387 };
388​
389 const existingMessage = thread.messages.find((entry) => entry.id === message.id);
390 const messages = existingMessage
391 ? Arr.map(thread.messages, (entry) =>
392 entry.id !== message.id
393 ? entry
394 : {
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
405 ? { attachments: message.attachments }
406 : {}),
407 },
408 )
409 : Arr.append(thread.messages, message);
410 // Update latestTurn for assistant messages bound to a turn. A completed
411 // assistant message only settles the turn once the session is no longer
412 // running it — providers may emit several assistant messages per turn
413 // (commentary between tool calls), and the turn must stay unsettled
414 // until the provider reports turn end. Streaming deltas recompute the
415 // same record, so the previous reference is kept when nothing changed.
416 const turnStillRunning =
417 event.payload.turnId !== null &&
418 thread.session?.status === "running" &&
419 thread.session.activeTurnId === event.payload.turnId;
420 const settlesTurn = !event.payload.streaming && !turnStillRunning;
421 const latestTurn = reuseLatestTurn(
422 thread.latestTurn,
423 event.payload.role === "assistant" &&
424 event.payload.turnId !== null &&
425 (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
426 ? {
427 turnId: event.payload.turnId,
428 state: settlesTurn
429 ? thread.latestTurn?.state === "interrupted"
430 ? "interrupted"
431 : thread.latestTurn?.state === "error"
432 ? "error"
433 : "completed"
434 : "running",
435 requestedAt:
436 thread.latestTurn?.turnId === event.payload.turnId
437 ? thread.latestTurn.requestedAt
438 : event.payload.createdAt,
439 startedAt:
440 thread.latestTurn?.turnId === event.payload.turnId
441 ? (thread.latestTurn.startedAt ?? event.payload.createdAt)
442 : event.payload.createdAt,
443 completedAt: settlesTurn
444 ? event.payload.updatedAt
445 : thread.latestTurn?.turnId === event.payload.turnId
446 ? (thread.latestTurn.completedAt ?? null)
447 : null,
448 assistantMessageId: event.payload.messageId,
449 }
450 : thread.latestTurn,
451 );
452​
453 // Rebind checkpoint assistant message IDs for assistant messages. The
454 // helper hands back the same array when the entry is already bound.
455 const checkpoints =
456 event.payload.role === "assistant" && event.payload.turnId !== null
457 ? rebindCheckpointAssistantMessage(
458 thread.checkpoints,
459 event.payload.turnId,
460 event.payload.messageId,
461 )
462 : thread.checkpoints;
463​
464 return {
465 kind: "updated",
466 thread: {
467 ...thread,
468 messages,
469 checkpoints,
470 latestTurn,
471 updatedAt: event.occurredAt,
472 },
473 };
474 }
475​
476 // ── Session ─────────────────────────────────────────────────────
477 case "thread.session-set": {
478 // Leaving the "running" session status is the turn-end signal: settle a
479 // still-running latest turn so its duration reflects the whole turn.
480 const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
481 const latestTurn = reuseLatestTurn(
482 thread.latestTurn,
483 event.payload.session.status === "running" && event.payload.session.activeTurnId !== null
484 ? {
485 turnId: event.payload.session.activeTurnId,
486 state: "running",
487 requestedAt:
488 thread.latestTurn?.turnId === event.payload.session.activeTurnId
489 ? thread.latestTurn.requestedAt
490 : event.payload.session.updatedAt,
491 startedAt:
492 thread.latestTurn?.turnId === event.payload.session.activeTurnId
493 ? (thread.latestTurn.startedAt ?? event.payload.session.updatedAt)
494 : event.payload.session.updatedAt,
495 completedAt: null,
496 assistantMessageId:
497 thread.latestTurn?.turnId === event.payload.session.activeTurnId
498 ? thread.latestTurn.assistantMessageId
499 : null,
500 }
501 : thread.latestTurn !== null &&
502 thread.latestTurn.state === "running" &&
503 settledTurnState !== null
504 ? {
505 ...thread.latestTurn,
506 state: settledTurnState,
507 // A running turn's completedAt can only hold a mid-turn
508 // placeholder checkpoint timestamp — the session leaving
509 // "running" is the authoritative turn end.
510 completedAt: event.payload.session.updatedAt,
511 }
512 : thread.latestTurn,
513 );
514​
515 return {
516 kind: "updated",
517 thread: {
518 ...thread,
519 session: event.payload.session,
520 latestTurn,
521 updatedAt: event.occurredAt,
522 },
523 };
524 }
525​
526 case "thread.session-stop-requested":
527 return thread.session === null
528 ? { kind: "unchanged" }
529 : {
530 kind: "updated",
531 thread: {
532 ...thread,
533 session: {
534 ...thread.session,
535 status: "stopped",
536 activeTurnId: null,
537 updatedAt: event.payload.createdAt,
538 },
539 updatedAt: event.occurredAt,
540 },
541 };
542​
543 // ── Proposed plans ──────────────────────────────────────────────
544 case "thread.proposed-plan-upserted": {
545 const proposedPlan = event.payload.proposedPlan;
546​
547 const proposedPlans = pipe(
548 thread.proposedPlans,
549 Arr.filter((entry) => entry.id !== proposedPlan.id),
550 Arr.append(proposedPlan),
551 Arr.sort(proposedPlanOrder),
552 );
553​
554 return {
555 kind: "updated",
556 thread: { ...thread, proposedPlans, updatedAt: event.occurredAt },
557 };
558 }
559​
560 // ── Checkpoints / turn diffs ────────────────────────────────────
561 case "thread.turn-diff-completed": {
562 const checkpoint: OrchestrationCheckpointSummary = {
563 turnId: event.payload.turnId,
564 checkpointTurnCount: event.payload.checkpointTurnCount,
565 checkpointRef: event.payload.checkpointRef,
566 status: event.payload.status,
567 files: event.payload.files,
568 assistantMessageId: event.payload.assistantMessageId,
569 completedAt: event.payload.completedAt,
570 };
571​
572 const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId);
573 // Don't overwrite a non-missing checkpoint with a missing one.
574 if (existing && existing.status !== "missing" && checkpoint.status === "missing") {
575 return { kind: "unchanged" };
576 }
577​
578 const checkpoints = pipe(
579 thread.checkpoints,
580 Arr.filter((entry) => entry.turnId !== checkpoint.turnId),
581 Arr.append(checkpoint),
582 Arr.sort(checkpointOrder),
583 );
584​
585 // Mid-turn diff updates produce placeholder checkpoints; record the
586 // checkpoint, but don't settle a turn its session is still running.
587 const diffTurnStillRunning =
588 thread.session?.status === "running" &&
589 thread.session.activeTurnId === event.payload.turnId;
590 const latestTurn =
591 !diffTurnStillRunning &&
592 (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
593 ? {
594 turnId: event.payload.turnId,
595 state:
596 thread.latestTurn?.state === "interrupted"
597 ? "interrupted"
598 : checkpointStatusToTurnState(event.payload.status),
599 requestedAt: thread.latestTurn?.requestedAt ?? event.payload.completedAt,
600 startedAt: thread.latestTurn?.startedAt ?? event.payload.completedAt,
601 completedAt: event.payload.completedAt,
602 assistantMessageId: event.payload.assistantMessageId,
603 }
604 : thread.latestTurn;
605​
606 return {
607 kind: "updated",
608 thread: { ...thread, checkpoints, latestTurn, updatedAt: event.occurredAt },
609 };
610 }
611​
612 // ── Revert ──────────────────────────────────────────────────────
613 case "thread.reverted": {
614 const checkpoints = pipe(
615 thread.checkpoints,
616 Arr.filter(
617 (entry) =>
618 entry.checkpointTurnCount !== undefined &&
619 entry.checkpointTurnCount <= event.payload.turnCount,
620 ),
621 Arr.sort(checkpointOrder),
622 );
623​
624 const retainedTurnIds = new Set(Arr.map(checkpoints, (entry) => entry.turnId));
625 const messages = retainMessagesAfterRevert(
626 thread.messages,
627 retainedTurnIds,
628 event.payload.turnCount,
629 );
630 const proposedPlans = pipe(
631 thread.proposedPlans,
632 Arr.filter((plan) => plan.turnId === null || retainedTurnIds.has(plan.turnId)),
633 );
634 const activities = pipe(
635 thread.activities,
636 Arr.filter((activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId)),
637 );
638 const latestCheckpoint = checkpoints.at(-1) ?? null;
639​
640 return {
641 kind: "updated",
642 thread: {
643 ...thread,
644 checkpoints,
645 messages,
646 proposedPlans,
647 activities,
648 latestTurn:
649 latestCheckpoint === null
650 ? null
651 : {
652 turnId: latestCheckpoint.turnId,
653 state: checkpointStatusToTurnState(
654 latestCheckpoint.status as "ready" | "missing" | "error",
655 ),
656 requestedAt: latestCheckpoint.completedAt,
657 startedAt: latestCheckpoint.completedAt,
658 completedAt: latestCheckpoint.completedAt,
659 assistantMessageId: latestCheckpoint.assistantMessageId ?? null,
660 },
661 updatedAt: event.occurredAt,
662 },
663 };
664 }
665​
666 // ── Activities ──────────────────────────────────────────────────
667 case "thread.activity-appended": {
668 const activity = event.payload.activity;
669 // A resolvable context-window update supersedes earlier resolvable ones
670 // for the same turn: consumers only read the latest value (walking the
671 // array backwards), and providers stream these updates continuously, so
672 // retaining the history grows the thread by thousands of rows over a
673 // long session. Mirrors the server-side snapshot rule in
674 // dropStaleContextWindowActivities; retention stays per turn so a
675 // thread.reverted that discards turns can still resolve a value from
676 // the turns that survive.
677 const supersedesContextWindow = isResolvableContextWindowActivity(activity);
678 // Live streams append in order: an unseen id sorting at/after the tail
679 // of a known-sorted array appends without re-filtering and re-sorting
680 // the whole history on every event. The id set moves forward to the new
681 // array; a superseded array falls back to the sorting path.
682 const ids = activityIdIndex.get(thread.activities);
683 const lastActivity = thread.activities.at(-1);
684 if (
685 !supersedesContextWindow &&
686 ids !== undefined &&
687 (lastActivity === undefined || activityOrder(lastActivity, activity) <= 0) &&
688 !ids.has(activity.id)
689 ) {
690 const activities = Arr.append(thread.activities, activity);
691 activityIdIndex.delete(thread.activities);
692 ids.add(activity.id);
693 activityIdIndex.set(activities, ids);
694 return {
695 kind: "updated",
696 thread: {
697 ...thread,
698 activities,
699 updatedAt: event.occurredAt,
700 },
701 };
702 }
703 const activities = pipe(
704 thread.activities,
705 Arr.filter(
706 (entry) =>
707 entry.id !== activity.id &&
708 !(
709 supersedesContextWindow &&
710 entry.turnId === activity.turnId &&
711 isResolvableContextWindowActivity(entry)
712 ),
713 ),
714 Arr.append(activity),
715 Arr.sort(activityOrder),
716 );
717 activityIdIndex.set(activities, new Set(activities.map((entry) => entry.id)));
718​
719 return {
720 kind: "updated",
721 thread: { ...thread, activities, updatedAt: event.occurredAt },
722 };
723 }
724​
725 // ── Events that don't mutate thread state directly ──────────────
726 case "thread.approval-response-requested":
727 case "thread.user-input-response-requested":
728 case "thread.checkpoint-revert-requested":
729 return { kind: "unchanged" };
730 }
731​
732 // Forward-compatible: ignore unrecognized event types.
733 return { kind: "unchanged" };
735​
736// ── Helpers ──────────────────────────────────────────────────────────
737​
738/**
739 * Turn state to settle a still-running latest turn with when its session
740 * leaves the "running" status, or null while the session is (re)starting or
741 * running and the turn must stay unsettled.
742 */
743function settledTurnStateForSessionStatus(
744 status: OrchestrationSession["status"],
745): "completed" | "interrupted" | "error" | null {
746 switch (status) {
747 case "idle":
748 case "ready":
749 return "completed";
750 case "error":
751 return "error";
752 case "interrupted":
753 case "stopped":
754 return "interrupted";
755 case "starting":
756 case "running":
757 return null;
758 }
760​
761function checkpointStatusToTurnState(
762 status: "ready" | "missing" | "error",
763): OrchestrationLatestTurn["state"] {
764 switch (status) {
765 case "ready":
766 return "completed";
767 case "error":
768 return "error";
769 case "missing":
770 return "completed";
771 }
773​
774/**
775 * Returns `previous` when `next` matches it field for field, otherwise `next`.
776 * Streaming cases recompute the latest turn on every delta, and keeping the
777 * old reference lets selectors and memos keyed on `latestTurn` skip work.
778 */
779function reuseLatestTurn(
780 previous: OrchestrationLatestTurn | null,
781 next: OrchestrationLatestTurn | null,
782): OrchestrationLatestTurn | null {
783 if (previous === null || next === null) {
784 return next;
785 }
786 return previous.turnId === next.turnId &&
787 previous.state === next.state &&
788 previous.requestedAt === next.requestedAt &&
789 previous.startedAt === next.startedAt &&
790 previous.completedAt === next.completedAt &&
791 previous.assistantMessageId === next.assistantMessageId &&
792 previous.sourceProposedPlan?.threadId === next.sourceProposedPlan?.threadId &&
793 previous.sourceProposedPlan?.planId === next.sourceProposedPlan?.planId
794 ? previous
795 : next;
797​
798/**
799 * Points the checkpoint for `turnId` at `messageId`. Returns the input array
800 * untouched when no checkpoint needs rebinding, so streaming deltas for an
801 * already-bound message do not allocate a new `checkpoints` reference.
802 */
803function rebindCheckpointAssistantMessage(
804 checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
805 turnId: TurnId,
806 messageId: MessageId,
807): ReadonlyArray<OrchestrationCheckpointSummary> {
808 const needsRebind = checkpoints.some(
809 (entry) => entry.turnId === turnId && entry.assistantMessageId !== messageId,
810 );
811 if (!needsRebind) {
812 return checkpoints;
813 }
814 return Arr.map(checkpoints, (entry) =>
815 entry.turnId === turnId ? { ...entry, assistantMessageId: messageId } : entry,
816 );
818​
819function retainMessagesAfterRevert(
820 messages: ReadonlyArray<OrchestrationMessage>,
821 retainedTurnIds: ReadonlySet<string>,
822 turnCount: number,
823): OrchestrationMessage[] {
824 const retainedMessageIds = new Set<string>();
825 for (const message of messages) {
826 if (message.role === "system" || isImportedAgentSessionMessageId(message.id)) {
827 retainedMessageIds.add(message.id);
828 } else if (message.turnId !== null && retainedTurnIds.has(message.turnId)) {
829 retainedMessageIds.add(message.id);
830 }
831 }
832​
833 for (const role of ["user", "assistant"] as const) {
834 const retainedCount = messages.filter(
835 (message) =>
836 message.role === role &&
837 !isImportedAgentSessionMessageId(message.id) &&
838 retainedMessageIds.has(message.id),
839 ).length;
840 const missingCount = Math.max(0, turnCount - retainedCount);
841 const fallbackMessages = messages
842 .filter(
843 (message) =>
844 message.role === role &&
845 !retainedMessageIds.has(message.id) &&
846 (message.turnId === null || retainedTurnIds.has(message.turnId)),
847 )
848 .toSorted(
849 (left, right) =>
850 compareDateTimeStrings(left.createdAt, right.createdAt) ||
851 left.id.localeCompare(right.id),
852 )
853 .slice(0, missingCount);
854 for (const message of fallbackMessages) {
855 retainedMessageIds.add(message.id);
856 }
857 }
858​
859 return Arr.filter(messages, (message) => retainedMessageIds.has(message.id));