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