Skip to content
TypeScript

fix(web): screen readers hear when the open thread starts, needs you or finishes (#23752)

shivameb1510d2493c
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 92707af8ca1..62223ba8209 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -1,5 +1,6 @@
import { ScrollToEndButton, WorkspaceFileDropOverlay } from "./chat/TimelineOverlays";
import { usePasteToFocusComposer } from "./chat/usePasteToFocusComposer";
+import { announcedRun, isDetailBehindShell } from "./chat/threadActivityAnnouncement";
import {
deriveAvailableRevertTurnCounts,
deriveThreadPendingBackgroundTasks,
@@ -3275,11 +3276,22 @@ export default function ChatView(props: ChatViewProps) {
}
isCompacting={!paintOnlyDisplayedTimeline && isCompacting}
awaitingUser={
- !paintOnlyDisplayedTimeline &&
- (activePendingApproval !== null ||
- activePendingUserInput !== null ||
- // A secret request has no runtime request; the shell carries it.
- activeThreadShell?.hasPendingUserInput === true)
+ paintOnlyDisplayedTimeline
+ ? null
+ : activePendingApproval !== null
+ ? "approval"
+ : activePendingUserInput !== null ||
+ // A secret request has no runtime request; the shell carries it.
+ activeThreadShell?.hasPendingUserInput === true
+ ? "input"
+ : null
+ }
+ awaitingRequestId={
+ paintOnlyDisplayedTimeline
+ ? null
+ : (activePendingApproval?.requestId ??
+ activePendingUserInput?.requestId ??
+ null)
}
activeTurnStartedAt={paintOnlyDisplayedTimeline ? null : activeWorkStartedAt}
worktreeSetup={paintOnlyDisplayedTimeline ? null : worktreeSetup}
@@ -3315,6 +3327,15 @@ export default function ChatView(props: ChatViewProps) {
listRef={legendListRef}
runs={paintOnlyDisplayedTimeline ? [] : (serverProjection?.runs ?? [])}
latestRun={paintOnlyDisplayedTimeline ? null : activeActivityRun}
+ announcedRun={
+ paintOnlyDisplayedTimeline
+ ? null
+ : announcedRun(activeActivityRun, serverProjection?.runs ?? [])
+ }
+ detailBehindShell={
+ !paintOnlyDisplayedTimeline &&
+ isDetailBehindShell(activeLatestRun, activeThreadShell?.latestRun ?? null)
+ }
runningRunId={paintOnlyDisplayedTimeline ? null : activeRunningTurnId}
turnDiffSummaries={
paintOnlyDisplayedTimeline ? EMPTY_HELD_TURN_DIFF_SUMMARIES : turnDiffSummaries
@@ -3325,6 +3346,7 @@ export default function ChatView(props: ChatViewProps) {
routeThreadKey={displayedTimelineKey}
displayThreadKey={displayedTimelineKey}
paintOnly={paintOnlyDisplayedTimeline}
+ announceTurnStatus={!isProviderSubagent}
onOpenTurnDiff={
paintOnlyDisplayedTimeline ? noopHeldTurnDiff : onOpenTurnDiffStable
}
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index c3e2007c9aa..19b1aeb55a5 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -112,6 +112,7 @@ import {
import { V2EventTimelineRow } from "./TimelineV2EventRow";
import { useTimelinePositionRestore } from "./useTimelinePositionRestore";
import { useThreadFindPositionReader } from "./useThreadFindPositionReader";
+import { ThreadActivityAnnouncer } from "./ThreadActivityAnnouncer";
import { useStableHandoffRuns, useIncrementalTimelineRows, useStableRows } from "./useTimelineRows";
function timelineListStateFor(identity: string): {
@@ -192,17 +193,25 @@ interface MessagesTimelineProps {
onOpenWorktreeSetupTerminal?: (terminalId: string) => void;
isPreparingWorktree?: boolean;
isCompacting?: boolean;
- awaitingUser?: boolean;
+ awaitingUser?: "approval" | "input" | null;
+ /** Which request is waiting, so a second one of the same kind is announced too. */
+ awaitingRequestId?: string | null;
footer?: ReactNode;
listRef: React.RefObject<LegendListRef | null>;
timelineEntries: ReadonlyArray<TimelineEntry>;
latestRun: TimelineLatestRun | null;
+ /** The run the screen reader announcer follows; see announcedRun. */
+ announcedRun?: { readonly runId: RunId; readonly status: TimelineLatestRun["status"] } | null;
+ /** See isDetailBehindShell. */
+ detailBehindShell?: boolean;
runningRunId?: RunId | null;
turnDiffSummaries: ReadonlyArray<TurnDiffSummary>;
routeThreadKey: string;
displayThreadKey?: string;
paintOnly?: boolean;
+ /** Off where another region already speaks the thread's status, like a subagent's bar. */
+ announceTurnStatus?: boolean;
onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void;
parentThreadLink?: {
@@ -299,7 +308,8 @@ const ConversationTimeline = memo(function ConversationTimeline({
onOpenWorktreeSetupTerminal,
isPreparingWorktree = false,
isCompacting = false,
- awaitingUser = false,
+ awaitingUser = null,
+ awaitingRequestId = null,
listRef,
timelineEntries,
findExpanded = false,
@@ -308,11 +318,14 @@ const ConversationTimeline = memo(function ConversationTimeline({
findNavigationId = 0,
findPositionReaderRef,
latestRun,
+ announcedRun = null,
+ detailBehindShell = false,
runningRunId = null,
turnDiffSummaries,
routeThreadKey,
displayThreadKey,
paintOnly = false,
+ announceTurnStatus = true,
onOpenTurnDiff,
onOpenThread,
parentThreadLink = null,
@@ -947,10 +960,22 @@ const ConversationTimeline = memo(function ConversationTimeline({
isRevertingCheckpoint,
backgroundWorktreeSetup,
activeTurnInProgress,
- awaitingUser,
+ awaitingUser: awaitingUser !== null,
isPreparingWorktree,
latestRunId: latestRun?.runId ?? null,
};
+ // Mounted in both the empty and filled timeline so a thread's first turn
+ // starts from a baseline instead of a fresh, silent region.
+ const activityAnnouncer = (
+ <ThreadActivityAnnouncer
+ threadKey={paintOnly || !announceTurnStatus ? null : listIdentityKey}
+ status={awaitingUser ?? (isWorking ? "working" : "idle")}
+ requestId={awaitingRequestId}
+ runId={announcedRun?.runId ?? null}
+ runStatus={announcedRun?.status ?? null}
+ detailBehind={detailBehindShell}
+ />
+ );
const listHeaderLeadingContent =
parentThreadLink === null ? (
topFadeEnabled ? (
@@ -1044,100 +1069,111 @@ const ConversationTimeline = memo(function ConversationTimeline({
footer === null
) {
if (hideEmptyPlaceholder) {
- return <div className="h-full min-h-0 bg-background" data-timeline-loading="true" />;
+ return (
+ <>
+ {activityAnnouncer}
+ <div className="h-full min-h-0 bg-background" data-timeline-loading="true" />
+ </>
+ );
}
return (
- <div
- className="flex h-full items-center justify-center ps-(--chat-lane-inset-start) pe-(--chat-lane-inset-end)"
- style={{ paddingBottom: emptyPlaceholderInset }}
- >
- <p className="text-sm text-muted-foreground/30">
- Send a message to start the conversation.
- </p>
- </div>
+ <>
+ {activityAnnouncer}
+ <div
+ className="flex h-full items-center justify-center ps-(--chat-lane-inset-start) pe-(--chat-lane-inset-end)"
+ style={{ paddingBottom: emptyPlaceholderInset }}
+ >
+ <p className="text-sm text-muted-foreground/30">
+ Send a message to start the conversation.
+ </p>
+ </div>
+ </>
);
}
return (
- <MarkdownFindContext value={findActive}>
- <TimelineRowActivityCtx value={activityState}>
- <TooltipScrollDismissArea
- ref={setTimelineViewportElement}
- className="relative h-full min-h-0"
- data-assistant-citation-viewport="true"
- >
- {onCiteAssistantText && citationThreadRef ? (
- <AssistantSelectionToolbar
- viewport={timelineViewportElement}
- threadRef={citationThreadRef}
- onCite={onCiteAssistantText}
+ <>
+ {activityAnnouncer}
+ <MarkdownFindContext value={findActive}>
+ <TimelineRowActivityCtx value={activityState}>
+ <TooltipScrollDismissArea
+ ref={setTimelineViewportElement}
+ className="relative h-full min-h-0"
+ data-assistant-citation-viewport="true"
+ >
+ {onCiteAssistantText && citationThreadRef ? (
+ <AssistantSelectionToolbar
+ viewport={timelineViewportElement}
+ threadRef={citationThreadRef}
+ onCite={onCiteAssistantText}
+ />
+ ) : null}
+ <LegendList<MessagesTimelineRow>
+ ref={setTimelineList}
+ data={rows}
+ extraData={listExtraData}
+ keyExtractor={keyExtractor}
+ getItemType={getItemType}
+ renderItem={renderItem}
+ estimatedItemSize={90}
+ initialScrollAtEnd={
+ !findActive && citationRequest === null && rememberedPosition?.atEnd !== false
+ }
+ // Legend needs a data refresh to mount new pins without a scroll event.
+ dataVersion={readyCitationRequest?.key ?? listIdentityKey}
+ {...(alwaysRender ? { alwaysRender } : {})}
+ onLoad={handleListLoad}
+ {...(anchoredEndSpace ? { anchoredEndSpace } : {})}
+ contentInsetEndAdjustment={anchoredEndSpace ? contentInsetEndAdjustment : 0}
+ maintainScrollAtEnd={
+ citationPositioning ||
+ (restoringThreadPosition && rememberedPosition?.atEnd === false) ||
+ anchoredEndSpace ||
+ !liveFollowEnabled ||
+ fullscreenAppRowId !== null ||
+ disclosureToggleSettling
+ ? false
+ : isWorking && !prefersReducedMotion && settlingListIdentity === null
+ ? TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH
+ : TIMELINE_MAINTAIN_SCROLL_AT_END
+ }
+ maintainVisibleContentPosition={
+ findActive ||
+ citationPositioning ||
+ (restoringThreadPosition && rememberedPosition?.atEnd === false)
+ ? false
+ : maintainVisibleContentPosition
+ }
+ maintainScrollAtEndThreshold={1}
+ onScroll={handleScroll}
+ onItemSizeChanged={handleItemSizeChanged}
+ className={cn(
+ "messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain [overflow-anchor:none]",
+ topFadeEnabled && "topbar-scroll-fade",
+ )}
+ ListHeaderComponent={listHeader}
+ ListFooterComponent={timelineListFooter}
/>
- ) : null}
- <LegendList<MessagesTimelineRow>
- ref={setTimelineList}
- data={rows}
- extraData={listExtraData}
- keyExtractor={keyExtractor}
- getItemType={getItemType}
- renderItem={renderItem}
- estimatedItemSize={90}
- initialScrollAtEnd={
- !findActive && citationRequest === null && rememberedPosition?.atEnd !== false
- }
- // Legend needs a data refresh to mount new pins without a scroll event.
- dataVersion={readyCitationRequest?.key ?? listIdentityKey}
- {...(alwaysRender ? { alwaysRender } : {})}
- onLoad={handleListLoad}
- {...(anchoredEndSpace ? { anchoredEndSpace } : {})}
- contentInsetEndAdjustment={anchoredEndSpace ? contentInsetEndAdjustment : 0}
- maintainScrollAtEnd={
- citationPositioning ||
- (restoringThreadPosition && rememberedPosition?.atEnd === false) ||
- anchoredEndSpace ||
- !liveFollowEnabled ||
- fullscreenAppRowId !== null ||
- disclosureToggleSettling
- ? false
- : isWorking && !prefersReducedMotion && settlingListIdentity === null
- ? TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH
- : TIMELINE_MAINTAIN_SCROLL_AT_END
- }
- maintainVisibleContentPosition={
- findActive ||
- citationPositioning ||
- (restoringThreadPosition && rememberedPosition?.atEnd === false)
- ? false
- : maintainVisibleContentPosition
- }
- maintainScrollAtEndThreshold={1}
- onScroll={handleScroll}
- onItemSizeChanged={handleItemSizeChanged}
- className={cn(
- "messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain [overflow-anchor:none]",
- topFadeEnabled && "topbar-scroll-fade",
- )}
- ListHeaderComponent={listHeader}
- ListFooterComponent={timelineListFooter}
- />
- <TimelineMinimap
- items={minimapItems}
- hasPersistentGutter={minimapHasPersistentGutter}
- hitStripWidth={minimapHitStripWidth}
- currentIndex={minimapCurrentIndex}
- stripMap={minimapStripMap}
- onWheel={forwardMinimapWheel}
- onSelect={(item) => {
- onManualNavigation();
- void listRef.current?.scrollToIndex({
- index: item.rowIndex,
- animated: !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
- viewOffset: 24,
- });
- }}
- />
- </TooltipScrollDismissArea>
- </TimelineRowActivityCtx>
- </MarkdownFindContext>
+ <TimelineMinimap
+ items={minimapItems}
+ hasPersistentGutter={minimapHasPersistentGutter}
+ hitStripWidth={minimapHitStripWidth}
+ currentIndex={minimapCurrentIndex}
+ stripMap={minimapStripMap}
+ onWheel={forwardMinimapWheel}
+ onSelect={(item) => {
+ onManualNavigation();
+ void listRef.current?.scrollToIndex({
+ index: item.rowIndex,
+ animated: !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
+ viewOffset: 24,
+ });
+ }}
+ />
+ </TooltipScrollDismissArea>
+ </TimelineRowActivityCtx>
+ </MarkdownFindContext>
+ </>
);
});
diff --git a/apps/web/src/components/chat/ThreadActivityAnnouncer.tsx b/apps/web/src/components/chat/ThreadActivityAnnouncer.tsx
new file mode 100644
index 00000000000..0a1f13fcbc0
--- /dev/null
+++ b/apps/web/src/components/chat/ThreadActivityAnnouncer.tsx
@@ -0,0 +1,57 @@
+import { memo, useEffect, useRef } from "react";
+
+import {
+ nextThreadAnnouncement,
+ type ThreadActivitySnapshot,
+ type ThreadAnnouncementMemory,
+} from "./threadActivityAnnouncement";
+
+/**
+ * One polite live region for the open thread. Text is written straight to the
+ * DOM so an announcement never re-renders the timeline.
+ */
+export const ThreadActivityAnnouncer = memo(function ThreadActivityAnnouncer({
+ threadKey,
+ status,
+ requestId,
+ runId,
+ runStatus,
+ detailBehind,
+}: ThreadActivitySnapshot & {
+ /** Null while the timeline shows another thread during a switch. */
+ readonly threadKey: string | null;
+ /** See isDetailBehindShell. */
+ readonly detailBehind: boolean;
+}) {
+ const regionRef = useRef<HTMLDivElement>(null);
+ const memoryRef = useRef<{ threadKey: string; memory: ThreadAnnouncementMemory } | null>(null);
+
+ useEffect(() => {
+ const region = regionRef.current;
+ if (threadKey === null) {
+ memoryRef.current = null;
+ if (region !== null) region.textContent = "";
+ return;
+ }
+ if (detailBehind) return;
+ const previous = memoryRef.current?.threadKey === threadKey ? memoryRef.current.memory : null;
+ const { memory, announcement } = nextThreadAnnouncement(previous, {
+ status,
+ requestId,
+ runId,
+ runStatus,
+ });
+ memoryRef.current = { threadKey, memory };
+ if (region === null) return;
+ if (previous === null) {
+ region.textContent = "";
+ } else if (announcement !== null) {
+ // Screen readers ignore a write that leaves the text unchanged, so a
+ // repeated "Done" gets a trailing non-breaking space to count as new.
+ region.textContent = region.textContent === announcement ? `${announcement} ` : announcement;
+ }
+ }, [threadKey, status, requestId, runId, runStatus, detailBehind]);
+
+ // No role="status": Orca 50 maps it to a status bar in Chromium and drops its updates.
+ return <div ref={regionRef} aria-live="polite" className="sr-only" />;
+});
diff --git a/apps/web/src/components/chat/threadActivityAnnouncement.test.ts b/apps/web/src/components/chat/threadActivityAnnouncement.test.ts
new file mode 100644
index 00000000000..b4789542630
--- /dev/null
+++ b/apps/web/src/components/chat/threadActivityAnnouncement.test.ts
@@ -0,0 +1,221 @@
+import {
+ MessageId,
+ type OrchestrationV2Run,
+ ProviderInstanceId,
+ RunId,
+ ThreadId,
+} from "@t3tools/contracts";
+import * as DateTime from "effect/DateTime";
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ announcedRun,
+ nextThreadAnnouncement,
+ type ThreadActivitySnapshot,
+ type ThreadAnnouncementMemory,
+} from "./threadActivityAnnouncement";
+
+const firstRun = RunId.make("run-1");
+const secondRun = RunId.make("run-2");
+
+const idle = (
+ runId: RunId | null,
+ runStatus: ThreadActivitySnapshot["runStatus"],
+): ThreadActivitySnapshot => ({ status: "idle", requestId: null, runId, runStatus });
+const busy = (
+ status: Exclude<ThreadActivitySnapshot["status"], "idle"> = "working",
+ runId: RunId | null = secondRun,
+ runStatus: ThreadActivitySnapshot["runStatus"] = "running",
+ requestId: string | null = status === "working" ? null : "request-1",
+): ThreadActivitySnapshot => ({ status, requestId, runId, runStatus });
+
+function speak(snapshots: ReadonlyArray<ThreadActivitySnapshot>) {
+ let memory: ThreadAnnouncementMemory | null = null;
+ const spoken: string[] = [];
+ for (const snapshot of snapshots) {
+ const result = nextThreadAnnouncement(memory, snapshot);
+ memory = result.memory;
+ if (result.announcement !== null) spoken.push(result.announcement);
+ }
+ return spoken;
+}
+
+describe("nextThreadAnnouncement", () => {
+ it("follows a turn from start to finish", () => {
+ expect(
+ speak([idle(firstRun, "completed"), busy(), busy(), idle(secondRun, "completed")]),
+ ).toEqual(["Working", "Done"]);
+ });
+
+ it("says Working once when a send looks idle before its run appears", () => {
+ expect(
+ speak([idle(null, null), busy(), idle(null, null), busy(), idle(secondRun, "completed")]),
+ ).toEqual(["Working", "Done"]);
+ });
+
+ it("announces a queued message that starts as the last turn ends", () => {
+ const thirdRun = RunId.make("run-3");
+ expect(
+ speak([
+ idle(firstRun, "completed"),
+ busy("working", firstRun, "completed"),
+ busy(),
+ busy("working", secondRun, "completed"),
+ busy("working", thirdRun, "starting"),
+ idle(thirdRun, "completed"),
+ ]),
+ ).toEqual(["Working", "Working", "Done"]);
+ // The last turn's run is still settling when the follow-up is sent.
+ expect(
+ speak([
+ idle(firstRun, "running"),
+ busy("working", firstRun, "running"),
+ busy("working", secondRun, "starting"),
+ ]),
+ ).toEqual(["Working"]);
+ expect(
+ speak([
+ idle(firstRun, "running"),
+ busy("working", firstRun, "running"),
+ idle(firstRun, "completed"),
+ busy("working", secondRun, "starting"),
+ idle(secondRun, "completed"),
+ ]),
+ ).toEqual(["Working", "Done"]);
+ expect(
+ speak([
+ busy("working", firstRun, "running"),
+ idle(firstRun, "running"),
+ busy("working", firstRun, "running"),
+ busy("working", secondRun, "starting"),
+ ]),
+ ).toEqual(["Working"]);
+ });
+
+ it("treats a run that starts while the thread looks idle as the next turn", () => {
+ const thirdRun = RunId.make("run-3");
+ // A resume or a turn started from another device.
+ expect(
+ speak([
+ idle(firstRun, "completed"),
+ idle(secondRun, "starting"),
+ busy("working", secondRun, "running"),
+ idle(secondRun, "completed"),
+ ]),
+ ).toEqual(["Working", "Done"]);
+ // A queued message waiting to start after the last turn.
+ expect(
+ speak([
+ idle(firstRun, "completed"),
+ busy(),
+ idle(thirdRun, "queued"),
+ idle(thirdRun, "starting"),
+ busy("working", thirdRun, "running"),
+ idle(thirdRun, "completed"),
+ ]),
+ ).toEqual(["Working", "Working", "Done"]);
+ });
+
+ it("stays silent when a thread opens mid-turn or after one", () => {
+ expect(speak([idle(firstRun, "completed"), idle(firstRun, "completed")])).toEqual([]);
+ expect(speak([busy(), busy()])).toEqual([]);
+ });
+
+ it("announces the end of a turn that was already running when the thread opened", () => {
+ expect(speak([busy(), idle(secondRun, "failed")])).toEqual(["Failed"]);
+ });
+
+ it("says how the turn ended when a queued message was cancelled before it started", () => {
+ const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
+ const run = (id: RunId, ordinal: number, status: OrchestrationV2Run["status"]) =>
+ ({
+ id,
+ threadId: ThreadId.make("thread-1"),
+ ordinal,
+ providerInstanceId: ProviderInstanceId.make("codex"),
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
+ providerThreadId: null,
+ userMessageId: MessageId.make(`message-${ordinal}`),
+ rootNodeId: null,
+ activeAttemptId: null,
+ status,
+ requestedAt: now,
+ startedAt: status === "cancelled" ? null : now,
+ completedAt: now,
+ checkpointId: null,
+ contextHandoffId: null,
+ }) satisfies OrchestrationV2Run;
+ const cancelledRun = RunId.make("run-3");
+ const ended = announcedRun({ runId: cancelledRun, status: "cancelled", startedAt: null }, [
+ run(secondRun, 1, "completed"),
+ run(cancelledRun, 2, "cancelled"),
+ ]);
+ expect(speak([busy(), idle(ended?.runId ?? null, ended?.status ?? null)])).toEqual(["Done"]);
+ });
+
+ it("waits for the run to settle before announcing how the turn ended", () => {
+ expect(
+ speak([
+ idle(firstRun, "completed"),
+ busy(),
+ idle(secondRun, "running"),
+ idle(secondRun, "interrupted"),
+ ]),
+ ).toEqual(["Working", "Stopped"]);
+ });
+
+ it("does not report the previous turn's ending when work stops before a new run exists", () => {
+ expect(
+ speak([
+ idle(firstRun, "completed"),
+ busy("working", firstRun, "completed"),
+ idle(firstRun, "completed"),
+ busy(),
+ idle(secondRun, "completed"),
+ ]),
+ ).toEqual(["Working", "Working", "Done"]);
+ // The previous run finished while this client looked idle.
+ expect(
+ speak([
+ idle(firstRun, "completed"),
+ idle(secondRun, "completed"),
+ busy("working", secondRun, "completed"),
+ idle(secondRun, "completed"),
+ ]),
+ ).toEqual(["Working"]);
+ });
+
+ it("lets the next turn start after one is rolled back", () => {
+ expect(
+ speak([
+ idle(firstRun, "completed"),
+ busy(),
+ idle(secondRun, "rolled_back"),
+ busy("working", RunId.make("run-3")),
+ ]),
+ ).toEqual(["Working", "Working"]);
+ });
+
+ it("announces each request once without repeating that work resumed", () => {
+ expect(
+ speak([
+ busy(),
+ busy("approval"),
+ busy("approval"),
+ busy(),
+ busy("input"),
+ idle(secondRun, "completed"),
+ ]),
+ ).toEqual(["Needs approval", "Needs your input", "Done"]);
+ });
+
+ it("announces a second request of the same kind once the first is answered", () => {
+ expect(
+ speak([
+ busy(),
+ busy("approval", secondRun, "running", "request-1"),
+ busy("approval", secondRun, "running", "request-2"),
+ ]),
+ ).toEqual(["Needs approval", "Needs approval"]);
+ });
+});
diff --git a/apps/web/src/components/chat/threadActivityAnnouncement.ts b/apps/web/src/components/chat/threadActivityAnnouncement.ts
new file mode 100644
index 00000000000..5e658748dbe
--- /dev/null
+++ b/apps/web/src/components/chat/threadActivityAnnouncement.ts
@@ -0,0 +1,166 @@
+import type { OrchestrationV2Run, OrchestrationV2RunStatus, RunId } from "@t3tools/contracts";
+import { latestExecutedRun } from "@t3tools/shared/orchestrationV2ThreadError";
+
+export type ThreadActivityStatus = "working" | "approval" | "input" | "idle";
+
+export interface ThreadActivitySnapshot {
+ readonly status: ThreadActivityStatus;
+ /** The pending approval or question, when there is one. */
+ readonly requestId: string | null;
+ readonly runId: RunId | null;
+ readonly runStatus: OrchestrationV2RunStatus | null;
+}
+
+export interface ThreadAnnouncementMemory {
+ readonly snapshot: ThreadActivitySnapshot;
+ /**
+ * The turn under way: the run it belongs to, "unknown" until that run shows
+ * up, or null between turns. Its ending is announced once, then it clears.
+ */
+ readonly turnRunId: RunId | "unknown" | null;
+ /** The run whose ending is already known, so a stale run is never announced as this turn's. */
+ readonly settledRunId: RunId | null;
+ /** The run shown while idle belongs to the last turn, even if it is still settling. */
+ readonly idleRunId: RunId | null;
+}
+
+const ACTIVE_RUN_STATUSES: ReadonlySet<OrchestrationV2RunStatus | null> = new Set([
+ "preparing",
+ "starting",
+ "running",
+ "waiting",
+]);
+
+const STARTING_RUN_STATUSES: ReadonlySet<OrchestrationV2RunStatus | null> = new Set([
+ "queued",
+ "preparing",
+ "starting",
+]);
+
+function runOutcomeText(status: OrchestrationV2RunStatus | null): string | null {
+ switch (status) {
+ case "completed":
+ return "Done";
+ case "failed":
+ return "Failed";
+ case "interrupted":
+ case "cancelled":
+ return "Stopped";
+ default:
+ return null;
+ }
+}
+
+interface RunState {
+ readonly runId: RunId;
+ readonly status: OrchestrationV2RunStatus;
+}
+
+/**
+ * The thread's detail hasn't caught up with the live thread shell: it isn't
+ * loaded yet, or a cached copy still shows an older run or state. Reading such
+ * a frame as the baseline replays what already happened, so it's skipped.
+ */
+export function isDetailBehindShell(detailRun: RunState | null, shellRun: RunState | null) {
+ return (
+ shellRun !== null &&
+ (detailRun?.runId !== shellRun.runId || detailRun.status !== shellRun.status)
+ );
+}
+
+/**
+ * A queued message cancelled before it started keeps its place in line, so it
+ * shows up as the thread's latest run. It never ran, so the turn ended however
+ * the last run that did ran.
+ */
+export function announcedRun(
+ activityRun: (RunState & { readonly startedAt: string | null }) | null,
+ runs: ReadonlyArray<OrchestrationV2Run>,
+): RunState | null {
+ if (activityRun?.status !== "cancelled" || activityRun.startedAt !== null) return activityRun;
+ const run = latestExecutedRun(runs);
+ return run === null ? null : { runId: run.id, status: run.status };
+}
+
+/**
+ * Decides what a screen reader hears when the open thread's turn changes state.
+ * The first snapshot of a thread is a silent baseline, so opening or switching
+ * threads never replays what already happened.
+ */
+export function nextThreadAnnouncement(
+ previous: ThreadAnnouncementMemory | null,
+ next: ThreadActivitySnapshot,
+): { readonly memory: ThreadAnnouncementMemory; readonly announcement: string | null } {
+ const idle = next.status === "idle";
+ // A run still starting up while the thread looks idle (a queued message,
+ // a resume) is the next turn's, not a leftover from the last one.
+ const idleRunId =
+ idle && !STARTING_RUN_STATUSES.has(next.runStatus) ? next.runId : (previous?.idleRunId ?? null);
+ // A run doing new work; the run left over from the last turn doesn't count.
+ const newRunId =
+ !idle && ACTIVE_RUN_STATUSES.has(next.runStatus) && next.runId !== idleRunId
+ ? next.runId
+ : null;
+
+ if (previous === null) {
+ return {
+ memory: {
+ snapshot: next,
+ turnRunId: idle ? null : (newRunId ?? "unknown"),
+ settledRunId: runOutcomeText(next.runStatus) === null ? null : next.runId,
+ idleRunId,
+ },
+ announcement: null,
+ };
+ }
+ const memory = { ...previous, snapshot: next, idleRunId };
+ const { turnRunId } = previous;
+
+ if (!idle) {
+ // Sending can look idle for a moment before the server reports the run,
+ // so a turn is tied to its run as soon as one appears, and only another
+ // run taking over (a queued message starting) is a new turn.
+ const turnStarted =
+ turnRunId === null ||
+ (newRunId !== null && turnRunId !== "unknown" && newRunId !== turnRunId);
+ const nextTurnRunId =
+ turnStarted || turnRunId === "unknown" ? (newRunId ?? "unknown") : turnRunId;
+ const announcement =
+ next.status === "approval"
+ ? previous.snapshot.status === "approval" && previous.snapshot.requestId === next.requestId
+ ? null
+ : "Needs approval"
+ : next.status === "input"
+ ? previous.snapshot.status === "input" && previous.snapshot.requestId === next.requestId
+ ? null
+ : "Needs your input"
+ : turnStarted
+ ? "Working"
+ : null;
+ return { memory: { ...memory, turnRunId: nextTurnRunId }, announcement };
+ }
+
+ // Work can stop a moment before the run settles; the ending waits for the run.
+ const outcome = runOutcomeText(next.runStatus);
+ if (turnRunId === null) {
+ // A run that settled unseen is history too, or the next failed send would claim it.
+ const settledRunId = outcome === null ? previous.settledRunId : next.runId;
+ return { memory: { ...memory, settledRunId }, announcement: null };
+ }
+ if (next.runStatus === "rolled_back") {
+ return { memory: { ...memory, turnRunId: null, settledRunId: next.runId }, announcement: null };
+ }
+ if (outcome === null) return { memory, announcement: null };
+ // Work stopped without a new run, e.g. a send that failed; the retry is a new turn.
+ if (next.runId === previous.settledRunId) {
+ return { memory: { ...memory, turnRunId: null }, announcement: null };
+ }
+ // The last turn's run settling while this turn waits for its own run is not this turn's ending.
+ if (turnRunId === "unknown" && next.runId === previous.idleRunId) {
+ return { memory: { ...memory, settledRunId: next.runId }, announcement: null };
+ }
+ return {
+ memory: { ...memory, turnRunId: null, settledRunId: next.runId },
+ announcement: outcome,
+ };
+}
diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx
index bff3c2c78ae..ac7ae29afef 100644
--- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx
+++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx
@@ -1344,8 +1344,12 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
) : null}
{/* The label alone is the live region: a role="status"
wrapper around the ticking duration would make
- screen readers announce every second. */}
- <span role="status">{topStatus.label}</span>
+ screen readers announce every second. The open
+ thread announces its own status, so its row stays
+ quiet instead of saying everything twice. */}
+ <span role={props.isRouteThread ? undefined : "status"}>
+ {topStatus.label}
+ </span>
{status === "working" ? (
<span aria-hidden>
<WorkingDuration startedAt={resolveWorkingStartedAt(thread)} />