Open History to see the last commit
1import type { RunId, ScreenReaderAnnouncements } from "@t3tools/contracts";
2import * as DateTime from "effect/DateTime";
3
4import type { TimelineEntry, WorkLogEntry } from "../../session-logic";
5import {
6 liveWorkEntryLabel,
7 timelineEntryRunId,
8 timelineEntryStartsResponse,
9} from "./MessagesTimeline.logic";
10import { markdownPlainText } from "./timelineMinimapItems";
11
12export interface TurnMessage {
13 readonly id: string;
14 /** Markdown. */
15 readonly text: string;
16 /** The agent stopped writing it and went on working. A turn's closing reply never is. */
17 readonly finished: boolean;
18 /** It arrived after the entry the caller last saw, unlike history loaded above it. */
19 readonly fresh: boolean;
20}
21
22export interface TurnDetail {
23 /** The step the agent is on, or null when its newest output is not a step. */
24 readonly activity: string | null;
25 /** The agent's messages in the latest turn, oldest first. */
26 readonly messages: ReadonlyArray<TurnMessage>;
27 /** The thread's newest entry. */
28 readonly tailId: string | null;
29}
30
31export const NO_TURN_DETAIL: TurnDetail = { activity: null, messages: [], tailId: null };
32
33const ACTIVITY_MAX_LENGTH = 120;
34// Parsing is synchronous, and nobody listens to a longer message through a live region.
35const MESSAGE_MAX_LENGTH = 2_000;
36
37// On screen these labels are a path or a query beside an icon.
38function withVerb(work: WorkLogEntry, label: string) {
39 if (work.itemType === "file_change") return `Editing ${label}`;
40 if (work.itemType !== "file_search" && work.itemType !== "web_search") return label;
41 if (/^search(?:ed|ing)?\s/i.test(label)) return label;
42 return `${work.itemType === "web_search" ? "Searching the web for" : "Searching for"} ${label}`;
43}
44
45type MessageEntry = Extract<TimelineEntry, { kind: "message" }>;
46
47// A steer starts a new attempt in the same run. The reply it cut off also stops streaming,
48// so only one that completed before the steer finished; see completeSupersededReplyEntryIds.
49function completedBeforeSuperseded(entry: MessageEntry) {
50 const item = entry.projectedItem?.item;
51 const supersededAt = entry.attempt?.completedAt ?? null;
52 return (
53 item?.type === "assistant_message" &&
54 item.status === "completed" &&
55 item.completedAt !== null &&
56 supersededAt !== null &&
57 DateTime.isLessThan(item.completedAt, supersededAt)
58 );
59}
60
61function stepLabel(work: WorkLogEntry, workspaceRoot: string | undefined): string | null {
62 // Reasoning text is never read out.
63 if (work.itemType === "reasoning") return "Thinking";
64 const status = work.toolLifecycleStatus;
65 if (status === "failed" || status === "declined" || status === "stopped") return null;
66 const label = liveWorkEntryLabel(work, workspaceRoot, true).replace(/\s+/g, " ").trim();
67 if (label === "") return null;
68 const spoken = withVerb(work, label);
69 return spoken.length > ACTIVITY_MAX_LENGTH ? `${spoken.slice(0, ACTIVITY_MAX_LENGTH)}…` : spoken;
70}
71
72/**
73 * What a screen reader can be told about the latest turn beyond its status.
74 * It reads the thread's entries before "Tool calls in chat" hides any, so what
75 * is spoken follows the announcement setting alone.
76 */
77export function turnDetail(
78 entries: ReadonlyArray<TimelineEntry>,
79 workspaceRoot: string | undefined,
80 knownTailId: string | null,
81): TurnDetail {
82 const messages: TurnMessage[] = [];
83 // Runs and attempts the agent kept working in after the entry being looked at.
84 const continuedRunIds = new Set<RunId | null>();
85 const continuedAttemptIds = new Set<string>();
86 const markContinued = (entry: TimelineEntry, runId: RunId | null) => {
87 continuedRunIds.add(runId);
88 if (entry.attempt !== undefined) continuedAttemptIds.add(entry.attempt.id);
89 };
90 let activity: string | null | undefined;
91 let fresh = true;
92 let index = entries.length - 1;
93 for (; index >= 0; index -= 1) {
94 const entry = entries[index]!;
95 if (timelineEntryStartsResponse(entry)) break;
96 if (entry.id === knownTailId) fresh = false;
97 if (entry.kind === "event") continue;
98 if (entry.kind === "work") {
99 const work = entry.entry;
100 if (work.sourceActivityKind === "context-compaction") {
101 activity ??= null;
102 continue;
103 }
104 // Notices, todo lists and checkpoints sit beside the turn's steps without being one.
105 if (work.tone !== "tool" && work.itemType !== "reasoning") continue;
106 markContinued(entry, work.runId ?? null);
107 // A request is spoken as the thread's status; once answered, the step it was for goes on.
108 if (work.itemType === "approval_request" || work.itemType === "user_input_request") continue;
109 if (activity === undefined) activity = stepLabel(work, workspaceRoot);
110 continue;
111 }
112 if (entry.kind === "message" && entry.message.role !== "assistant") continue;
113 // A reply, plan or rendered page is newer than any step before it.
114 activity ??= null;
115 const runId = timelineEntryRunId(entry);
116 if (entry.kind === "message") {
117 messages.push({
118 id: entry.message.id,
119 text: entry.message.text,
120 finished:
121 !entry.message.streaming &&
122 continuedRunIds.has(runId) &&
123 (entry.attempt?.status !== "superseded" ||
124 continuedAttemptIds.has(entry.attempt.id) ||
125 completedBeforeSuperseded(entry)),
126 fresh,
127 });
128 }
129 markContinued(entry, runId);
130 }
131 // Nothing is known to be new when the entry last seen is gone, or there was none.
132 let tailKnown = !fresh;
133 if (knownTailId !== null) {
134 for (; !tailKnown && index >= 0; index -= 1) tailKnown = entries[index]!.id === knownTailId;
135 }
136 return {
137 activity: activity ?? null,
138 messages: (tailKnown
139 ? messages
140 : messages.map((message) => ({ ...message, fresh: false }))
141 ).reverse(),
142 tailId: entries.at(-1)?.id ?? null,
143 };
144}
145
146export interface TurnDetailSnapshot extends TurnDetail {
147 readonly level: ScreenReaderAnnouncements;
148 readonly status: "working" | "approval" | "input" | "idle";
149}
150
151export interface TurnDetailMemory {
152 readonly activity: string | null;
153 /** Each message seen in the turn, and whether it was already finished then. */
154 readonly messages: ReadonlyMap<string, boolean>;
155 readonly tailId: string | null;
156}
157
158/** The heading every agent message has in the timeline. */
159const MESSAGE_AUTHOR = "T3 Code";
160
161/**
162 * Decides which of the turn's messages and steps a screen reader hears next.
163 * The first snapshot of a thread is a silent baseline, like its status.
164 */
165export function nextTurnDetailAnnouncement(
166 previous: TurnDetailMemory | null,
167 next: TurnDetailSnapshot,
168): {
169 readonly memory: TurnDetailMemory;
170 readonly messages: ReadonlyArray<string>;
171 readonly activity: string | null;
172} {
173 const memory: TurnDetailMemory = {
174 // A step is spoken again after a pause for an approval or a question.
175 activity: next.status === "working" ? next.activity : null,
176 messages: new Map(next.messages.map((message) => [message.id, message.finished])),
177 tailId: next.tailId,
178 };
179 // A turn that already ended is history, however late its entries arrive.
180 if (previous === null || next.level === "status" || next.status === "idle") {
181 return { memory, messages: [], activity: null };
182 }
183 return {
184 memory,
185 messages: next.messages
186 .filter(
187 (message) =>
188 message.finished &&
189 previous.messages.get(message.id) !== true &&
190 (message.fresh || previous.messages.has(message.id)),
191 )
192 .map((message) =>
193 message.text.length > MESSAGE_MAX_LENGTH
194 ? `${markdownPlainText(message.text.slice(0, MESSAGE_MAX_LENGTH))} More in the thread.`
195 : markdownPlainText(message.text),
196 )
197 .filter((text) => text !== "")
198 .map((text) => `${MESSAGE_AUTHOR}: ${text}`),
199 activity:
200 next.level === "everything" && memory.activity !== previous.activity ? memory.activity : null,
201 };
202}