Open History to see the last commit
1import type { OrchestrationV2Run, OrchestrationV2RunStatus, RunId } from "@t3tools/contracts";
2import { latestExecutedRun } from "@t3tools/shared/orchestrationV2ThreadError";
3
4export type ThreadActivityStatus = "working" | "approval" | "input" | "idle";
5
6export interface ThreadActivitySnapshot {
7 readonly status: ThreadActivityStatus;
8 /** The pending approval or question, when there is one. */
9 readonly requestId: string | null;
10 readonly runId: RunId | null;
11 readonly runStatus: OrchestrationV2RunStatus | null;
12}
13
14export interface ThreadAnnouncementMemory {
15 readonly snapshot: ThreadActivitySnapshot;
16 /**
17 * The turn under way: the run it belongs to, "unknown" until that run shows
18 * up, or null between turns. Its ending is announced once, then it clears.
19 */
20 readonly turnRunId: RunId | "unknown" | null;
21 /** The run whose ending is already known, so a stale run is never announced as this turn's. */
22 readonly settledRunId: RunId | null;
23 /** The run shown while idle belongs to the last turn, even if it is still settling. */
24 readonly idleRunId: RunId | null;
25}
26
27const ACTIVE_RUN_STATUSES: ReadonlySet<OrchestrationV2RunStatus | null> = new Set([
28 "preparing",
29 "starting",
30 "running",
31 "waiting",
32]);
33
34const STARTING_RUN_STATUSES: ReadonlySet<OrchestrationV2RunStatus | null> = new Set([
35 "queued",
36 "preparing",
37 "starting",
38]);
39
40function runOutcomeText(status: OrchestrationV2RunStatus | null): string | null {
41 switch (status) {
42 case "completed":
43 return "Done";
44 case "failed":
45 return "Failed";
46 case "interrupted":
47 case "cancelled":
48 return "Stopped";
49 default:
50 return null;
51 }
52}
53
54interface RunState {
55 readonly runId: RunId;
56 readonly status: OrchestrationV2RunStatus;
57}
58
59/**
60 * The thread's detail hasn't caught up with the live thread shell: it isn't
61 * loaded yet, or a cached copy still shows an older run or state. Reading such
62 * a frame as the baseline replays what already happened, so it's skipped.
63 */
64export function isDetailBehindShell(detailRun: RunState | null, shellRun: RunState | null) {
65 return (
66 shellRun !== null &&
67 (detailRun?.runId !== shellRun.runId || detailRun.status !== shellRun.status)
68 );
69}
70
71/**
72 * A queued message cancelled before it started keeps its place in line, so it
73 * shows up as the thread's latest run. It never ran, so the turn ended however
74 * the last run that did ran.
75 */
76export function announcedRun(
77 activityRun: (RunState & { readonly startedAt: string | null }) | null,
78 runs: ReadonlyArray<OrchestrationV2Run>,
79): RunState | null {
80 if (activityRun?.status !== "cancelled" || activityRun.startedAt !== null) return activityRun;
81 const run = latestExecutedRun(runs);
82 return run === null ? null : { runId: run.id, status: run.status };
83}
84
85/**
86 * Decides what a screen reader hears when the open thread's turn changes state.
87 * The first snapshot of a thread is a silent baseline, so opening or switching
88 * threads never replays what already happened.
89 */
90export function nextThreadAnnouncement(
91 previous: ThreadAnnouncementMemory | null,
92 next: ThreadActivitySnapshot,
93): { readonly memory: ThreadAnnouncementMemory; readonly announcement: string | null } {
94 const idle = next.status === "idle";
95 // A run still starting up while the thread looks idle (a queued message,
96 // a resume) is the next turn's, not a leftover from the last one.
97 const idleRunId =
98 idle && !STARTING_RUN_STATUSES.has(next.runStatus) ? next.runId : (previous?.idleRunId ?? null);
99 // A run doing new work; the run left over from the last turn doesn't count.
100 const newRunId =
101 !idle && ACTIVE_RUN_STATUSES.has(next.runStatus) && next.runId !== idleRunId
102 ? next.runId
103 : null;
104
105 if (previous === null) {
106 return {
107 memory: {
108 snapshot: next,
109 turnRunId: idle ? null : (newRunId ?? "unknown"),
110 settledRunId: runOutcomeText(next.runStatus) === null ? null : next.runId,
111 idleRunId,
112 },
113 announcement: null,
114 };
115 }
116 const memory = { ...previous, snapshot: next, idleRunId };
117 const { turnRunId } = previous;
118
119 if (!idle) {
120 // Sending can look idle for a moment before the server reports the run,
121 // so a turn is tied to its run as soon as one appears, and only another
122 // run taking over (a queued message starting) is a new turn.
123 const turnStarted =
124 turnRunId === null ||
125 (newRunId !== null && turnRunId !== "unknown" && newRunId !== turnRunId);
126 const nextTurnRunId =
127 turnStarted || turnRunId === "unknown" ? (newRunId ?? "unknown") : turnRunId;
128 const announcement =
129 next.status === "approval"
130 ? previous.snapshot.status === "approval" && previous.snapshot.requestId === next.requestId
131 ? null
132 : "Needs approval"
133 : next.status === "input"
134 ? previous.snapshot.status === "input" && previous.snapshot.requestId === next.requestId
135 ? null
136 : "Needs your input"
137 : turnStarted
138 ? "Working"
139 : null;
140 return { memory: { ...memory, turnRunId: nextTurnRunId }, announcement };
141 }
142
143 // Work can stop a moment before the run settles; the ending waits for the run.
144 const outcome = runOutcomeText(next.runStatus);
145 if (turnRunId === null) {
146 // A run that settled unseen is history too, or the next failed send would claim it.
147 const settledRunId = outcome === null ? previous.settledRunId : next.runId;
148 return { memory: { ...memory, settledRunId }, announcement: null };
149 }
150 if (next.runStatus === "rolled_back") {
151 return { memory: { ...memory, turnRunId: null, settledRunId: next.runId }, announcement: null };
152 }
153 if (outcome === null) return { memory, announcement: null };
154 // Work stopped without a new run, e.g. a send that failed; the retry is a new turn.
155 if (next.runId === previous.settledRunId) {
156 return { memory: { ...memory, turnRunId: null }, announcement: null };
157 }
158 // The last turn's run settling while this turn waits for its own run is not this turn's ending.
159 if (turnRunId === "unknown" && next.runId === previous.idleRunId) {
160 return { memory: { ...memory, settledRunId: next.runId }, announcement: null };
161 }
162 return {
163 memory: { ...memory, turnRunId: null, settledRunId: next.runId },
164 announcement: outcome,
165 };
166}