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

threadReducer.ts

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