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

threadReducer.ts

883 lines31.0 KB

1import { pendingProviderTurnUpdate } from "@t3tools/shared/pendingProviderTurn";
2import { pipe } from "effect/Function";
3import * as Arr from "effect/Array";
4import * as O from "effect/Order";
5import type {
6 MessageId,
7 OrchestrationCheckpointSummary,
8 OrchestrationEvent,
9 OrchestrationLatestTurn,
10 OrchestrationMessage,
11 OrchestrationSession,
12 OrchestrationThread,
13 OrchestrationThreadActivity,
14 ThreadPullRequestLink,
15 TurnId,
16} from "@t3tools/contracts";
17import { threadPullRequestKeysEqual } from "@t3tools/shared/threadPullRequests";
18import { isImportedAgentSessionMessageId } from "@t3tools/contracts";
19import { compareDateTimeStrings } from "@t3tools/shared/dateTime";
20​
21export type ThreadDetailReducerResult =
22 | { readonly kind: "updated"; readonly thread: OrchestrationThread }
23 | { readonly kind: "deleted" }
24 | { readonly kind: "unchanged" };
25​
26/** Keep only a legacy route supplied by the server; detail events cannot resolve project hosts. */
27function withPullRequests(
28 thread: OrchestrationThread,
29 pullRequests: ReadonlyArray<ThreadPullRequestLink>,
30 updatedAt: string,
31): ThreadDetailReducerResult {
32 return {
33 kind: "updated",
34 thread: {
35 ...thread,
36 pullRequests,
37 linkedPullRequest:
38 thread.linkedPullRequest &&
39 pullRequests.some(
40 (link) => link.source !== "stack-dismissed" && link.url === thread.linkedPullRequest?.url,
41 )
42 ? thread.linkedPullRequest
43 : null,
44 updatedAt,
45 },
46 };
48​
49const proposedPlanOrder = O.combine<OrchestrationThread["proposedPlans"][number]>(
50 O.mapInput(O.String, (p) => p.createdAt),
51 O.mapInput(O.String, (p) => p.id),
52);
53​
54const checkpointOrder = O.mapInput(
55 O.Number,
56 (cp: OrchestrationThread["checkpoints"][number]) =>
57 cp.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER,
58);
59​
60const activityOrder = O.combineAll<OrchestrationThreadActivity>([
61 O.mapInput(O.Number, (a) => a.sequence ?? Number.MAX_SAFE_INTEGER),
62 O.mapInput(O.String, (a) => a.createdAt),
63 O.mapInput(O.String, (a) => a.id),
64]);
65​
66// Per-array id index so the streaming append path can reject a re-delivered
67// id without rescanning the history. Only arrays this reducer produced are
68// indexed: presence also proves the array is activityOrder-sorted, which
69// snapshot-loaded arrays (DB order, null sequences first) are not.
70const activityIdIndex = new WeakMap<
71 ReadonlyArray<OrchestrationThreadActivity>,
72 Set<OrchestrationThreadActivity["id"]>
73>();
74​
75/**
76 * Matches the validity rule in `deriveLatestContextWindowSnapshot` (and the
77 * server's snapshot-side `dropStaleContextWindowActivities`): rows without a
78 * finite, non-negative `usedTokens` are skipped during the consumer's backward
79 * walk, so they must not replace an earlier resolvable row here.
80 */
81function isResolvableContextWindowActivity(activity: OrchestrationThreadActivity): boolean {
82 if (activity.kind !== "context-window.updated") {
83 return false;
84 }
85 const payload =
86 activity.payload && typeof activity.payload === "object"
87 ? (activity.payload as Record<string, unknown>)
88 : null;
89 const usedTokens = payload?.usedTokens;
90 return typeof usedTokens === "number" && Number.isFinite(usedTokens) && usedTokens >= 0;
92​
93/**
94 * Apply a single orchestration event to an `OrchestrationThread`, returning
95 * the updated thread, a deletion signal, or an "unchanged" marker when the
96 * event doesn't affect this thread.
97 *
98 * This is a pure reducer operating on contract types. UI-specific mapping
99 * (e.g. resolving attachment preview URLs, normalising model slugs, adding
100 * scoped fields like `environmentId`) is the caller's responsibility.
101 */
102function applyThreadDetailEventBase(
103 thread: OrchestrationThread,
104 event: OrchestrationEvent,
105): ThreadDetailReducerResult {
106 switch (event.type) {
107 // ── Project events (irrelevant to thread detail) ────────────────
108 case "project.created":
109 case "project.meta-updated":
110 case "project.deleted":
111 return { kind: "unchanged" };
112​
113 // ── Thread lifecycle ────────────────────────────────────────────
114 case "thread.created":
115 return {
116 kind: "updated",
117 thread: {
118 id: event.payload.threadId,
119 projectId: event.payload.projectId,
120 title: event.payload.title,
121 modelSelection: event.payload.modelSelection,
122 runtimeMode: event.payload.runtimeMode,
123 interactionMode: event.payload.interactionMode,
124 branch: event.payload.branch,
125 worktreePath: event.payload.worktreePath,
126 branchPullRequest: null,
127 latestTurn: null,
128 createdAt: event.payload.createdAt,
129 updatedAt: event.payload.updatedAt,
130 archivedAt: null,
131 settledOverride: null,
132 settledAt: null,
133 unsettledAt: null,
134 activeOrderKey: 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 // ── Thread metadata ─────────────────────────────────────────────
254 case "thread.meta-updated":
255 return {
256 kind: "updated",
257 thread: {
258 ...thread,
259 ...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
260 ...(event.payload.titleRegeneration !== undefined
261 ? { titleRegeneration: event.payload.titleRegeneration }
262 : {}),
263 ...(event.payload.modelSelection !== undefined
264 ? { modelSelection: event.payload.modelSelection }
265 : {}),
266 ...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
267 ...(event.payload.worktreePath !== undefined
268 ? { worktreePath: event.payload.worktreePath }
269 : {}),
270 ...(event.payload.linkedPullRequest !== undefined
271 ? { linkedPullRequest: event.payload.linkedPullRequest }
272 : {}),
273 ...(event.payload.branchPullRequest !== undefined
274 ? { branchPullRequest: event.payload.branchPullRequest }
275 : {}),
276 ...(event.payload.activeOrderKey !== undefined
277 ? { activeOrderKey: event.payload.activeOrderKey }
278 : {}),
279 updatedAt: event.payload.updatedAt,
280 },
281 };
282​
283 case "thread.pull-request-linked": {
284 const link = event.payload.link;
285 const others = thread.pullRequests.filter(
286 (existing) => !threadPullRequestKeysEqual(existing, link),
287 );
288 return withPullRequests(thread, [...others, link], event.payload.updatedAt);
289 }
290​
291 case "thread.pull-request-unlinked":
292 return withPullRequests(
293 thread,
294 thread.pullRequests.filter(
295 (existing) => !threadPullRequestKeysEqual(existing, event.payload),
296 ),
297 event.payload.updatedAt,
298 );
299​
300 case "thread.pull-request-synced": {
301 if (
302 !thread.pullRequests.some((existing) => threadPullRequestKeysEqual(existing, event.payload))
303 ) {
304 return { kind: "unchanged" };
305 }
306 return withPullRequests(
307 thread,
308 thread.pullRequests.map((existing) =>
309 threadPullRequestKeysEqual(existing, event.payload)
310 ? { ...existing, snapshot: event.payload.snapshot, stack: event.payload.stack }
311 : existing,
312 ),
313 event.payload.updatedAt,
314 );
315 }
316​
317 case "thread.runtime-mode-set":
318 return {
319 kind: "updated",
320 thread: {
321 ...thread,
322 runtimeMode: event.payload.runtimeMode,
323 updatedAt: event.payload.updatedAt,
324 },
325 };
326​
327 case "thread.interaction-mode-set":
328 return {
329 kind: "updated",
330 thread: {
331 ...thread,
332 interactionMode: event.payload.interactionMode,
333 updatedAt: event.payload.updatedAt,
334 },
335 };
336​
337 // ── Turn lifecycle ──────────────────────────────────────────────
338 case "thread.turn-start-requested":
339 return {
340 kind: "updated",
341 thread: {
342 ...thread,
343 ...(event.payload.modelSelection !== undefined
344 ? { modelSelection: event.payload.modelSelection }
345 : {}),
346 runtimeMode: event.payload.runtimeMode,
347 interactionMode: event.payload.interactionMode,
348 updatedAt: event.occurredAt,
349 },
350 };
351​
352 case "thread.turn-interrupt-requested": {
353 if (event.payload.turnId === undefined) {
354 return { kind: "unchanged" };
355 }
356 const latestTurn = thread.latestTurn;
357 if (latestTurn === null || latestTurn.turnId !== event.payload.turnId) {
358 return { kind: "unchanged" };
359 }
360 return {
361 kind: "updated",
362 thread: {
363 ...thread,
364 latestTurn: {
365 ...latestTurn,
366 state: "interrupted",
367 startedAt: latestTurn.startedAt ?? event.payload.createdAt,
368 completedAt: latestTurn.completedAt ?? event.payload.createdAt,
369 },
370 updatedAt: event.occurredAt,
371 },
372 };
373 }
374​
375 // ── Messages ────────────────────────────────────────────────────
376 case "thread.message-sent": {
377 const message: OrchestrationMessage = {
378 id: event.payload.messageId,
379 role: event.payload.role,
380 text: event.payload.text,
381 ...(event.payload.attachments !== undefined
382 ? { attachments: event.payload.attachments }
383 : {}),
384 ...(event.payload.context !== undefined ? { context: event.payload.context } : {}),
385 turnId: event.payload.turnId,
386 streaming: event.payload.streaming,
387 createdAt: event.payload.createdAt,
388 updatedAt: event.payload.updatedAt,
389 };
390​
391 let found = false;
392 const messages = thread.messages.map((entry) => {
393 if (entry.id !== message.id) return entry;
394 found = true;
395 return {
396 ...entry,
397 text: message.streaming
398 ? `${entry.text}${message.text}`
399 : message.text.length > 0
400 ? message.text
401 : entry.text,
402 streaming: message.streaming,
403 ...(message.turnId !== undefined ? { turnId: message.turnId } : {}),
404 ...(message.streaming ? {} : { updatedAt: message.updatedAt }),
405 ...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
406 ...(message.context !== undefined ? { context: message.context } : {}),
407 };
408 });
409 if (!found) messages.push(message);
410 // Update latestTurn for assistant messages bound to a turn. A completed
411 // assistant message only settles the turn once the session is no longer
412 // running it — providers may emit several assistant messages per turn
413 // (commentary between tool calls), and the turn must stay unsettled
414 // until the provider reports turn end. Streaming deltas recompute the
415 // same record, so the previous reference is kept when nothing changed.
416 const turnStillRunning =
417 event.payload.turnId !== null &&
418 thread.session?.status === "running" &&
419 thread.session.activeTurnId === event.payload.turnId;
420 const settlesTurn = !event.payload.streaming && !turnStillRunning;
421 const latestTurn = reuseLatestTurn(
422 thread.latestTurn,
423 event.payload.role === "assistant" &&
424 event.payload.turnId !== null &&
425 (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
426 ? {
427 turnId: event.payload.turnId,
428 state: settlesTurn
429 ? thread.latestTurn?.state === "interrupted"
430 ? "interrupted"
431 : thread.latestTurn?.state === "error"
432 ? "error"
433 : "completed"
434 : "running",
435 requestedAt:
436 thread.latestTurn?.turnId === event.payload.turnId
437 ? thread.latestTurn.requestedAt
438 : event.payload.createdAt,
439 startedAt:
440 thread.latestTurn?.turnId === event.payload.turnId
441 ? (thread.latestTurn.startedAt ?? event.payload.createdAt)
442 : event.payload.createdAt,
443 completedAt: settlesTurn
444 ? event.payload.updatedAt
445 : thread.latestTurn?.turnId === event.payload.turnId
446 ? (thread.latestTurn.completedAt ?? null)
447 : null,
448 assistantMessageId: event.payload.messageId,
449 }
450 : thread.latestTurn,
451 );
452​
453 // Rebind checkpoint assistant message IDs for assistant messages. The
454 // helper hands back the same array when the entry is already bound.
455 const checkpoints =
456 event.payload.role === "assistant" && event.payload.turnId !== null
457 ? rebindCheckpointAssistantMessage(
458 thread.checkpoints,
459 event.payload.turnId,
460 event.payload.messageId,
461 )
462 : thread.checkpoints;
463​
464 return {
465 kind: "updated",
466 thread: {
467 ...thread,
468 messages,
469 checkpoints,
470 latestTurn,
471 updatedAt: event.occurredAt,
472 },
473 };
474 }
475​
476 // ── Session ─────────────────────────────────────────────────────
477 case "thread.session-set": {
478 // Leaving the "running" session status is the turn-end signal: settle a
479 // still-running latest turn so its duration reflects the whole turn.
480 const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
481 const latestTurn = reuseLatestTurn(
482 thread.latestTurn,
483 event.payload.session.status === "running" && event.payload.session.activeTurnId !== null
484 ? {
485 turnId: event.payload.session.activeTurnId,
486 state: "running",
487 requestedAt:
488 thread.latestTurn?.turnId === event.payload.session.activeTurnId
489 ? thread.latestTurn.requestedAt
490 : event.payload.session.updatedAt,
491 startedAt:
492 thread.latestTurn?.turnId === event.payload.session.activeTurnId
493 ? (thread.latestTurn.startedAt ?? event.payload.session.updatedAt)
494 : event.payload.session.updatedAt,
495 completedAt: null,
496 assistantMessageId:
497 thread.latestTurn?.turnId === event.payload.session.activeTurnId
498 ? thread.latestTurn.assistantMessageId
499 : null,
500 }
501 : thread.latestTurn !== null &&
502 thread.latestTurn.state === "running" &&
503 settledTurnState !== null
504 ? {
505 ...thread.latestTurn,
506 state: settledTurnState,
507 // A running turn's completedAt can only hold a mid-turn
508 // placeholder checkpoint timestamp — the session leaving
509 // "running" is the authoritative turn end.
510 completedAt: event.payload.session.updatedAt,
511 }
512 : thread.latestTurn,
513 );
514​
515 return {
516 kind: "updated",
517 thread: {
518 ...thread,
519 session: event.payload.session,
520 latestTurn,
521 updatedAt: event.occurredAt,
522 },
523 };
524 }
525​
526 case "thread.session-stop-requested":
527 return thread.session === null
528 ? { kind: "unchanged" }
529 : {
530 kind: "updated",
531 thread: {
532 ...thread,
533 session: {
534 ...thread.session,
535 status: "stopped",
536 activeTurnId: null,
537 updatedAt: event.payload.createdAt,
538 },
539 updatedAt: event.occurredAt,
540 },
541 };
542​
543 // ── Proposed plans ──────────────────────────────────────────────
544 case "thread.proposed-plan-upserted": {
545 const proposedPlan = event.payload.proposedPlan;
546​
547 const proposedPlans = pipe(
548 thread.proposedPlans,
549 Arr.filter((entry) => entry.id !== proposedPlan.id),
550 Arr.append(proposedPlan),
551 Arr.sort(proposedPlanOrder),
552 );
553​
554 return {
555 kind: "updated",
556 thread: { ...thread, proposedPlans, updatedAt: event.occurredAt },
557 };
558 }
559​
560 // ── Checkpoints / turn diffs ────────────────────────────────────
561 case "thread.turn-diff-completed": {
562 const checkpoint: OrchestrationCheckpointSummary = {
563 turnId: event.payload.turnId,
564 checkpointTurnCount: event.payload.checkpointTurnCount,
565 checkpointRef: event.payload.checkpointRef,
566 status: event.payload.status,
567 files: event.payload.files,
568 assistantMessageId: event.payload.assistantMessageId,
569 completedAt: event.payload.completedAt,
570 };
571​
572 const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId);
573 // Don't overwrite a non-missing checkpoint with a missing one.
574 if (existing && existing.status !== "missing" && checkpoint.status === "missing") {
575 return { kind: "unchanged" };
576 }
577​
578 const checkpoints = pipe(
579 thread.checkpoints,
580 Arr.filter((entry) => entry.turnId !== checkpoint.turnId),
581 Arr.append(checkpoint),
582 Arr.sort(checkpointOrder),
583 );
584​
585 // Mid-turn diff updates produce placeholder checkpoints; record the
586 // checkpoint, but don't settle a turn its session is still running.
587 const diffTurnStillRunning =
588 thread.session?.status === "running" &&
589 thread.session.activeTurnId === event.payload.turnId;
590 const latestTurn =
591 !diffTurnStillRunning &&
592 (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
593 ? {
594 turnId: event.payload.turnId,
595 state:
596 thread.latestTurn?.state === "interrupted"
597 ? "interrupted"
598 : checkpointStatusToTurnState(event.payload.status),
599 requestedAt: thread.latestTurn?.requestedAt ?? event.payload.completedAt,
600 startedAt: thread.latestTurn?.startedAt ?? event.payload.completedAt,
601 completedAt: event.payload.completedAt,
602 assistantMessageId: event.payload.assistantMessageId,
603 }
604 : thread.latestTurn;
605​
606 return {
607 kind: "updated",
608 thread: { ...thread, checkpoints, latestTurn, updatedAt: event.occurredAt },
609 };
610 }
611​
612 // ── Revert ──────────────────────────────────────────────────────
613 case "thread.reverted": {
614 const checkpoints = pipe(
615 thread.checkpoints,
616 Arr.filter(
617 (entry) =>
618 entry.checkpointTurnCount !== undefined &&
619 entry.checkpointTurnCount <= event.payload.turnCount,
620 ),
621 Arr.sort(checkpointOrder),
622 );
623​
624 const retainedTurnIds = new Set(Arr.map(checkpoints, (entry) => entry.turnId));
625 const messages = retainMessagesAfterRevert(
626 thread.messages,
627 retainedTurnIds,
628 event.payload.turnCount,
629 );
630 const proposedPlans = pipe(
631 thread.proposedPlans,
632 Arr.filter((plan) => plan.turnId === null || retainedTurnIds.has(plan.turnId)),
633 );
634 const activities = pipe(
635 thread.activities,
636 Arr.filter((activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId)),
637 );
638 const latestCheckpoint = checkpoints.at(-1) ?? null;
639​
640 return {
641 kind: "updated",
642 thread: {
643 ...thread,
644 checkpoints,
645 messages,
646 proposedPlans,
647 activities,
648 latestTurn:
649 latestCheckpoint === null
650 ? null
651 : {
652 turnId: latestCheckpoint.turnId,
653 state: checkpointStatusToTurnState(
654 latestCheckpoint.status as "ready" | "missing" | "error",
655 ),
656 requestedAt: latestCheckpoint.completedAt,
657 startedAt: latestCheckpoint.completedAt,
658 completedAt: latestCheckpoint.completedAt,
659 assistantMessageId: latestCheckpoint.assistantMessageId ?? null,
660 },
661 updatedAt: event.occurredAt,
662 },
663 };
664 }
665​
666 // ── Activities ──────────────────────────────────────────────────
667 case "thread.activity-appended": {
668 const activity = event.payload.activity;
669 // A resolvable context-window update supersedes earlier resolvable ones
670 // for the same turn: consumers only read the latest value (walking the
671 // array backwards), and providers stream these updates continuously, so
672 // retaining the history grows the thread by thousands of rows over a
673 // long session. Mirrors the server-side snapshot rule in
674 // dropStaleContextWindowActivities; retention stays per turn so a
675 // thread.reverted that discards turns can still resolve a value from
676 // the turns that survive.
677 const supersedesContextWindow = isResolvableContextWindowActivity(activity);
678 // Live streams append in order: an unseen id sorting at/after the tail
679 // of a known-sorted array appends without re-filtering and re-sorting
680 // the whole history on every event. The id set moves forward to the new
681 // array; a superseded array falls back to the sorting path.
682 const ids = activityIdIndex.get(thread.activities);
683 const lastActivity = thread.activities.at(-1);
684 if (
685 !supersedesContextWindow &&
686 ids !== undefined &&
687 (lastActivity === undefined || activityOrder(lastActivity, activity) <= 0) &&
688 !ids.has(activity.id)
689 ) {
690 const activities = Arr.append(thread.activities, activity);
691 activityIdIndex.delete(thread.activities);
692 ids.add(activity.id);
693 activityIdIndex.set(activities, ids);
694 return {
695 kind: "updated",
696 thread: {
697 ...thread,
698 activities,
699 updatedAt: event.occurredAt,
700 },
701 };
702 }
703 const activities = pipe(
704 thread.activities,
705 Arr.filter(
706 (entry) =>
707 entry.id !== activity.id &&
708 !(
709 supersedesContextWindow &&
710 entry.turnId === activity.turnId &&
711 isResolvableContextWindowActivity(entry)
712 ),
713 ),
714 Arr.append(activity),
715 Arr.sort(activityOrder),
716 );
717 activityIdIndex.set(activities, new Set(activities.map((entry) => entry.id)));
718​
719 return {
720 kind: "updated",
721 thread: { ...thread, activities, updatedAt: event.occurredAt },
722 };
723 }
724​
725 // ── Events that don't mutate thread state directly ──────────────
726 case "thread.approval-response-requested":
727 case "thread.user-input-response-requested":
728 case "thread.checkpoint-revert-requested":
729 return { kind: "unchanged" };
730 }
731​
732 // Forward-compatible: ignore unrecognized event types.
733 return { kind: "unchanged" };
735​
736// ── Helpers ──────────────────────────────────────────────────────────
737​
738/**
739 * Turn state to settle a still-running latest turn with when its session
740 * leaves the "running" status, or null while the session is (re)starting or
741 * running and the turn must stay unsettled.
742 */
743function settledTurnStateForSessionStatus(
744 status: OrchestrationSession["status"],
745): "completed" | "interrupted" | "error" | null {
746 switch (status) {
747 case "idle":
748 case "ready":
749 return "completed";
750 case "error":
751 return "error";
752 case "interrupted":
753 case "stopped":
754 return "interrupted";
755 case "starting":
756 case "running":
757 return null;
758 }
760​
761function checkpointStatusToTurnState(
762 status: "ready" | "missing" | "error",
763): OrchestrationLatestTurn["state"] {
764 switch (status) {
765 case "ready":
766 return "completed";
767 case "error":
768 return "error";
769 case "missing":
770 return "completed";
771 }
773​
774/**
775 * Returns `previous` when `next` matches it field for field, otherwise `next`.
776 * Streaming cases recompute the latest turn on every delta, and keeping the
777 * old reference lets selectors and memos keyed on `latestTurn` skip work.
778 */
779function reuseLatestTurn(
780 previous: OrchestrationLatestTurn | null,
781 next: OrchestrationLatestTurn | null,
782): OrchestrationLatestTurn | null {
783 if (previous === null || next === null) {
784 return next;
785 }
786 return previous.turnId === next.turnId &&
787 previous.state === next.state &&
788 previous.requestedAt === next.requestedAt &&
789 previous.startedAt === next.startedAt &&
790 previous.completedAt === next.completedAt &&
791 previous.assistantMessageId === next.assistantMessageId &&
792 previous.sourceProposedPlan?.threadId === next.sourceProposedPlan?.threadId &&
793 previous.sourceProposedPlan?.planId === next.sourceProposedPlan?.planId
794 ? previous
795 : next;
797​
798/**
799 * Points the checkpoint for `turnId` at `messageId`. Returns the input array
800 * untouched when no checkpoint needs rebinding, so streaming deltas for an
801 * already-bound message do not allocate a new `checkpoints` reference.
802 */
803function rebindCheckpointAssistantMessage(
804 checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
805 turnId: TurnId,
806 messageId: MessageId,
807): ReadonlyArray<OrchestrationCheckpointSummary> {
808 const needsRebind = checkpoints.some(
809 (entry) => entry.turnId === turnId && entry.assistantMessageId !== messageId,
810 );
811 if (!needsRebind) {
812 return checkpoints;
813 }
814 return Arr.map(checkpoints, (entry) =>
815 entry.turnId === turnId ? { ...entry, assistantMessageId: messageId } : entry,
816 );
818​
819function retainMessagesAfterRevert(
820 messages: ReadonlyArray<OrchestrationMessage>,
821 retainedTurnIds: ReadonlySet<string>,
822 turnCount: number,
823): OrchestrationMessage[] {
824 const retainedMessageIds = new Set<string>();
825 for (const message of messages) {
826 if (message.role === "system" || isImportedAgentSessionMessageId(message.id)) {
827 retainedMessageIds.add(message.id);
828 } else if (message.turnId !== null && retainedTurnIds.has(message.turnId)) {
829 retainedMessageIds.add(message.id);
830 }
831 }
832​
833 for (const role of ["user", "assistant"] as const) {
834 const retainedCount = messages.filter(
835 (message) =>
836 message.role === role &&
837 !isImportedAgentSessionMessageId(message.id) &&
838 retainedMessageIds.has(message.id),
839 ).length;
840 const missingCount = Math.max(0, turnCount - retainedCount);
841 const fallbackMessages = messages
842 .filter(
843 (message) =>
844 message.role === role &&
845 !retainedMessageIds.has(message.id) &&
846 (message.turnId === null || retainedTurnIds.has(message.turnId)),
847 )
848 // `.sort()`, not `.toSorted()`: `.filter()` above already returned a fresh array, and
849 // this is shared with mobile, which runs on Hermes and has no ES2023 array methods.
850 .sort(
851 (left, right) =>
852 compareDateTimeStrings(left.createdAt, right.createdAt) ||
853 left.id.localeCompare(right.id),
854 )
855 .slice(0, missingCount);
856 for (const message of fallbackMessages) {
857 retainedMessageIds.add(message.id);
858 }
859 }
860​
861 return Arr.filter(messages, (message) => retainedMessageIds.has(message.id));
863​
864export function applyThreadDetailEvent(
865 thread: OrchestrationThread,
866 event: OrchestrationEvent,
867): ThreadDetailReducerResult {
868 const result = applyThreadDetailEventBase(thread, event);
869 const update = pendingProviderTurnUpdate(event);
870 if (
871 update === undefined ||
872 result.kind === "deleted" ||
873 (update === null && thread.pendingProviderTurn == null)
874 )
875 return result;
876 return {
877 kind: "updated",
878 thread: {
879 ...(result.kind === "updated" ? result.thread : thread),
880 pendingProviderTurn: update,
881 },
882 };