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 deletedAt: null,
115 messages: [],
116 proposedPlans: [],
117 activities: [],
118 checkpoints: [],
119 session: null,
120 },
121 };
122
123 case "thread.deleted":
124 return { kind: "deleted" };
125
126 case "thread.archived":
127 return {
128 kind: "updated",
129 thread: {
130 ...thread,
131 archivedAt: event.payload.archivedAt,
132 updatedAt: event.payload.updatedAt,
133 },
134 };
135
136 case "thread.unarchived":
137 return {
138 kind: "updated",
139 thread: { ...thread, archivedAt: null, updatedAt: event.payload.updatedAt },
140 };
141
142 // ── Thread metadata ─────────────────────────────────────────────
143 case "thread.meta-updated":
144 return {
145 kind: "updated",
146 thread: {
147 ...thread,
148 ...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
149 ...(event.payload.modelSelection !== undefined
150 ? { modelSelection: event.payload.modelSelection }
151 : {}),
152 ...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
153 ...(event.payload.worktreePath !== undefined
154 ? { worktreePath: event.payload.worktreePath }
155 : {}),
156 updatedAt: event.payload.updatedAt,
157 },
158 };
159
160 case "thread.runtime-mode-set":
161 return {
162 kind: "updated",
163 thread: {
164 ...thread,
165 runtimeMode: event.payload.runtimeMode,
166 updatedAt: event.payload.updatedAt,
167 },
168 };
169
170 case "thread.interaction-mode-set":
171 return {
172 kind: "updated",
173 thread: {
174 ...thread,
175 interactionMode: event.payload.interactionMode,
176 updatedAt: event.payload.updatedAt,
177 },
178 };
179
180 // ── Turn lifecycle ──────────────────────────────────────────────
181 case "thread.turn-start-requested":
182 return {
183 kind: "updated",
184 thread: {
185 ...thread,
186 ...(event.payload.modelSelection !== undefined
187 ? { modelSelection: event.payload.modelSelection }
188 : {}),
189 runtimeMode: event.payload.runtimeMode,
190 interactionMode: event.payload.interactionMode,
191 updatedAt: event.occurredAt,
192 },
193 };
194
195 case "thread.turn-interrupt-requested": {
196 if (event.payload.turnId === undefined) {
197 return { kind: "unchanged" };
198 }
199 const latestTurn = thread.latestTurn;
200 if (latestTurn === null || latestTurn.turnId !== event.payload.turnId) {
201 return { kind: "unchanged" };
202 }
203 return {
204 kind: "updated",
205 thread: {
206 ...thread,
207 latestTurn: {
208 ...latestTurn,
209 state: "interrupted",
210 startedAt: latestTurn.startedAt ?? event.payload.createdAt,
211 completedAt: latestTurn.completedAt ?? event.payload.createdAt,
212 },
213 updatedAt: event.occurredAt,
214 },
215 };
216 }
217
218 // ── Messages ────────────────────────────────────────────────────
219 case "thread.message-sent": {
220 const message: OrchestrationMessage = {
221 id: event.payload.messageId,
222 role: event.payload.role,
223 text: event.payload.text,
224 ...(event.payload.attachments !== undefined
225 ? { attachments: event.payload.attachments }
226 : {}),
227 turnId: event.payload.turnId,
228 streaming: event.payload.streaming,
229 createdAt: event.payload.createdAt,
230 updatedAt: event.payload.updatedAt,
231 };
232
233 const existingMessage = thread.messages.find((entry) => entry.id === message.id);
234 const messages = existingMessage
235 ? Arr.map(thread.messages, (entry) =>
236 entry.id !== message.id
237 ? entry
238 : {
239 ...entry,
240 text: message.streaming
241 ? `${entry.text}${message.text}`
242 : message.text.length > 0
243 ? message.text
244 : entry.text,
245 streaming: message.streaming,
246 ...(message.turnId !== undefined ? { turnId: message.turnId } : {}),
247 ...(message.streaming ? {} : { updatedAt: message.updatedAt }),
248 ...(message.attachments !== undefined
249 ? { attachments: message.attachments }
250 : {}),
251 },
252 )
253 : Arr.append(thread.messages, message);
254 // Update latestTurn for assistant messages bound to a turn. A completed
255 // assistant message only settles the turn once the session is no longer
256 // running it — providers may emit several assistant messages per turn
257 // (commentary between tool calls), and the turn must stay unsettled
258 // until the provider reports turn end.
259 const turnStillRunning =
260 event.payload.turnId !== null &&
261 thread.session?.status === "running" &&
262 thread.session.activeTurnId === event.payload.turnId;
263 const settlesTurn = !event.payload.streaming && !turnStillRunning;
264 const latestTurn: OrchestrationThread["latestTurn"] =
265 event.payload.role === "assistant" &&
266 event.payload.turnId !== null &&
267 (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
268 ? {
269 turnId: event.payload.turnId,
270 state: settlesTurn
271 ? thread.latestTurn?.state === "interrupted"
272 ? "interrupted"
273 : thread.latestTurn?.state === "error"
274 ? "error"
275 : "completed"
276 : "running",
277 requestedAt:
278 thread.latestTurn?.turnId === event.payload.turnId
279 ? thread.latestTurn.requestedAt
280 : event.payload.createdAt,
281 startedAt:
282 thread.latestTurn?.turnId === event.payload.turnId
283 ? (thread.latestTurn.startedAt ?? event.payload.createdAt)
284 : event.payload.createdAt,
285 completedAt: settlesTurn
286 ? event.payload.updatedAt
287 : thread.latestTurn?.turnId === event.payload.turnId
288 ? (thread.latestTurn.completedAt ?? null)
289 : null,
290 assistantMessageId: event.payload.messageId,
291 }
292 : thread.latestTurn;
293
294 // Rebind checkpoint assistant message IDs for assistant messages.
295 const checkpoints =
296 event.payload.role === "assistant" && event.payload.turnId !== null
297 ? rebindCheckpointAssistantMessage(
298 thread.checkpoints,
299 event.payload.turnId,
300 event.payload.messageId,
301 )
302 : thread.checkpoints;
303
304 return {
305 kind: "updated",
306 thread: {
307 ...thread,
308 messages,
309 checkpoints,
310 latestTurn,
311 updatedAt: event.occurredAt,
312 },
313 };
314 }
315
316 // ── Session ─────────────────────────────────────────────────────
317 case "thread.session-set": {
318 // Leaving the "running" session status is the turn-end signal: settle a
319 // still-running latest turn so its duration reflects the whole turn.
320 const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
321 const latestTurn: OrchestrationLatestTurn | null =
322 event.payload.session.status === "running" && event.payload.session.activeTurnId !== null
323 ? {
324 turnId: event.payload.session.activeTurnId,
325 state: "running",
326 requestedAt:
327 thread.latestTurn?.turnId === event.payload.session.activeTurnId
328 ? thread.latestTurn.requestedAt
329 : event.payload.session.updatedAt,
330 startedAt:
331 thread.latestTurn?.turnId === event.payload.session.activeTurnId
332 ? (thread.latestTurn.startedAt ?? event.payload.session.updatedAt)
333 : event.payload.session.updatedAt,
334 completedAt: null,
335 assistantMessageId:
336 thread.latestTurn?.turnId === event.payload.session.activeTurnId
337 ? thread.latestTurn.assistantMessageId
338 : null,
339 }
340 : thread.latestTurn !== null &&
341 thread.latestTurn.state === "running" &&
342 settledTurnState !== null
343 ? {
344 ...thread.latestTurn,
345 state: settledTurnState,
346 // A running turn's completedAt can only hold a mid-turn
347 // placeholder checkpoint timestamp — the session leaving
348 // "running" is the authoritative turn end.
349 completedAt: event.payload.session.updatedAt,
350 }
351 : thread.latestTurn;
352
353 return {
354 kind: "updated",
355 thread: {
356 ...thread,
357 session: event.payload.session,
358 latestTurn,
359 updatedAt: event.occurredAt,
360 },
361 };
362 }
363
364 case "thread.session-stop-requested":
365 return thread.session === null
366 ? { kind: "unchanged" }
367 : {
368 kind: "updated",
369 thread: {
370 ...thread,
371 session: {
372 ...thread.session,
373 status: "stopped",
374 activeTurnId: null,
375 updatedAt: event.payload.createdAt,
376 },
377 updatedAt: event.occurredAt,
378 },
379 };
380
381 // ── Proposed plans ──────────────────────────────────────────────
382 case "thread.proposed-plan-upserted": {
383 const proposedPlan = event.payload.proposedPlan;
384
385 const proposedPlans = pipe(
386 thread.proposedPlans,
387 Arr.filter((entry) => entry.id !== proposedPlan.id),
388 Arr.append(proposedPlan),
389 Arr.sort(proposedPlanOrder),
390 );
391
392 return {
393 kind: "updated",
394 thread: { ...thread, proposedPlans, updatedAt: event.occurredAt },
395 };
396 }
397
398 // ── Checkpoints / turn diffs ────────────────────────────────────
399 case "thread.turn-diff-completed": {
400 const checkpoint: OrchestrationCheckpointSummary = {
401 turnId: event.payload.turnId,
402 checkpointTurnCount: event.payload.checkpointTurnCount,
403 checkpointRef: event.payload.checkpointRef,
404 status: event.payload.status,
405 files: event.payload.files,
406 assistantMessageId: event.payload.assistantMessageId,
407 completedAt: event.payload.completedAt,
408 };
409
410 const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId);
411 // Don't overwrite a non-missing checkpoint with a missing one.
412 if (existing && existing.status !== "missing" && checkpoint.status === "missing") {
413 return { kind: "unchanged" };
414 }
415
416 const checkpoints = pipe(
417 thread.checkpoints,
418 Arr.filter((entry) => entry.turnId !== checkpoint.turnId),
419 Arr.append(checkpoint),
420 Arr.sort(checkpointOrder),
421 );
422
423 // Mid-turn diff updates produce placeholder checkpoints; record the
424 // checkpoint, but don't settle a turn its session is still running.
425 const diffTurnStillRunning =
426 thread.session?.status === "running" &&
427 thread.session.activeTurnId === event.payload.turnId;
428 const latestTurn =
429 !diffTurnStillRunning &&
430 (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
431 ? {
432 turnId: event.payload.turnId,
433 state: checkpointStatusToTurnState(event.payload.status),
434 requestedAt: thread.latestTurn?.requestedAt ?? event.payload.completedAt,
435 startedAt: thread.latestTurn?.startedAt ?? event.payload.completedAt,
436 completedAt: event.payload.completedAt,
437 assistantMessageId: event.payload.assistantMessageId,
438 }
439 : thread.latestTurn;
440
441 return {
442 kind: "updated",
443 thread: { ...thread, checkpoints, latestTurn, updatedAt: event.occurredAt },
444 };
445 }
446
447 // ── Revert ──────────────────────────────────────────────────────
448 case "thread.reverted": {
449 const checkpoints = pipe(
450 thread.checkpoints,
451 Arr.filter(
452 (entry) =>
453 entry.checkpointTurnCount !== undefined &&
454 entry.checkpointTurnCount <= event.payload.turnCount,
455 ),
456 Arr.sort(checkpointOrder),
457 );
458
459 const retainedTurnIds = new Set(Arr.map(checkpoints, (entry) => entry.turnId));
460 const messages = retainMessagesAfterRevert(thread.messages, retainedTurnIds);
461 const proposedPlans = pipe(
462 thread.proposedPlans,
463 Arr.filter((plan) => plan.turnId === null || retainedTurnIds.has(plan.turnId)),
464 );
465 const activities = pipe(
466 thread.activities,
467 Arr.filter((activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId)),
468 );
469 const latestCheckpoint = checkpoints.at(-1) ?? null;
470
471 return {
472 kind: "updated",
473 thread: {
474 ...thread,
475 checkpoints,
476 messages,
477 proposedPlans,
478 activities,
479 latestTurn:
480 latestCheckpoint === null
481 ? null
482 : {
483 turnId: latestCheckpoint.turnId,
484 state: checkpointStatusToTurnState(
485 latestCheckpoint.status as "ready" | "missing" | "error",
486 ),
487 requestedAt: latestCheckpoint.completedAt,
488 startedAt: latestCheckpoint.completedAt,
489 completedAt: latestCheckpoint.completedAt,
490 assistantMessageId: latestCheckpoint.assistantMessageId ?? null,
491 },
492 updatedAt: event.occurredAt,
493 },
494 };
495 }
496
497 // ── Activities ──────────────────────────────────────────────────
498 case "thread.activity-appended": {
499 const activities = pipe(
500 thread.activities,
501 Arr.filter((activity) => activity.id !== event.payload.activity.id),
502 Arr.append(event.payload.activity),
503 Arr.sort(activityOrder),
504 );
505
506 return {
507 kind: "updated",
508 thread: { ...thread, activities, updatedAt: event.occurredAt },
509 };
510 }
511
512 // ── Events that don't mutate thread state directly ──────────────
513 case "thread.approval-response-requested":
514 case "thread.user-input-response-requested":
515 case "thread.checkpoint-revert-requested":
516 return { kind: "unchanged" };
517 }
518
519 // Forward-compatible: ignore unrecognized event types.
520 return { kind: "unchanged" };
521}
522
523// ── Helpers ──────────────────────────────────────────────────────────
524
525/**
526 * Turn state to settle a still-running latest turn with when its session
527 * leaves the "running" status, or null while the session is (re)starting or
528 * running and the turn must stay unsettled.
529 */
530function settledTurnStateForSessionStatus(
531 status: OrchestrationSession["status"],
532): "completed" | "interrupted" | "error" | null {
533 switch (status) {
534 case "idle":
535 case "ready":
536 return "completed";
537 case "error":
538 return "error";
539 case "interrupted":
540 case "stopped":
541 return "interrupted";
542 case "starting":
543 case "running":
544 return null;
545 }
546}
547
548function checkpointStatusToTurnState(
549 status: "ready" | "missing" | "error",
550): OrchestrationLatestTurn["state"] {
551 switch (status) {
552 case "ready":
553 return "completed";
554 case "error":
555 return "error";
556 case "missing":
557 return "completed";
558 }
559}
560
561function rebindCheckpointAssistantMessage(
562 checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
563 turnId: TurnId,
564 messageId: MessageId,
565): OrchestrationCheckpointSummary[] {
566 return Arr.map(checkpoints, (entry) =>
567 entry.turnId === turnId ? { ...entry, assistantMessageId: messageId } : entry,
568 );
569}
570
571function retainMessagesAfterRevert(
572 messages: ReadonlyArray<OrchestrationMessage>,
573 retainedTurnIds: ReadonlySet<string>,
574): OrchestrationMessage[] {
575 // Keep messages that belong to a retained turn, plus system messages and
576 // messages without a turn binding (pre-turn-0 user messages).
577 return Arr.filter(messages, (message) => {
578 if (message.role === "system") {
579 return true;
580 }
581 if (message.turnId === null) {
582 return true;
583 }
584 return retainedTurnIds.has(message.turnId);
585 });
586}