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

threadReducer.ts

675 lines23.6 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-interrupt-requested": {
261 if (event.payload.turnId === undefined) {
262 return { kind: "unchanged" };
263 }
264 const latestTurn = thread.latestTurn;
265 if (latestTurn === null || latestTurn.turnId !== event.payload.turnId) {
266 return { kind: "unchanged" };
267 }
268 return {
269 kind: "updated",
270 thread: {
271 ...thread,
272 latestTurn: {
273 ...latestTurn,
274 state: "interrupted",
275 startedAt: latestTurn.startedAt ?? event.payload.createdAt,
276 completedAt: latestTurn.completedAt ?? event.payload.createdAt,
277 },
278 updatedAt: event.occurredAt,
279 },
280 };
281 }
282​
283 // ── Messages ────────────────────────────────────────────────────
284 case "thread.message-sent": {
285 const message: OrchestrationMessage = {
286 id: event.payload.messageId,
287 role: event.payload.role,
288 text: event.payload.text,
289 ...(event.payload.actualModel !== undefined
290 ? { actualModel: event.payload.actualModel }
291 : {}),
292 ...(event.payload.attachments !== undefined
293 ? { attachments: event.payload.attachments }
294 : {}),
295 turnId: event.payload.turnId,
296 streaming: event.payload.streaming,
297 createdAt: event.payload.createdAt,
298 updatedAt: event.payload.updatedAt,
299 };
300​
301 const existingMessage = thread.messages.find((entry) => entry.id === message.id);
302 const messages = existingMessage
303 ? Arr.map(thread.messages, (entry) =>
304 entry.id !== message.id
305 ? entry
306 : {
307 ...entry,
308 text: message.streaming
309 ? `${entry.text}${message.text}`
310 : message.text.length > 0
311 ? message.text
312 : entry.text,
313 streaming: message.streaming,
314 ...(message.turnId !== undefined ? { turnId: message.turnId } : {}),
315 ...(message.actualModel !== undefined
316 ? { actualModel: message.actualModel }
317 : {}),
318 ...(message.streaming ? {} : { updatedAt: message.updatedAt }),
319 ...(message.attachments !== undefined
320 ? { attachments: message.attachments }
321 : {}),
322 },
323 )
324 : Arr.append(thread.messages, message);
325 // Update latestTurn for assistant messages bound to a turn. A completed
326 // assistant message only settles the turn once the session is no longer
327 // running it — providers may emit several assistant messages per turn
328 // (commentary between tool calls), and the turn must stay unsettled
329 // until the provider reports turn end.
330 const turnStillRunning =
331 event.payload.turnId !== null &&
332 thread.session?.status === "running" &&
333 thread.session.activeTurnId === event.payload.turnId;
334 const settlesTurn = !event.payload.streaming && !turnStillRunning;
335 const latestTurn: OrchestrationThread["latestTurn"] =
336 event.payload.role === "assistant" &&
337 event.payload.turnId !== null &&
338 (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
339 ? {
340 turnId: event.payload.turnId,
341 state: settlesTurn
342 ? thread.latestTurn?.state === "interrupted"
343 ? "interrupted"
344 : thread.latestTurn?.state === "error"
345 ? "error"
346 : "completed"
347 : "running",
348 requestedAt:
349 thread.latestTurn?.turnId === event.payload.turnId
350 ? thread.latestTurn.requestedAt
351 : event.payload.createdAt,
352 startedAt:
353 thread.latestTurn?.turnId === event.payload.turnId
354 ? (thread.latestTurn.startedAt ?? event.payload.createdAt)
355 : event.payload.createdAt,
356 completedAt: settlesTurn
357 ? event.payload.updatedAt
358 : thread.latestTurn?.turnId === event.payload.turnId
359 ? (thread.latestTurn.completedAt ?? null)
360 : null,
361 assistantMessageId: event.payload.messageId,
362 }
363 : thread.latestTurn;
364​
365 // Rebind checkpoint assistant message IDs for assistant messages.
366 const checkpoints =
367 event.payload.role === "assistant" && event.payload.turnId !== null
368 ? rebindCheckpointAssistantMessage(
369 thread.checkpoints,
370 event.payload.turnId,
371 event.payload.messageId,
372 )
373 : thread.checkpoints;
374​
375 return {
376 kind: "updated",
377 thread: {
378 ...thread,
379 messages,
380 checkpoints,
381 latestTurn,
382 updatedAt: event.occurredAt,
383 },
384 };
385 }
386​
387 // ── Session ─────────────────────────────────────────────────────
388 case "thread.session-set": {
389 // Leaving the "running" session status is the turn-end signal: settle a
390 // still-running latest turn so its duration reflects the whole turn.
391 const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
392 const latestTurn: OrchestrationLatestTurn | null =
393 event.payload.session.status === "running" && event.payload.session.activeTurnId !== null
394 ? {
395 turnId: event.payload.session.activeTurnId,
396 state: "running",
397 requestedAt:
398 thread.latestTurn?.turnId === event.payload.session.activeTurnId
399 ? thread.latestTurn.requestedAt
400 : event.payload.session.updatedAt,
401 startedAt:
402 thread.latestTurn?.turnId === event.payload.session.activeTurnId
403 ? (thread.latestTurn.startedAt ?? event.payload.session.updatedAt)
404 : event.payload.session.updatedAt,
405 completedAt: null,
406 assistantMessageId:
407 thread.latestTurn?.turnId === event.payload.session.activeTurnId
408 ? thread.latestTurn.assistantMessageId
409 : null,
410 }
411 : thread.latestTurn !== null &&
412 thread.latestTurn.state === "running" &&
413 settledTurnState !== null
414 ? {
415 ...thread.latestTurn,
416 state: settledTurnState,
417 // A running turn's completedAt can only hold a mid-turn
418 // placeholder checkpoint timestamp — the session leaving
419 // "running" is the authoritative turn end.
420 completedAt: event.payload.session.updatedAt,
421 }
422 : thread.latestTurn;
423​
424 return {
425 kind: "updated",
426 thread: {
427 ...thread,
428 session: event.payload.session,
429 latestTurn,
430 updatedAt: event.occurredAt,
431 },
432 };
433 }
434​
435 case "thread.session-stop-requested":
436 return thread.session === null
437 ? { kind: "unchanged" }
438 : {
439 kind: "updated",
440 thread: {
441 ...thread,
442 session: {
443 ...thread.session,
444 status: "stopped",
445 activeTurnId: null,
446 updatedAt: event.payload.createdAt,
447 },
448 updatedAt: event.occurredAt,
449 },
450 };
451​
452 // ── Proposed plans ──────────────────────────────────────────────
453 case "thread.proposed-plan-upserted": {
454 const proposedPlan = event.payload.proposedPlan;
455​
456 const proposedPlans = pipe(
457 thread.proposedPlans,
458 Arr.filter((entry) => entry.id !== proposedPlan.id),
459 Arr.append(proposedPlan),
460 Arr.sort(proposedPlanOrder),
461 );
462​
463 return {
464 kind: "updated",
465 thread: { ...thread, proposedPlans, updatedAt: event.occurredAt },
466 };
467 }
468​
469 // ── Checkpoints / turn diffs ────────────────────────────────────
470 case "thread.turn-diff-completed": {
471 const checkpoint: OrchestrationCheckpointSummary = {
472 turnId: event.payload.turnId,
473 checkpointTurnCount: event.payload.checkpointTurnCount,
474 checkpointRef: event.payload.checkpointRef,
475 status: event.payload.status,
476 files: event.payload.files,
477 assistantMessageId: event.payload.assistantMessageId,
478 completedAt: event.payload.completedAt,
479 };
480​
481 const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId);
482 // Don't overwrite a non-missing checkpoint with a missing one.
483 if (existing && existing.status !== "missing" && checkpoint.status === "missing") {
484 return { kind: "unchanged" };
485 }
486​
487 const checkpoints = pipe(
488 thread.checkpoints,
489 Arr.filter((entry) => entry.turnId !== checkpoint.turnId),
490 Arr.append(checkpoint),
491 Arr.sort(checkpointOrder),
492 );
493​
494 // Mid-turn diff updates produce placeholder checkpoints; record the
495 // checkpoint, but don't settle a turn its session is still running.
496 const diffTurnStillRunning =
497 thread.session?.status === "running" &&
498 thread.session.activeTurnId === event.payload.turnId;
499 const latestTurn =
500 !diffTurnStillRunning &&
501 (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
502 ? {
503 turnId: event.payload.turnId,
504 state: checkpointStatusToTurnState(event.payload.status),
505 requestedAt: thread.latestTurn?.requestedAt ?? event.payload.completedAt,
506 startedAt: thread.latestTurn?.startedAt ?? event.payload.completedAt,
507 completedAt: event.payload.completedAt,
508 assistantMessageId: event.payload.assistantMessageId,
509 }
510 : thread.latestTurn;
511​
512 return {
513 kind: "updated",
514 thread: { ...thread, checkpoints, latestTurn, updatedAt: event.occurredAt },
515 };
516 }
517​
518 // ── Revert ──────────────────────────────────────────────────────
519 case "thread.reverted": {
520 const checkpoints = pipe(
521 thread.checkpoints,
522 Arr.filter(
523 (entry) =>
524 entry.checkpointTurnCount !== undefined &&
525 entry.checkpointTurnCount <= event.payload.turnCount,
526 ),
527 Arr.sort(checkpointOrder),
528 );
529​
530 const retainedTurnIds = new Set(Arr.map(checkpoints, (entry) => entry.turnId));
531 const messages = retainMessagesAfterRevert(thread.messages, retainedTurnIds);
532 const proposedPlans = pipe(
533 thread.proposedPlans,
534 Arr.filter((plan) => plan.turnId === null || retainedTurnIds.has(plan.turnId)),
535 );
536 const activities = pipe(
537 thread.activities,
538 Arr.filter((activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId)),
539 );
540 const latestCheckpoint = checkpoints.at(-1) ?? null;
541​
542 return {
543 kind: "updated",
544 thread: {
545 ...thread,
546 checkpoints,
547 messages,
548 proposedPlans,
549 activities,
550 latestTurn:
551 latestCheckpoint === null
552 ? null
553 : {
554 turnId: latestCheckpoint.turnId,
555 state: checkpointStatusToTurnState(
556 latestCheckpoint.status as "ready" | "missing" | "error",
557 ),
558 requestedAt: latestCheckpoint.completedAt,
559 startedAt: latestCheckpoint.completedAt,
560 completedAt: latestCheckpoint.completedAt,
561 assistantMessageId: latestCheckpoint.assistantMessageId ?? null,
562 },
563 updatedAt: event.occurredAt,
564 },
565 };
566 }
567​
568 // ── Activities ──────────────────────────────────────────────────
569 case "thread.activity-appended": {
570 const activity = event.payload.activity;
571 // A resolvable context-window update supersedes earlier resolvable ones
572 // for the same turn: consumers only read the latest value (walking the
573 // array backwards), and providers stream these updates continuously, so
574 // retaining the history grows the thread by thousands of rows over a
575 // long session. Mirrors the server-side snapshot rule in
576 // dropStaleContextWindowActivities; retention stays per turn so a
577 // thread.reverted that discards turns can still resolve a value from
578 // the turns that survive.
579 const supersedesContextWindow = isResolvableContextWindowActivity(activity);
580 const activities = pipe(
581 thread.activities,
582 Arr.filter(
583 (entry) =>
584 entry.id !== activity.id &&
585 !(
586 supersedesContextWindow &&
587 entry.turnId === activity.turnId &&
588 isResolvableContextWindowActivity(entry)
589 ),
590 ),
591 Arr.append(activity),
592 Arr.sort(activityOrder),
593 );
594​
595 return {
596 kind: "updated",
597 thread: { ...thread, activities, updatedAt: event.occurredAt },
598 };
599 }
600​
601 // ── Events that don't mutate thread state directly ──────────────
602 case "thread.approval-response-requested":
603 case "thread.user-input-response-requested":
604 case "thread.checkpoint-revert-requested":
605 return { kind: "unchanged" };
606 }
607​
608 // Forward-compatible: ignore unrecognized event types.
609 return { kind: "unchanged" };
611​
612// ── Helpers ──────────────────────────────────────────────────────────
613​
614/**
615 * Turn state to settle a still-running latest turn with when its session
616 * leaves the "running" status, or null while the session is (re)starting or
617 * running and the turn must stay unsettled.
618 */
619function settledTurnStateForSessionStatus(
620 status: OrchestrationSession["status"],
621): "completed" | "interrupted" | "error" | null {
622 switch (status) {
623 case "idle":
624 case "ready":
625 return "completed";
626 case "error":
627 return "error";
628 case "interrupted":
629 case "stopped":
630 return "interrupted";
631 case "starting":
632 case "running":
633 return null;
634 }
636​
637function checkpointStatusToTurnState(
638 status: "ready" | "missing" | "error",
639): OrchestrationLatestTurn["state"] {
640 switch (status) {
641 case "ready":
642 return "completed";
643 case "error":
644 return "error";
645 case "missing":
646 return "completed";
647 }
649​
650function rebindCheckpointAssistantMessage(
651 checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
652 turnId: TurnId,
653 messageId: MessageId,
654): OrchestrationCheckpointSummary[] {
655 return Arr.map(checkpoints, (entry) =>
656 entry.turnId === turnId ? { ...entry, assistantMessageId: messageId } : entry,
657 );
659​
660function retainMessagesAfterRevert(
661 messages: ReadonlyArray<OrchestrationMessage>,
662 retainedTurnIds: ReadonlySet<string>,
663): OrchestrationMessage[] {
664 // Keep messages that belong to a retained turn, plus system messages and
665 // messages without a turn binding (pre-turn-0 user messages).
666 return Arr.filter(messages, (message) => {
667 if (message.role === "system") {
668 return true;
669 }
670 if (message.turnId === null) {
671 return true;
672 }
673 return retainedTurnIds.has(message.turnId);
674 });