Open History to see the last commit
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 TurnId,
14} from "@t3tools/contracts";
15
16export type ThreadDetailReducerResult =
17 | { readonly kind: "updated"; readonly thread: OrchestrationThread }
18 | { readonly kind: "deleted" }
19 | { readonly kind: "unchanged" };
20
21const proposedPlanOrder = O.combine<OrchestrationThread["proposedPlans"][number]>(
22 O.mapInput(O.String, (p) => p.createdAt),
23 O.mapInput(O.String, (p) => p.id),
24);
25
26const checkpointOrder = O.mapInput(
27 O.Number,
28 (cp: OrchestrationThread["checkpoints"][number]) =>
29 cp.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER,
30);
31
32const activityOrder = O.combineAll<OrchestrationThreadActivity>([
33 O.mapInput(O.Number, (a) => a.sequence ?? Number.MAX_SAFE_INTEGER),
34 O.mapInput(O.String, (a) => a.createdAt),
35 O.mapInput(O.String, (a) => a.id),
36]);
37
38/**
39 * Matches the validity rule in `deriveLatestContextWindowSnapshot` (and the
40 * server's snapshot-side `dropStaleContextWindowActivities`): rows without a
41 * finite, non-negative `usedTokens` are skipped during the consumer's backward
42 * walk, so they must not replace an earlier resolvable row here.
43 */
44function isResolvableContextWindowActivity(activity: OrchestrationThreadActivity): boolean {
45 if (activity.kind !== "context-window.updated") {
46 return false;
47 }
48 const payload =
49 activity.payload && typeof activity.payload === "object"
50 ? (activity.payload as Record<string, unknown>)
51 : null;
52 const usedTokens = payload?.usedTokens;
53 return typeof usedTokens === "number" && Number.isFinite(usedTokens) && usedTokens >= 0;
54}
55
56/**
57 * Apply a single orchestration event to an `OrchestrationThread`, returning
58 * the updated thread, a deletion signal, or an "unchanged" marker when the
59 * event doesn't affect this thread.
60 *
61 * This is a pure reducer operating on contract types. UI-specific mapping
62 * (e.g. resolving attachment preview URLs, normalising model slugs, adding
63 * scoped fields like `environmentId`) is the caller's responsibility.
64 */
65export function applyThreadDetailEvent(
66 thread: OrchestrationThread,
67 event: OrchestrationEvent,
68): ThreadDetailReducerResult {
69 switch (event.type) {
70 // ── Project events (irrelevant to thread detail) ────────────────
71 case "project.created":
72 case "project.meta-updated":
73 case "project.deleted":
74 return { kind: "unchanged" };
75
76 // ── Thread lifecycle ────────────────────────────────────────────
77 case "thread.created":
78 return {
79 kind: "updated",
80 thread: {
81 id: event.payload.threadId,
82 projectId: event.payload.projectId,
83 title: event.payload.title,
84 modelSelection: event.payload.modelSelection,
85 runtimeMode: event.payload.runtimeMode,
86 interactionMode: event.payload.interactionMode,
87 branch: event.payload.branch,
88 worktreePath: event.payload.worktreePath,
89 latestTurn: null,
90 createdAt: event.payload.createdAt,
91 updatedAt: event.payload.updatedAt,
92 archivedAt: null,
93 settledOverride: null,
94 settledAt: null,
95 unsettledAt: null,
96 snoozedUntil: null,
97 snoozedAt: null,
98 deletedAt: null,
99 messages: [],
100 proposedPlans: [],
101 activities: [],
102 checkpoints: [],
103 session: null,
104 },
105 };
106
107 case "thread.deleted":
108 return { kind: "deleted" };
109
110 case "thread.archived":
111 return {
112 kind: "updated",
113 thread: {
114 ...thread,
115 archivedAt: event.payload.archivedAt,
116 titleRegeneration: null,
117 updatedAt: event.payload.updatedAt,
118 },
119 };
120
121 case "thread.unarchived":
122 return {
123 kind: "updated",
124 thread: { ...thread, archivedAt: null, updatedAt: event.payload.updatedAt },
125 };
126
127 case "thread.settled":
128 return {
129 kind: "updated",
130 thread: {
131 ...thread,
132 settledOverride: "settled",
133 settledAt: event.payload.settledAt,
134 unsettledAt: null,
135 updatedAt: event.payload.updatedAt,
136 },
137 };
138
139 case "thread.unsettled":
140 return {
141 kind: "updated",
142 thread: {
143 ...thread,
144 settledOverride: event.payload.reason === "user" ? "active" : null,
145 settledAt: null,
146 // A thread already pinned active keeps its re-entry stamp: the
147 // activity reset that clears the pin must not reorder the list.
148 unsettledAt:
149 thread.settledOverride === "active"
150 ? (thread.unsettledAt ?? null)
151 : event.payload.updatedAt,
152 updatedAt: event.payload.updatedAt,
153 },
154 };
155
156 case "thread.snoozed":
157 return {
158 kind: "updated",
159 thread: {
160 ...thread,
161 snoozedUntil: event.payload.snoozedUntil,
162 snoozedAt: event.payload.snoozedAt,
163 updatedAt: event.payload.updatedAt,
164 },
165 };
166
167 case "thread.unsnoozed":
168 return {
169 kind: "updated",
170 thread: {
171 ...thread,
172 snoozedUntil: null,
173 snoozedAt: null,
174 updatedAt: event.payload.updatedAt,
175 },
176 };
177
178 case "thread.pinned":
179 return {
180 kind: "updated",
181 thread: {
182 ...thread,
183 pinnedAt: event.payload.pinnedAt,
184 ...(event.payload.pinOrderKey !== undefined
185 ? { pinOrderKey: event.payload.pinOrderKey }
186 : {}),
187 updatedAt: event.payload.updatedAt,
188 },
189 };
190
191 case "thread.unpinned":
192 return {
193 kind: "updated",
194 thread: {
195 ...thread,
196 pinnedAt: null,
197 pinOrderKey: null,
198 updatedAt: event.payload.updatedAt,
199 },
200 };
201
202 case "thread.pin-reordered":
203 return {
204 kind: "updated",
205 thread: {
206 ...thread,
207 pinOrderKey: event.payload.orderKey,
208 updatedAt: event.payload.updatedAt,
209 },
210 };
211
212 // ── Thread metadata ─────────────────────────────────────────────
213 case "thread.meta-updated":
214 return {
215 kind: "updated",
216 thread: {
217 ...thread,
218 ...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
219 ...(event.payload.titleRegeneration !== undefined
220 ? { titleRegeneration: event.payload.titleRegeneration }
221 : {}),
222 ...(event.payload.modelSelection !== undefined
223 ? { modelSelection: event.payload.modelSelection }
224 : {}),
225 ...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
226 ...(event.payload.worktreePath !== undefined
227 ? { worktreePath: event.payload.worktreePath }
228 : {}),
229 ...(event.payload.linkedPullRequest !== undefined
230 ? { linkedPullRequest: event.payload.linkedPullRequest }
231 : {}),
232 updatedAt: event.payload.updatedAt,
233 },
234 };
235
236 case "thread.runtime-mode-set":
237 return {
238 kind: "updated",
239 thread: {
240 ...thread,
241 runtimeMode: event.payload.runtimeMode,
242 updatedAt: event.payload.updatedAt,
243 },
244 };
245
246 case "thread.interaction-mode-set":
247 return {
248 kind: "updated",
249 thread: {
250 ...thread,
251 interactionMode: event.payload.interactionMode,
252 updatedAt: event.payload.updatedAt,
253 },
254 };
255
256 // ── Turn lifecycle ──────────────────────────────────────────────
257 case "thread.turn-start-requested":
258 return {
259 kind: "updated",
260 thread: {
261 ...thread,
262 ...(event.payload.modelSelection !== undefined
263 ? { modelSelection: event.payload.modelSelection }
264 : {}),
265 runtimeMode: event.payload.runtimeMode,
266 interactionMode: event.payload.interactionMode,
267 updatedAt: event.occurredAt,
268 },
269 };
270
271 case "thread.turn-interrupt-requested": {
272 if (event.payload.turnId === undefined) {
273 return { kind: "unchanged" };
274 }
275 const latestTurn = thread.latestTurn;
276 if (latestTurn === null || latestTurn.turnId !== event.payload.turnId) {
277 return { kind: "unchanged" };
278 }
279 return {
280 kind: "updated",
281 thread: {
282 ...thread,
283 latestTurn: {
284 ...latestTurn,
285 state: "interrupted",
286 startedAt: latestTurn.startedAt ?? event.payload.createdAt,
287 completedAt: latestTurn.completedAt ?? event.payload.createdAt,
288 },
289 updatedAt: event.occurredAt,
290 },
291 };
292 }
293
294 // ── Messages ────────────────────────────────────────────────────
295 case "thread.message-sent": {
296 const message: OrchestrationMessage = {
297 id: event.payload.messageId,
298 role: event.payload.role,
299 text: event.payload.text,
300 ...(event.payload.attachments !== undefined
301 ? { attachments: event.payload.attachments }
302 : {}),
303 turnId: event.payload.turnId,
304 streaming: event.payload.streaming,
305 createdAt: event.payload.createdAt,
306 updatedAt: event.payload.updatedAt,
307 };
308
309 const existingMessage = thread.messages.find((entry) => entry.id === message.id);
310 const messages = existingMessage
311 ? Arr.map(thread.messages, (entry) =>
312 entry.id !== message.id
313 ? entry
314 : {
315 ...entry,
316 text: message.streaming
317 ? `${entry.text}${message.text}`
318 : message.text.length > 0
319 ? message.text
320 : entry.text,
321 streaming: message.streaming,
322 ...(message.turnId !== undefined ? { turnId: message.turnId } : {}),
323 ...(message.streaming ? {} : { updatedAt: message.updatedAt }),
324 ...(message.attachments !== undefined
325 ? { attachments: message.attachments }
326 : {}),
327 },
328 )
329 : Arr.append(thread.messages, message);
330 // Update latestTurn for assistant messages bound to a turn. A completed
331 // assistant message only settles the turn once the session is no longer
332 // running it — providers may emit several assistant messages per turn
333 // (commentary between tool calls), and the turn must stay unsettled
334 // until the provider reports turn end.
335 const turnStillRunning =
336 event.payload.turnId !== null &&
337 thread.session?.status === "running" &&
338 thread.session.activeTurnId === event.payload.turnId;
339 const settlesTurn = !event.payload.streaming && !turnStillRunning;
340 const latestTurn: OrchestrationThread["latestTurn"] =
341 event.payload.role === "assistant" &&
342 event.payload.turnId !== null &&
343 (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
344 ? {
345 turnId: event.payload.turnId,
346 state: settlesTurn
347 ? thread.latestTurn?.state === "interrupted"
348 ? "interrupted"
349 : thread.latestTurn?.state === "error"
350 ? "error"
351 : "completed"
352 : "running",
353 requestedAt:
354 thread.latestTurn?.turnId === event.payload.turnId
355 ? thread.latestTurn.requestedAt
356 : event.payload.createdAt,
357 startedAt:
358 thread.latestTurn?.turnId === event.payload.turnId
359 ? (thread.latestTurn.startedAt ?? event.payload.createdAt)
360 : event.payload.createdAt,
361 completedAt: settlesTurn
362 ? event.payload.updatedAt
363 : thread.latestTurn?.turnId === event.payload.turnId
364 ? (thread.latestTurn.completedAt ?? null)
365 : null,
366 assistantMessageId: event.payload.messageId,
367 }
368 : thread.latestTurn;
369
370 // Rebind checkpoint assistant message IDs for assistant messages.
371 const checkpoints =
372 event.payload.role === "assistant" && event.payload.turnId !== null
373 ? rebindCheckpointAssistantMessage(
374 thread.checkpoints,
375 event.payload.turnId,
376 event.payload.messageId,
377 )
378 : thread.checkpoints;
379
380 return {
381 kind: "updated",
382 thread: {
383 ...thread,
384 messages,
385 checkpoints,
386 latestTurn,
387 updatedAt: event.occurredAt,
388 },
389 };
390 }
391
392 // ── Session ─────────────────────────────────────────────────────
393 case "thread.session-set": {
394 // Leaving the "running" session status is the turn-end signal: settle a
395 // still-running latest turn so its duration reflects the whole turn.
396 const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
397 const latestTurn: OrchestrationLatestTurn | null =
398 event.payload.session.status === "running" && event.payload.session.activeTurnId !== null
399 ? {
400 turnId: event.payload.session.activeTurnId,
401 state: "running",
402 requestedAt:
403 thread.latestTurn?.turnId === event.payload.session.activeTurnId
404 ? thread.latestTurn.requestedAt
405 : event.payload.session.updatedAt,
406 startedAt:
407 thread.latestTurn?.turnId === event.payload.session.activeTurnId
408 ? (thread.latestTurn.startedAt ?? event.payload.session.updatedAt)
409 : event.payload.session.updatedAt,
410 completedAt: null,
411 assistantMessageId:
412 thread.latestTurn?.turnId === event.payload.session.activeTurnId
413 ? thread.latestTurn.assistantMessageId
414 : null,
415 }
416 : thread.latestTurn !== null &&
417 thread.latestTurn.state === "running" &&
418 settledTurnState !== null
419 ? {
420 ...thread.latestTurn,
421 state: settledTurnState,
422 // A running turn's completedAt can only hold a mid-turn
423 // placeholder checkpoint timestamp — the session leaving
424 // "running" is the authoritative turn end.
425 completedAt: event.payload.session.updatedAt,
426 }
427 : thread.latestTurn;
428
429 return {
430 kind: "updated",
431 thread: {
432 ...thread,
433 session: event.payload.session,
434 latestTurn,
435 updatedAt: event.occurredAt,
436 },
437 };
438 }
439
440 case "thread.session-stop-requested":
441 return thread.session === null
442 ? { kind: "unchanged" }
443 : {
444 kind: "updated",
445 thread: {
446 ...thread,
447 session: {
448 ...thread.session,
449 status: "stopped",
450 activeTurnId: null,
451 updatedAt: event.payload.createdAt,
452 },
453 updatedAt: event.occurredAt,
454 },
455 };
456
457 // ── Proposed plans ──────────────────────────────────────────────
458 case "thread.proposed-plan-upserted": {
459 const proposedPlan = event.payload.proposedPlan;
460
461 const proposedPlans = pipe(
462 thread.proposedPlans,
463 Arr.filter((entry) => entry.id !== proposedPlan.id),
464 Arr.append(proposedPlan),
465 Arr.sort(proposedPlanOrder),
466 );
467
468 return {
469 kind: "updated",
470 thread: { ...thread, proposedPlans, updatedAt: event.occurredAt },
471 };
472 }
473
474 // ── Checkpoints / turn diffs ────────────────────────────────────
475 case "thread.turn-diff-completed": {
476 const checkpoint: OrchestrationCheckpointSummary = {
477 turnId: event.payload.turnId,
478 checkpointTurnCount: event.payload.checkpointTurnCount,
479 checkpointRef: event.payload.checkpointRef,
480 status: event.payload.status,
481 files: event.payload.files,
482 assistantMessageId: event.payload.assistantMessageId,
483 completedAt: event.payload.completedAt,
484 };
485
486 const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId);
487 // Don't overwrite a non-missing checkpoint with a missing one.
488 if (existing && existing.status !== "missing" && checkpoint.status === "missing") {
489 return { kind: "unchanged" };
490 }
491
492 const checkpoints = pipe(
493 thread.checkpoints,
494 Arr.filter((entry) => entry.turnId !== checkpoint.turnId),
495 Arr.append(checkpoint),
496 Arr.sort(checkpointOrder),
497 );
498
499 // Mid-turn diff updates produce placeholder checkpoints; record the
500 // checkpoint, but don't settle a turn its session is still running.
501 const diffTurnStillRunning =
502 thread.session?.status === "running" &&
503 thread.session.activeTurnId === event.payload.turnId;
504 const latestTurn =
505 !diffTurnStillRunning &&
506 (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
507 ? {
508 turnId: event.payload.turnId,
509 state: checkpointStatusToTurnState(event.payload.status),
510 requestedAt: thread.latestTurn?.requestedAt ?? event.payload.completedAt,
511 startedAt: thread.latestTurn?.startedAt ?? event.payload.completedAt,
512 completedAt: event.payload.completedAt,
513 assistantMessageId: event.payload.assistantMessageId,
514 }
515 : thread.latestTurn;
516
517 return {
518 kind: "updated",
519 thread: { ...thread, checkpoints, latestTurn, updatedAt: event.occurredAt },
520 };
521 }
522
523 // ── Revert ──────────────────────────────────────────────────────
524 case "thread.reverted": {
525 const checkpoints = pipe(
526 thread.checkpoints,
527 Arr.filter(
528 (entry) =>
529 entry.checkpointTurnCount !== undefined &&
530 entry.checkpointTurnCount <= event.payload.turnCount,
531 ),
532 Arr.sort(checkpointOrder),
533 );
534
535 const retainedTurnIds = new Set(Arr.map(checkpoints, (entry) => entry.turnId));
536 const messages = retainMessagesAfterRevert(thread.messages, retainedTurnIds);
537 const proposedPlans = pipe(
538 thread.proposedPlans,
539 Arr.filter((plan) => plan.turnId === null || retainedTurnIds.has(plan.turnId)),
540 );
541 const activities = pipe(
542 thread.activities,
543 Arr.filter((activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId)),
544 );
545 const latestCheckpoint = checkpoints.at(-1) ?? null;
546
547 return {
548 kind: "updated",
549 thread: {
550 ...thread,
551 checkpoints,
552 messages,
553 proposedPlans,
554 activities,
555 latestTurn:
556 latestCheckpoint === null
557 ? null
558 : {
559 turnId: latestCheckpoint.turnId,
560 state: checkpointStatusToTurnState(
561 latestCheckpoint.status as "ready" | "missing" | "error",
562 ),
563 requestedAt: latestCheckpoint.completedAt,
564 startedAt: latestCheckpoint.completedAt,
565 completedAt: latestCheckpoint.completedAt,
566 assistantMessageId: latestCheckpoint.assistantMessageId ?? null,
567 },
568 updatedAt: event.occurredAt,
569 },
570 };
571 }
572
573 // ── Activities ──────────────────────────────────────────────────
574 case "thread.activity-appended": {
575 const activity = event.payload.activity;
576 // A resolvable context-window update supersedes earlier resolvable ones
577 // for the same turn: consumers only read the latest value (walking the
578 // array backwards), and providers stream these updates continuously, so
579 // retaining the history grows the thread by thousands of rows over a
580 // long session. Mirrors the server-side snapshot rule in
581 // dropStaleContextWindowActivities; retention stays per turn so a
582 // thread.reverted that discards turns can still resolve a value from
583 // the turns that survive.
584 const supersedesContextWindow = isResolvableContextWindowActivity(activity);
585 const activities = pipe(
586 thread.activities,
587 Arr.filter(
588 (entry) =>
589 entry.id !== activity.id &&
590 !(
591 supersedesContextWindow &&
592 entry.turnId === activity.turnId &&
593 isResolvableContextWindowActivity(entry)
594 ),
595 ),
596 Arr.append(activity),
597 Arr.sort(activityOrder),
598 );
599
600 return {
601 kind: "updated",
602 thread: { ...thread, activities, updatedAt: event.occurredAt },
603 };
604 }
605
606 // ── Events that don't mutate thread state directly ──────────────
607 case "thread.approval-response-requested":
608 case "thread.user-input-response-requested":
609 case "thread.checkpoint-revert-requested":
610 return { kind: "unchanged" };
611 }
612
613 // Forward-compatible: ignore unrecognized event types.
614 return { kind: "unchanged" };
615}
616
617// ── Helpers ──────────────────────────────────────────────────────────
618
619/**
620 * Turn state to settle a still-running latest turn with when its session
621 * leaves the "running" status, or null while the session is (re)starting or
622 * running and the turn must stay unsettled.
623 */
624function settledTurnStateForSessionStatus(
625 status: OrchestrationSession["status"],
626): "completed" | "interrupted" | "error" | null {
627 switch (status) {
628 case "idle":
629 case "ready":
630 return "completed";
631 case "error":
632 return "error";
633 case "interrupted":
634 case "stopped":
635 return "interrupted";
636 case "starting":
637 case "running":
638 return null;
639 }
640}
641
642function checkpointStatusToTurnState(
643 status: "ready" | "missing" | "error",
644): OrchestrationLatestTurn["state"] {
645 switch (status) {
646 case "ready":
647 return "completed";
648 case "error":
649 return "error";
650 case "missing":
651 return "completed";
652 }
653}
654
655function rebindCheckpointAssistantMessage(
656 checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
657 turnId: TurnId,
658 messageId: MessageId,
659): OrchestrationCheckpointSummary[] {
660 return Arr.map(checkpoints, (entry) =>
661 entry.turnId === turnId ? { ...entry, assistantMessageId: messageId } : entry,
662 );
663}
664
665function retainMessagesAfterRevert(
666 messages: ReadonlyArray<OrchestrationMessage>,
667 retainedTurnIds: ReadonlySet<string>,
668): OrchestrationMessage[] {
669 // Keep messages that belong to a retained turn, plus system messages and
670 // messages without a turn binding (pre-turn-0 user messages).
671 return Arr.filter(messages, (message) => {
672 if (message.role === "system") {
673 return true;
674 }
675 if (message.turnId === null) {
676 return true;
677 }
678 return retainedTurnIds.has(message.turnId);
679 });
680}