TypeScript
fix(web): screen readers hear which background thread finished, even with the sidebar collapsed (#23839)
shivama46f80ee28d9
diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsxindex bc3474e514f..e3213614c68 100644--- a/apps/web/src/components/AppSidebarLayout.tsx+++ b/apps/web/src/components/AppSidebarLayout.tsx@@ -37,6 +37,7 @@ import {usePanelAnimationSettings,usePanelNavigationSuppression,} from "../panelAnimations";+import { BackgroundThreadAnnouncer } from "./BackgroundThreadAnnouncer";import LegacyThreadSidebar from "./LegacySidebar";import { useThreadVisitedMigration } from "../hooks/useThreadVisitedMigration";import ThreadSidebar from "./Sidebar";@@ -434,6 +435,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {<SidebarRail onDoubleClick={resetSidebarWidth} /></Sidebar>{children}+ <BackgroundThreadAnnouncer /><SidebarControl /><NavigationHistoryShortcuts />{isOnSettings ? null : <ThreadUndoShortcut />}diff --git a/apps/web/src/components/BackgroundThreadAnnouncer.tsx b/apps/web/src/components/BackgroundThreadAnnouncer.tsxnew file mode 100644index 00000000000..40e0ebf3a0b--- /dev/null+++ b/apps/web/src/components/BackgroundThreadAnnouncer.tsx@@ -0,0 +1,64 @@+import { useAtomValue } from "@effect/atom-react";+import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";+import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";+import { useEffect, useRef } from "react";++import { useComposerDraftStore } from "../composerDraftStore";+import { useLiveRegion } from "../hooks/useLiveRegion";+import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget";+import { useQuietThreadShells } from "../state/entities";+import { liveShellEnvironmentIdsAtom } from "../state/shell";+import { resolveActiveThreadRouteRef } from "../threadRoutes";+import {+ type BackgroundThreadMemory,+ type BackgroundThreadSnapshot,+ nextBackgroundThreadAnnouncement,+ resolveBackgroundThreadRequest,+} from "./backgroundThreadAnnouncement";++/**+ * Speaks status changes for threads other than the open one. It lives outside+ * the sidebar because a collapsed sidebar is inert, which silences its rows.+ */+export function BackgroundThreadAnnouncer() {+ const threads = useQuietThreadShells();+ const liveEnvironmentIds = useAtomValue(liveShellEnvironmentIdsAtom);+ const routeTarget = useThreadRouteTarget();+ const routeDraftThread = useComposerDraftStore((store) =>+ routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null,+ );+ const openThreadRef = resolveActiveThreadRouteRef(routeTarget, routeDraftThread);+ const openThreadKey = openThreadRef === null ? null : scopedThreadKey(openThreadRef);+ const { regionRef, announce } = useLiveRegion();+ const memoryRef = useRef<BackgroundThreadMemory>(new Map());++ useEffect(() => {+ const now = new Date().toISOString();+ const snapshots: BackgroundThreadSnapshot[] = [];+ for (const thread of threads) {+ // Subagents have no row of their own; their requests surface on the parent.+ if (thread.archivedAt !== null || thread.lineage.relationshipToParent === "subagent")+ continue;+ if (!liveEnvironmentIds.has(thread.environmentId)) continue;+ snapshots.push({+ key: scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),+ title: thread.title,+ ...resolveBackgroundThreadRequest(thread),+ runId: thread.latestRun?.runId ?? null,+ runStatus: thread.latestRun?.status ?? null,+ activeRunId: thread.runtime?.activeRunId ?? null,+ snoozed: effectiveSnoozed(thread, { now }),+ });+ }+ const { memory, announcement } = nextBackgroundThreadAnnouncement(+ memoryRef.current,+ snapshots,+ openThreadKey,+ );+ memoryRef.current = memory;+ if (announcement !== null) announce(announcement);+ }, [threads, liveEnvironmentIds, openThreadKey, announce]);++ // 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/backgroundThreadAnnouncement.test.ts b/apps/web/src/components/backgroundThreadAnnouncement.test.tsnew file mode 100644index 00000000000..b2b6195d8f2--- /dev/null+++ b/apps/web/src/components/backgroundThreadAnnouncement.test.ts@@ -0,0 +1,189 @@+import { RunId, RuntimeRequestId } from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import { describe, expect, it } from "vite-plus/test";++import {+ type BackgroundThreadMemory,+ type BackgroundThreadSnapshot,+ nextBackgroundThreadAnnouncement,+ resolveBackgroundThreadRequest,+} from "./backgroundThreadAnnouncement";++const firstRun = RunId.make("run-1");+const secondRun = RunId.make("run-2");++function thread(+ key: string,+ title: string,+ state: Partial<Omit<BackgroundThreadSnapshot, "key" | "title">> = {},+): BackgroundThreadSnapshot {+ return {+ key,+ title,+ request: null,+ requestId: null,+ runId: firstRun,+ runStatus: "running",+ activeRunId: null,+ snoozed: false,+ ...state,+ };+}+const login = (state?: Partial<BackgroundThreadSnapshot>) =>+ thread("env:login", "Fix login redirect", state);+const docs = (state?: Partial<BackgroundThreadSnapshot>) =>+ thread("env:docs", "Update docs", state);++function speak(+ frames: ReadonlyArray<{+ readonly threads: ReadonlyArray<BackgroundThreadSnapshot>;+ readonly open?: string;+ }>,+) {+ let memory: BackgroundThreadMemory = new Map();+ const spoken: string[] = [];+ for (const frame of frames) {+ const result = nextBackgroundThreadAnnouncement(memory, frame.threads, frame.open ?? null);+ memory = result.memory;+ if (result.announcement !== null) spoken.push(result.announcement);+ }+ return spoken;+}++describe("nextBackgroundThreadAnnouncement", () => {+ it("names the thread with the same words the open thread uses", () => {+ expect(+ speak([+ { threads: [login()] },+ { threads: [login({ request: "approval" })] },+ { threads: [login()] },+ { threads: [login({ request: "input" })] },+ { threads: [login({ runStatus: "completed" })] },+ { threads: [login({ runId: secondRun, runStatus: "failed" })] },+ { threads: [login({ runId: RunId.make("run-3"), runStatus: "interrupted" })] },+ ]),+ ).toEqual([+ "Needs approval: Fix login redirect",+ "Needs your input: Fix login redirect",+ "Done: Fix login redirect",+ "Failed: Fix login redirect",+ "Stopped: Fix login redirect",+ ]);+ });++ it("announces each run's ending once", () => {+ expect(+ speak([+ { threads: [login()] },+ { threads: [login({ runStatus: "completed" })] },+ // Marking the thread unread or renaming it changes nothing about the run.+ { threads: [login({ runStatus: "completed", title: "Fix the login redirect" })] },+ // The next run can finish between two updates, so it never looks busy here.+ { threads: [login({ runId: secondRun, runStatus: "completed" })] },+ { threads: [login({ runId: RunId.make("run-3"), runStatus: "rolled_back" })] },+ ]),+ ).toEqual(["Done: Fix login redirect", "Done: Fix login redirect"]);+ });++ it("announces a second request of the same kind", () => {+ expect(+ speak([+ { threads: [login()] },+ { threads: [login({ request: "approval", requestId: "request-1" })] },+ { threads: [login({ request: "approval", requestId: "request-2" })] },+ ]),+ ).toEqual(["Needs approval: Fix login redirect", "Needs approval: Fix login redirect"]);+ });++ it("doesn't call a thread stopped when a queued message is cancelled while it works", () => {+ expect(+ speak([+ { threads: [login({ activeRunId: firstRun })] },+ {+ threads: [login({ runId: secondRun, runStatus: "cancelled", activeRunId: firstRun })],+ },+ { threads: [login({ runId: secondRun, runStatus: "cancelled" })] },+ ]),+ ).toEqual([]);+ });++ it("stays quiet for threads it sees for the first time, like on launch or reconnect", () => {+ expect(+ speak([+ { threads: [login({ runStatus: "completed" }), docs({ request: "approval" })] },+ { threads: [login({ runStatus: "completed" }), docs({ request: "approval" })] },+ // The environment drops out while it resyncs, then comes back changed.+ { threads: [] },+ {+ threads: [+ login({ runId: secondRun, runStatus: "failed" }),+ docs({ runStatus: "completed" }),+ ],+ },+ ]),+ ).toEqual([]);+ });++ it("leaves the open thread to its own announcer", () => {+ expect(+ speak([+ { threads: [login(), docs()], open: "env:login" },+ { threads: [login({ runStatus: "completed" }), docs()], open: "env:login" },+ // Switching away from a thread doesn't replay its ending.+ { threads: [login({ runStatus: "completed" }), docs()], open: "env:docs" },+ {+ threads: [login({ runStatus: "completed" }), docs({ request: "input" })],+ open: "env:login",+ },+ ]),+ ).toEqual(["Needs your input: Update docs"]);+ });++ it("keeps a snoozed thread quiet, even after it wakes", () => {+ expect(+ speak([+ { threads: [login({ snoozed: true })] },+ { threads: [login({ snoozed: true, runStatus: "completed" })] },+ { threads: [login({ runStatus: "completed" })] },+ ]),+ ).toEqual([]);+ });++ it("speaks threads that change together in one announcement", () => {+ expect(+ speak([+ { threads: [login(), docs()] },+ { threads: [login({ runStatus: "completed" }), docs({ request: "approval" })] },+ ]),+ ).toEqual(["Done: Fix login redirect. Needs approval: Update docs"]);+ });+});++describe("resolveBackgroundThreadRequest", () => {+ const question = (id: string) => ({+ id: RuntimeRequestId.make(id),+ kind: "user_input" as const,+ createdAt: DateTime.makeUnsafe(0),+ });+ const childApproval = (parentQuestion: string | null) =>+ resolveBackgroundThreadRequest({+ hasPendingApprovals: false,+ hasPendingUserInput: parentQuestion !== null,+ pendingSubagentRequest: "approval",+ source: { pendingRuntimeRequest: parentQuestion === null ? null : question(parentQuestion) },+ });++ it("raises a subagent's request on the parent without borrowing the parent's request id", () => {+ expect(childApproval(null)).toEqual({ request: "approval", requestId: null });+ // The parent's own questions come and go while the child's approval waits.+ expect(+ speak([+ { threads: [login()] },+ { threads: [login(childApproval(null))] },+ { threads: [login(childApproval("question-1"))] },+ { threads: [login(childApproval("question-2"))] },+ { threads: [login(childApproval(null))] },+ ]),+ ).toEqual(["Needs approval: Fix login redirect"]);+ });+});diff --git a/apps/web/src/components/backgroundThreadAnnouncement.ts b/apps/web/src/components/backgroundThreadAnnouncement.tsnew file mode 100644index 00000000000..c04d363f2bd--- /dev/null+++ b/apps/web/src/components/backgroundThreadAnnouncement.ts@@ -0,0 +1,88 @@+import type { OrchestrationV2RunStatus, RunId } from "@t3tools/contracts";++import type { SidebarThreadSummary } from "../types";+import { runOutcomeText, THREAD_STATUS_TEXT } from "./chat/threadActivityAnnouncement";++export interface BackgroundThreadSnapshot {+ readonly key: string;+ readonly title: string;+ readonly request: "approval" | "input" | null;+ /** Null for a subagent's request, which the parent's shell only knows by kind. */+ readonly requestId: string | null;+ readonly runId: RunId | null;+ readonly runStatus: OrchestrationV2RunStatus | null;+ /** The run doing work now, which can be older than a queued run cancelled while it ran. */+ readonly activeRunId: RunId | null;+ /** A snoozed thread stays hidden until its timer, so it stays quiet too. */+ readonly snoozed: boolean;+}++/** The request and its id come from the same source, so a subagent's request never takes the parent's id. */+export function resolveBackgroundThreadRequest(+ thread: Pick<+ SidebarThreadSummary,+ "hasPendingApprovals" | "hasPendingUserInput" | "pendingSubagentRequest"+ > & {+ readonly source: Pick<SidebarThreadSummary["source"], "pendingRuntimeRequest">;+ },+): Pick<BackgroundThreadSnapshot, "request" | "requestId"> {+ const ownRequestId = thread.source.pendingRuntimeRequest?.id ?? null;+ if (thread.hasPendingApprovals) return { request: "approval", requestId: ownRequestId };+ if (thread.pendingSubagentRequest === "approval") return { request: "approval", requestId: null };+ if (thread.hasPendingUserInput) return { request: "input", requestId: ownRequestId };+ if (thread.pendingSubagentRequest === "user_input") return { request: "input", requestId: null };+ return { request: null, requestId: null };+}++interface BackgroundThreadMemoryEntry {+ readonly request: BackgroundThreadSnapshot["request"];+ readonly requestId: string | null;+ /** The last run whose ending is known, so each run's ending is announced once. */+ readonly settledRunId: RunId | null;+}++export type BackgroundThreadMemory = ReadonlyMap<string, BackgroundThreadMemoryEntry>;++/**+ * Decides what a screen reader hears when a thread other than the open one+ * asks for something or ends a run. `threads` holds only threads whose+ * environment is live, so a thread is silent the first time it's seen:+ * opening the app or reconnecting takes a baseline instead of reading out+ * every thread.+ */+export function nextBackgroundThreadAnnouncement(+ previous: BackgroundThreadMemory,+ threads: ReadonlyArray<BackgroundThreadSnapshot>,+ openThreadKey: string | null,+): { readonly memory: BackgroundThreadMemory; readonly announcement: string | null } {+ const memory = new Map<string, BackgroundThreadMemoryEntry>();+ const announcements: string[] = [];+ for (const thread of threads) {+ const before = previous.get(thread.key);+ const outcome = runOutcomeText(thread.runStatus);+ const settled = outcome !== null || thread.runStatus === "rolled_back";+ memory.set(thread.key, {+ request: thread.request,+ requestId: thread.requestId,+ settledRunId: settled ? thread.runId : (before?.settledRunId ?? null),+ });+ if (before === undefined || thread.key === openThreadKey || thread.snoozed) continue;+ if (+ thread.request !== null &&+ (thread.request !== before.request || thread.requestId !== before.requestId)+ ) {+ announcements.push(`${THREAD_STATUS_TEXT[thread.request]}: ${thread.title}`);+ }+ // While another run still works, the latest run's ending (a queued message+ // cancelled before it started) isn't the thread finishing. The shell then+ // only reports the latest run, so the working run's own ending stays quiet.+ const anotherRunWorking = thread.activeRunId !== null && thread.activeRunId !== thread.runId;+ if (outcome !== null && thread.runId !== before.settledRunId && !anotherRunWorking) {+ announcements.push(`${outcome}: ${thread.title}`);+ }+ }+ return {+ memory,+ announcement: announcements.length === 0 ? null : announcements.join(". "),+ };+}diff --git a/apps/web/src/components/chat/ThreadActivityAnnouncer.tsx b/apps/web/src/components/chat/ThreadActivityAnnouncer.tsxindex 0a1f13fcbc0..d82ec08f41c 100644--- a/apps/web/src/components/chat/ThreadActivityAnnouncer.tsx+++ b/apps/web/src/components/chat/ThreadActivityAnnouncer.tsx@@ -1,15 +1,14 @@import { memo, useEffect, useRef } from "react";+import { useLiveRegion } from "../../hooks/useLiveRegion";+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.- */+/** One polite live region for the open thread. */export const ThreadActivityAnnouncer = memo(function ThreadActivityAnnouncer({threadKey,status,@@ -23,14 +22,13 @@ export const ThreadActivityAnnouncer = memo(function ThreadActivityAnnouncer({/** See isDetailBehindShell. */readonly detailBehind: boolean;}) {- const regionRef = useRef<HTMLDivElement>(null);+ const { regionRef, announce, clear } = useLiveRegion();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 = "";+ clear();return;}if (detailBehind) return;@@ -42,15 +40,9 @@ export const ThreadActivityAnnouncer = memo(function ThreadActivityAnnouncer({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]);+ if (previous === null) clear();+ else if (announcement !== null) announce(announcement);+ }, [threadKey, status, requestId, runId, runStatus, detailBehind, announce, clear]);// 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.ts b/apps/web/src/components/chat/threadActivityAnnouncement.tsindex 5e658748dbe..270f4c98964 100644--- a/apps/web/src/components/chat/threadActivityAnnouncement.ts+++ b/apps/web/src/components/chat/threadActivityAnnouncement.ts@@ -3,6 +3,15 @@ import { latestExecutedRun } from "@t3tools/shared/orchestrationV2ThreadError";export type ThreadActivityStatus = "working" | "approval" | "input" | "idle";+/** Background threads say these too, so a status sounds the same wherever it's heard. */+export const THREAD_STATUS_TEXT = {+ approval: "Needs approval",+ input: "Needs your input",+ done: "Done",+ failed: "Failed",+ stopped: "Stopped",+} as const;+export interface ThreadActivitySnapshot {readonly status: ThreadActivityStatus;/** The pending approval or question, when there is one. */@@ -37,15 +46,15 @@ const STARTING_RUN_STATUSES: ReadonlySet<OrchestrationV2RunStatus | null> = new"starting",]);-function runOutcomeText(status: OrchestrationV2RunStatus | null): string | null {+export function runOutcomeText(status: OrchestrationV2RunStatus | null): string | null {switch (status) {case "completed":- return "Done";+ return THREAD_STATUS_TEXT.done;case "failed":- return "Failed";+ return THREAD_STATUS_TEXT.failed;case "interrupted":case "cancelled":- return "Stopped";+ return THREAD_STATUS_TEXT.stopped;default:return null;}@@ -129,11 +138,11 @@ export function nextThreadAnnouncement(next.status === "approval"? previous.snapshot.status === "approval" && previous.snapshot.requestId === next.requestId? null- : "Needs approval"+ : THREAD_STATUS_TEXT.approval: next.status === "input"? previous.snapshot.status === "input" && previous.snapshot.requestId === next.requestId? null- : "Needs your input"+ : THREAD_STATUS_TEXT.input: turnStarted? "Working": null;diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsxindex 51d913f61b9..4a276b0ee73 100644--- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx+++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx@@ -1342,14 +1342,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP) : topStatus.icon === "done" ? (<CircleCheckIcon aria-hidden className="size-4 shrink-0" />) : null}- {/* The label alone is the live region: a role="status"- wrapper around the ticking duration would make- 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>+ {/* Not a live region: a collapsed sidebar is inert, so+ BackgroundThreadAnnouncer and the open thread's+ timeline speak status changes instead. */}+ {topStatus.label}{status === "working" ? (<span aria-hidden><WorkingDuration startedAt={resolveWorkingStartedAt(thread)} />diff --git a/apps/web/src/hooks/useLiveRegion.ts b/apps/web/src/hooks/useLiveRegion.tsnew file mode 100644index 00000000000..edc43cf69ce--- /dev/null+++ b/apps/web/src/hooks/useLiveRegion.ts@@ -0,0 +1,41 @@+import { useEffect, useRef } from "react";++// NVDA reads a polite region's leftover text again when focus returns from a+// dialog, so an announcement is cleared once it has had time to be spoken.+// Clearing doesn't cut off speech that already started.+const CLEAR_AFTER_MS = 7_000;++/** A polite live region written straight to the DOM, so speaking never re-renders. */+export function useLiveRegion() {+ const regionRef = useRef<HTMLDivElement>(null);+ const clearTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ const cancelClear = () => {+ if (clearTimerRef.current !== null) clearTimeout(clearTimerRef.current);+ clearTimerRef.current = null;+ };++ const clear = () => {+ cancelClear();+ if (regionRef.current !== null) regionRef.current.textContent = "";+ };++ const announce = (text: string) => {+ const region = regionRef.current;+ if (region === null) return;+ cancelClear();+ // Screen readers ignore a write that leaves the text unchanged, so a repeat+ // gets a trailing non-breaking space to count as new.+ region.textContent = region.textContent === text ? `${text} ` : text;+ clearTimerRef.current = setTimeout(clear, CLEAR_AFTER_MS);+ };++ useEffect(+ () => () => {+ if (clearTimerRef.current !== null) clearTimeout(clearTimerRef.current);+ },+ [],+ );++ return { regionRef, announce, clear };+}diff --git a/apps/web/src/state/shell.ts b/apps/web/src/state/shell.tsindex 38269987e75..6620630824d 100644--- a/apps/web/src/state/shell.ts+++ b/apps/web/src/state/shell.ts@@ -49,6 +49,23 @@ export function useEnvironmentShellHasSnapshot(environmentId: EnvironmentId | nu);}+let previousLiveEnvironmentIds: ReadonlySet<EnvironmentId> = new Set();+/** Environments whose threads reflect the server now, not a cache or a resync in flight. */+export const liveShellEnvironmentIdsAtom = Atom.make((get) => {+ const next = new Set<EnvironmentId>();+ for (const environmentId of enabledEnvironmentIds(get(environmentCatalog.catalogValueAtom))) {+ if (get(environmentShell.statusAtom(environmentId)) === "live") next.add(environmentId);+ }+ if (+ next.size === previousLiveEnvironmentIds.size &&+ [...next].every((environmentId) => previousLiveEnvironmentIds.has(environmentId))+ ) {+ return previousLiveEnvironmentIds;+ }+ previousLiveEnvironmentIds = next;+ return next;+}).pipe(Atom.withLabel("web-live-shell-environment-ids"));+export const allEnvironmentShellsBootstrappedAtom = Atom.make((get) => {const catalog = AsyncResult.value(get(environmentCatalog.catalogAtom));if (Option.isNone(catalog)) {