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

threadReducer.ts

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