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

threadReducer.ts

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