TypeScript
fix(web): screen readers say which thread a shortcut switched to (#23676)
shivam7f7daad98503
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsxindex eaf958fa2f5..6df3e967eaf 100644--- a/apps/web/src/components/chat/ChatComposer.tsx+++ b/apps/web/src/components/chat/ChatComposer.tsx@@ -3765,7 +3765,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)<ComposerContextActionsContext value={composerContextActions}><ComposerPromptEditordraftKey={composerDraftTargetKey}- ariaLabel="Message"+ // Switching threads lands focus here, so the label names the thread.+ ariaLabel={activeThread ? `Message ${activeThread.title}` : "Message"}suggestionListId={composerSuggestionListId}activeSuggestionId={composerSuggestionListVisible && activeComposerMenuItemdiff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsxindex 924f7455fc3..3b9e7b9cf22 100644--- a/apps/web/src/components/chat/ModelPickerContent.tsx+++ b/apps/web/src/components/chat/ModelPickerContent.tsx@@ -52,6 +52,7 @@ import {useEnvironmentModelPreferences,useToggleEnvironmentModelFavorite,} from "~/hooks/useSettings";+import { announce } from "~/lib/announce";import { cn } from "~/lib/utils";import { getVirtualizedScrollFadeClassName } from "../ui/scroll-area";import { TooltipProvider } from "../ui/tooltip";@@ -485,26 +486,26 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {modelSlug: string,instanceId: ProviderInstanceId,additive = false,- ) => {+ ): string | null => {if (getModelDisabledReason?.(instanceId, modelSlug)) {- return;+ return null;}const options = modelOptionsByInstance.get(instanceId);if (!options) {- return;+ return null;}const entry = instanceEntries.find((candidate) => candidate.instanceId === instanceId);if (!entry) {- return;+ return null;}const resolvedModel = resolveSelectableModel(entry.driverKind, modelSlug, options);- if (resolvedModel) {- if (additive && onToggleModel) {- onToggleModel(instanceId, resolvedModel);- } else {- onInstanceModelChange(instanceId, resolvedModel);- }+ if (!resolvedModel) return null;+ if (additive && onToggleModel) {+ onToggleModel(instanceId, resolvedModel);+ } else {+ onInstanceModelChange(instanceId, resolvedModel);}+ return resolvedModel;};const modelJumpShortcutContext = {@@ -773,6 +774,10 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {});setSearchQuery("");handleSelectInstance(next);+ announce(+ next === "favorites" ? "Favorites" : (entryByInstanceId.get(next)?.displayName ?? next),+ "model-picker",+ );return;}const jumpIndex = modelPickerJumpIndexFromCommand(command ?? "");@@ -790,7 +795,12 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {if (!model) {return;}- handleModelSelect(model.slug, model.instanceId);+ const selectedSlug = handleModelSelect(model.slug, model.instanceId);+ if (selectedSlug === null) return;+ const name = flatModels.find(+ (item) => item.slug === selectedSlug && item.instanceId === model.instanceId,+ )?.name;+ announce(`Model: ${name ?? selectedSlug}`, "model-picker");};return (diff --git a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx b/apps/web/src/components/chat/OpenInPicker.browser.test.tsxindex bb59ca99fe0..eafb73eb5cd 100644--- a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx+++ b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx@@ -1,9 +1,10 @@import { AuthOrchestrationOperateScope, EnvironmentId, type EditorId } from "@t3tools/contracts";import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";+import { Cause } from "effect";import { AsyncResult } from "effect/reactivity";import { describe, expect, it, vi } from "vite-plus/test";-import { act, render as renderUi } from "../../../test/render";+import { act, fakeTimers, render as renderUi } from "../../../test/render";import type { RemoteOpenState } from "../../remoteOpen";const state = vi.hoisted(() => ({@@ -181,3 +182,36 @@ describe("host editor access", () => {expect((await pressOpenFavorite()).defaultPrevented).toBe(false);});});++describe("open in editor announcement", () => {+ it("speaks only after the shortcut opened the editor, from the picker or the fallback", async () => {+ await using fixture = await setup();+ const { screen, renderPicker, pressOpenFavorite, FavoriteEditorFallback } = fixture;+ state.allowed.add(selected);+ await renderPicker();+ using _timers = fakeTimers();+ const regions = () => [...document.querySelectorAll('body > [aria-live="polite"]')];+ const spoken = async () => {+ await act(async () => vi.runAllTimers());+ return regions()+ .map((region) => region.textContent)+ .join("");+ };+ const refuse = () =>+ state.run.mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("No editor"))));++ refuse();+ await pressOpenFavorite();+ expect(await spoken()).toBe("");+ await pressOpenFavorite();+ expect(await spoken()).toBe("Opened in VS Code");++ for (const region of regions()) region.textContent = "";+ await act(async () => screen.rerender(<FavoriteEditorFallback />));+ refuse();+ await pressOpenFavorite();+ expect(await spoken()).toBe("");+ await pressOpenFavorite();+ expect(await spoken()).toBe("Opened in VS Code");+ });+});diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsxindex 900879ae049..8bc6a884fa3 100644--- a/apps/web/src/components/chat/OpenInPicker.tsx+++ b/apps/web/src/components/chat/OpenInPicker.tsx@@ -58,6 +58,7 @@ import {RustRoverIcon,WebStormIcon,} from "../JetBrainsIcons";+import { announce } from "~/lib/announce";import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";import { shellEnvironment } from "~/state/shell";import { useAtomCommand } from "~/state/use-atom-command";@@ -240,11 +241,11 @@ export const OpenInPicker = memo(function OpenInPicker({const effectiveEditors = remote.mode === "local-exec" ? availableEditors : remoteCapableEditors;const [preferredEditor, setPreferredEditor] = usePreferredEditor(effectiveEditors);- const openInEditor = (editorId: EditorId | null) => {- if (!openInCwd) return;+ const openInEditor = async (editorId: EditorId | null): Promise<boolean> => {+ if (!openInCwd) return false;const editor = editorId ?? preferredEditor;- if (!editor) return;- if (remote.mode === "remote-unavailable") return;+ if (!editor) return false;+ if (remote.mode === "remote-unavailable") return false;if (remote.mode === "remote-links") {const url = buildRemoteOpenUrl({editor,@@ -252,17 +253,16 @@ export const OpenInPicker = memo(function OpenInPicker({absolutePath: openInCwd,isFile: openInCwdIsFile,});- if (url === undefined) return;+ if (url === undefined) return false;// Only record hint-seen/preferred when the shell actually accepted// the URL (an older desktop build can refuse the editor scheme).- void openRemoteEditorUrl(url).then((opened) => {- if (!opened) return;- markRemoteHintSeen();- setPreferredEditor(editor);- });- return;+ const opened = await openRemoteEditorUrl(url);+ if (!opened) return false;+ markRemoteHintSeen();+ setPreferredEditor(editor);+ return true;}- if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return;+ if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;const result = openInEditorMutation({environmentId,input: {@@ -272,7 +272,7 @@ export const OpenInPicker = memo(function OpenInPicker({},});setPreferredEditor(editor);- return result;+ return (await result)._tag === "Success";};const openFavoriteEditorShortcutLabel = shortcutLabelForCommand(@@ -293,7 +293,10 @@ export const OpenInPicker = memo(function OpenInPicker({return;e.preventDefault();- void openInEditor(preferredEditor);+ const label = editorLabelForPlatform(preferredEditor, navigator.platform);+ void openInEditor(preferredEditor).then((opened) => {+ if (opened) announce(`Opened in ${label}`);+ });};window.addEventListener("keydown", handler, true);return () => window.removeEventListener("keydown", handler, true);diff --git a/apps/web/src/components/chat/OpenInPickerShortcut.ts b/apps/web/src/components/chat/OpenInPickerShortcut.tsindex 6d567b160d7..7cd000e83dc 100644--- a/apps/web/src/components/chat/OpenInPickerShortcut.ts+++ b/apps/web/src/components/chat/OpenInPickerShortcut.ts@@ -2,7 +2,9 @@ import type { EditorId, EnvironmentId, ResolvedKeybindingsConfig } from "@t3toolimport { useEffect } from "react";import { usePreferredEditor } from "../../editorPreferences";+import { editorLabelForPlatform } from "../../editorLabels";import { isOpenFavoriteEditorShortcut } from "../../keybindings";+import { announce } from "../../lib/announce";import { useRemoteOpenState } from "../../remoteOpen";import { shellEnvironment } from "../../state/shell";import { useAtomCommand } from "../../state/use-atom-command";@@ -31,12 +33,15 @@ export function useOpenFavoriteEditorShortcut({if (!openInCwd || !preferredEditor) return;event.preventDefault();+ const label = editorLabelForPlatform(preferredEditor, navigator.platform);void openInEditorMutation({environmentId,input: {cwd: openInCwd,editor: preferredEditor,},+ }).then((result) => {+ if (result._tag === "Success") announce(`Opened in ${label}`);});};window.addEventListener("keydown", handler);diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsxindex c169ac10e6b..e836a92f587 100644--- a/apps/web/src/components/chat/ProviderModelPicker.tsx+++ b/apps/web/src/components/chat/ProviderModelPicker.tsx@@ -300,9 +300,11 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {terminalOpen={props.terminalOpen ?? false}onRequestClose={() => setIsMenuOpen(false)}{...(props.onOpenProviderSetup ? { onOpenProviderSetup: props.onOpenProviderSetup } : {})}- {...(props.getModelDisabledReason- ? { getModelDisabledReason: props.getModelDisabledReason }- : {})}+ getModelDisabledReason={(instanceId, model) =>+ props.disabled+ ? "Model picker is disabled"+ : (props.getModelDisabledReason?.(instanceId, model) ?? null)+ }onInstanceModelChange={handleInstanceModelChange}/>{props.selectedModels === undefined ? (diff --git a/apps/web/src/components/sidebar/SidebarThreadUndoNotice.browser.test.tsx b/apps/web/src/components/sidebar/SidebarThreadUndoNotice.browser.test.tsxnew file mode 100644index 00000000000..049ef07ad80--- /dev/null+++ b/apps/web/src/components/sidebar/SidebarThreadUndoNotice.browser.test.tsx@@ -0,0 +1,37 @@+import { describe, expect, it, vi } from "vite-plus/test";++import { act, fakeTimers, render } from "../../../test/render";+import { useThreadUndoNotice } from "../../hooks/showThreadUndoNotice";+import { SidebarThreadUndoNotice } from "./SidebarThreadUndoNotice";++const spoken = () =>+ [...document.querySelectorAll('body > [aria-live="polite"]')]+ .map((region) => region.textContent)+ .join("");++describe("SidebarThreadUndoNotice", () => {+ it("speaks the notice, and drops it when the notice clears before it is spoken", async () => {+ using _notice = { [Symbol.dispose]: () => useThreadUndoNotice.setState({ notice: null }) };+ await using _screen = await render(<SidebarThreadUndoNotice />);+ using _timers = fakeTimers();+ const showSettled = () =>+ act(async () =>+ useThreadUndoNotice.setState({+ notice: { action: "Settled", count: 1, undo: async () => {} },+ }),+ );++ await showSettled();+ await act(async () => vi.advanceTimersByTime(300));+ expect(spoken()).toMatch(/^Settled 1 thread, /);++ await act(async () => useThreadUndoNotice.setState({ notice: null }));+ for (const region of document.querySelectorAll('body > [aria-live="polite"]')) {+ region.textContent = "";+ }+ await showSettled();+ await act(async () => useThreadUndoNotice.setState({ notice: null }));+ await act(async () => vi.advanceTimersByTime(300));+ expect(spoken()).toBe("");+ });+});diff --git a/apps/web/src/components/sidebar/SidebarThreadUndoNotice.tsx b/apps/web/src/components/sidebar/SidebarThreadUndoNotice.tsxindex 7f3f5bfe77e..71818e154a1 100644--- a/apps/web/src/components/sidebar/SidebarThreadUndoNotice.tsx+++ b/apps/web/src/components/sidebar/SidebarThreadUndoNotice.tsx@@ -1,7 +1,9 @@import { useAtomValue } from "@effect/atom-react";+import { useEffect } from "react";import { undoLatestThreadAction, useThreadUndoNotice } from "../../hooks/showThreadUndoNotice";import { shortcutLabelForCommand } from "../../keybindings";+import { announce, cancelAnnouncement } from "../../lib/announce";import { primaryServerKeybindingsAtom } from "../../state/server";import { Alert, AlertDescription } from "../ui/alert";import { InlineButton } from "../ui/button";@@ -10,17 +12,25 @@ export function SidebarThreadUndoNotice() {const notice = useThreadUndoNotice((state) => state.notice);const keybindings = useAtomValue(primaryServerKeybindingsAtom);- if (!notice) return null;const shortcut = shortcutLabelForCommand(keybindings, "thread.undo");- const noun = `${notice.action === "Discarded" ? "draft" : "thread"}${notice.count === 1 ? "" : "s"}`;+ const undoLabel = shortcut ? `${shortcut} to undo` : "Undo";+ const summary = notice+ ? `${notice.action} ${notice.count} ${notice.action === "Discarded" ? "draft" : "thread"}${notice.count === 1 ? "" : "s"}`+ : null;++ // A live region that mounts already filled is skipped by screen readers, and settling+ // usually moves focus to the next thread at the same moment.+ useEffect(() => {+ if (summary) announce(`${summary}, ${undoLabel}`, "thread-undo-notice");+ else cancelAnnouncement("thread-undo-notice");+ }, [summary, undoLabel]);++ if (!summary) return null;return (- <Alert role="status" variant="sidebar">+ <Alert role="group" variant="sidebar"><AlertDescription>- {notice.action} {notice.count} {noun},{" "}- <InlineButton onClick={undoLatestThreadAction}>- {shortcut ? `${shortcut} to undo` : "Undo"}- </InlineButton>+ {summary}, <InlineButton onClick={undoLatestThreadAction}>{undoLabel}</InlineButton></AlertDescription></Alert>);diff --git a/apps/web/src/lib/announce.browser.test.ts b/apps/web/src/lib/announce.browser.test.tsnew file mode 100644index 00000000000..72406754e2b--- /dev/null+++ b/apps/web/src/lib/announce.browser.test.ts@@ -0,0 +1,62 @@+import { describe, expect, it, vi } from "vite-plus/test";++import { fakeTimers } from "../../test/render";+import { announce, cancelAnnouncement } from "./announce";++function spokenText() {+ return Array.from(document.querySelectorAll('[aria-live="polite"]'), (region) =>+ region.textContent?.trim(),+ ).filter(Boolean);+}++describe("announce", () => {+ it("waits for focus to settle, then speaks waiting messages together", () => {+ using _timers = fakeTimers();+ const composer = document.createElement("textarea");+ document.body.append(composer);+ using _composer = { [Symbol.dispose]: () => composer.remove() };++ announce("Settled 1 thread, Ctrl+Z to undo");+ announce("Model: Claude Sonnet 5.5");+ vi.advanceTimersByTime(200);+ composer.focus();+ vi.advanceTimersByTime(200);+ expect(spokenText()).toEqual([]);++ vi.advanceTimersByTime(50);+ expect(spokenText()).toEqual(["Settled 1 thread, Ctrl+Z to undo. Model: Claude Sonnet 5.5"]);+ });++ it("speaks the same message twice in a row through the other region", () => {+ using _timers = fakeTimers();+ const regionTexts = () =>+ Array.from(document.querySelectorAll('[aria-live="polite"]'), (region) => region.textContent);++ announce("Claude");+ vi.runAllTimers();+ const first = regionTexts();+ announce("Claude");+ vi.runAllTimers();++ expect(regionTexts()).toEqual([...first].reverse());+ expect(regionTexts()).toContain("Claude");+ });++ it("replaces a waiting message from the same source", () => {+ using _timers = fakeTimers();++ announce("Settled 1 thread, Ctrl+Z to undo", "undo");+ announce("Opening in VS Code");+ announce("Settled 2 threads, Ctrl+Z to undo", "undo");+ vi.runAllTimers();++ expect(spokenText()).toEqual(["Opening in VS Code. Settled 2 threads, Ctrl+Z to undo"]);++ announce("Settled 1 thread, Ctrl+Z to undo", "undo");+ announce("Opening in Zed");+ cancelAnnouncement("undo");+ vi.runAllTimers();++ expect(spokenText()).toEqual(["Opening in Zed"]);+ });+});diff --git a/apps/web/src/lib/announce.ts b/apps/web/src/lib/announce.tsnew file mode 100644index 00000000000..20036b82a6d--- /dev/null+++ b/apps/web/src/lib/announce.ts@@ -0,0 +1,54 @@+// Screen readers skip a live region that appears already filled, and moving focus cuts off+// whatever they were saying. So the regions exist before the first message lands, and+// messages wait until focus has stayed put for a moment, then are spoken together.+const FOCUS_SETTLE_MS = 250;++let regions: readonly [HTMLElement, HTMLElement] | null = null;+let pending: { message: string; source: string | undefined }[] = [];+let flushTimer: ReturnType<typeof setTimeout> | undefined;++function scheduleFlush() {+ clearTimeout(flushTimer);+ flushTimer = setTimeout(flush, FOCUS_SETTLE_MS);+}++function flush() {+ if (!regions || pending.length === 0) return;+ const [first, second] = regions;+ // Alternating between two regions lets the same message be spoken twice in a row.+ const target = first.textContent ? second : first;+ first.textContent = "";+ second.textContent = "";+ target.textContent = pending.map((entry) => entry.message).join(". ");+ pending = [];+}++function createRegion() {+ const region = document.createElement("div");+ region.className = "sr-only";+ region.setAttribute("aria-live", "polite");+ region.setAttribute("aria-atomic", "true");+ document.body.append(region);+ return region;+}++/**+ * Tells screen reader users what an action did when focus alone doesn't show it. A message+ * replaces one still waiting from the same `source`, so a superseded status isn't read out.+ */+export function announce(message: string, source?: string) {+ if (!regions) {+ regions = [createRegion(), createRegion()];+ document.addEventListener("focusin", () => {+ if (pending.length > 0) scheduleFlush();+ });+ }+ if (source !== undefined) pending = pending.filter((entry) => entry.source !== source);+ if (pending.at(-1)?.message !== message) pending.push({ message, source });+ scheduleFlush();+}++/** Drops a message from `source` that hasn't been spoken yet, once it no longer applies. */+export function cancelAnnouncement(source: string) {+ pending = pending.filter((entry) => entry.source !== source);+}