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

threadReducer.ts

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