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

threadReducer.ts

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