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

threadReducer.ts

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