From 235ea3323a4deba1cd75cd5846f0f2025a82302c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 16:06:59 +0000 Subject: [PATCH 1/9] fix(ui-kit,ui-react): close non-modal panels on Android back (#2577) A native modal dialog receives Android back as a close request; the non-modal surfaces listened for an Escape keydown only, so on an installed Android PWA the back gesture skipped the open panel and left the app. One helper (`watchCloseRequests`, ui-kit internal) now owns close requests for a non-modal surface: while armed it keeps a CloseWatcher and hands its close to the surface, re-arming when the surface stays open; without CloseWatcher, or while disarmed for #2582's drill-in history, an Escape keydown stands in. - Non-modal Overlay entries (the phone destination drawers) get a watcher from the overlay stack, whose document Escape now steps aside for a watching top entry, so one Escape never closes twice. - The Settings and Files panes and the dictation field use it in place of their own listeners. A modal over them still closes first; a finishing take (D5) and closedBy="none" survive and re-arm. - Inner Escape consumers inside panels now prevent the keydown as well as stopping it (share menu, passkey rename, the graph node list), since Chromium raises the close request unless the keydown was prevented. Co-Authored-By: Claude Opus 5.5 --- .../2577-android-back-close-requests.md | 6 + api-report/ui-kit.txt | 3 + packages/ui-kit/src/chrome/Overlay.tsx | 9 +- packages/ui-kit/src/internal.ts | 1 + packages/ui-kit/src/internal/close-request.ts | 120 +++++++ packages/ui-kit/src/internal/overlay-stack.ts | 28 +- packages/ui-kit/tests/overlay-stack.test.ts | 8 +- packages/ui-kit/vitest.config.ts | 2 +- .../src/components/files/file-panel.tsx | 18 +- .../src/components/graph/graph-scene.tsx | 4 +- .../src/components/layout/slide-panel.tsx | 20 +- .../src/components/settings/passkey-list.tsx | 4 +- .../src/components/share/share-menu.tsx | 9 +- .../src/components/voice/dictation-field.tsx | 21 +- .../ui-react/src/lib/use-close-request.ts | 19 ++ .../tests/browser/close-requests.pointer.tsx | 306 ++++++++++++++++++ 16 files changed, 526 insertions(+), 52 deletions(-) create mode 100644 .changeset/2577-android-back-close-requests.md create mode 100644 packages/ui-kit/src/internal/close-request.ts create mode 100644 packages/ui-react/src/lib/use-close-request.ts create mode 100644 packages/ui-react/tests/browser/close-requests.pointer.tsx diff --git a/.changeset/2577-android-back-close-requests.md b/.changeset/2577-android-back-close-requests.md new file mode 100644 index 0000000000..d064ee8677 --- /dev/null +++ b/.changeset/2577-android-back-close-requests.md @@ -0,0 +1,6 @@ +--- +"@schlessera/brain-ui-kit": patch +"@schlessera/brain-ui-react": patch +--- + +Android back now closes an open panel instead of leaving the app. The phone destination drawers (Sessions, Files, Settings), the Settings and Files panes from 900px, and the dictation field each take a close request (Escape, the back gesture) through one shared `CloseWatcher` helper, close once and return focus to their opener. Where `CloseWatcher` is missing, Escape still closes them. A modal opened over a panel still closes first. A dictation take that is finishing, or a panel that cannot be dismissed, ignores the request. Escape in the share menu or the passkey rename field inside a panel now closes only that menu or field. diff --git a/api-report/ui-kit.txt b/api-report/ui-kit.txt index 72c392ed21..1971aae4f7 100644 --- a/api-report/ui-kit.txt +++ b/api-report/ui-kit.txt @@ -447,6 +447,8 @@ export "./brand" (./src/brand.ts) export "./brand/*" (./assets/brand/*) [asset] export "./internal" (./src/internal.ts) + type CloseRequestOptions + type CloseRequestWatch LIGHT_TOKENS PRINT_TOKENS TOKENS @@ -458,6 +460,7 @@ export "./internal" (./src/internal.ts) canvas mapViewBounds printThemeCss + watchCloseRequests export "./links" (./src/links.ts) LINK_URL_MAX diff --git a/packages/ui-kit/src/chrome/Overlay.tsx b/packages/ui-kit/src/chrome/Overlay.tsx index 6044dd8cb9..48899e4d99 100644 --- a/packages/ui-kit/src/chrome/Overlay.tsx +++ b/packages/ui-kit/src/chrome/Overlay.tsx @@ -88,10 +88,15 @@ export function Overlay(p: OverlayProps) { openingFocus.current ??= { opener: doc.activeElement as HTMLElement | null }; const { opener } = openingFocus.current; let active = true; - const request = (reason: OverlayCloseReason) => { + /** Returns whether the overlay was asked to close; `closedBy="none"` and a covered overlay stay. */ + const request = (reason: OverlayCloseReason): boolean => { cancelSwipe(); - if (active && isTopmost(doc, id.current) && latest.current.closedBy !== "none") latest.current.onClose(reason); + if (!active || !isTopmost(doc, id.current) || latest.current.closedBy === "none") return false; + latest.current.onClose(reason); + return true; }; + // A non-modal overlay's close request is its watcher's (#2577): Escape or + // Android back alike, reported with Escape's reason. const unregister = registerOverlay(doc, { id: id.current, modal, escape: () => request("escape") }); const focusInitial = () => { const body = surface.current?.querySelector(".bk-overlay-body"); diff --git a/packages/ui-kit/src/internal.ts b/packages/ui-kit/src/internal.ts index fb93dc57e9..caef2ae57d 100644 --- a/packages/ui-kit/src/internal.ts +++ b/packages/ui-kit/src/internal.ts @@ -4,5 +4,6 @@ * version. See docs/decisions/public-export-boundary.md. */ export { mapViewBounds } from "./blocks/MapView.js"; +export { watchCloseRequests, type CloseRequestOptions, type CloseRequestWatch } from "./internal/close-request.js"; export { LIGHT_TOKENS, PRINT_TOKENS, TOKENS, canvas, printThemeCss, type TokenName } from "./tokens.js"; export { TranscriptQualifiers, TranscriptSymbols, TranscriptReadingScope, type TranscriptQualifiersProps } from "./conversation/TranscriptQualifiers.js"; diff --git a/packages/ui-kit/src/internal/close-request.ts b/packages/ui-kit/src/internal/close-request.ts new file mode 100644 index 0000000000..bbdcafbd0c --- /dev/null +++ b/packages/ui-kit/src/internal/close-request.ts @@ -0,0 +1,120 @@ +/** + * Close requests for a non-modal surface (#2577): Escape, Android back and + * the other platform close gestures, as D52 N2 asks ("Esc, back, or the + * Close control closes a panel and returns focus to its opener"). + * + * A native modal `` already receives close requests. A non-modal + * panel does not: the platform mechanism is `CloseWatcher` (Chrome Android + * 126, Samsung 28, Firefox Android 149). While armed, this keeps one watcher + * for the surface and hands its `close` to `request`. Without `CloseWatcher`, + * or while disarmed, an Escape keydown stands in for it. + * + * `request` returns whether the surface closed. When it stays open + * (`closedBy="none"`, a dictation take that is finishing), the watcher has + * already been spent by the platform, so a new one is armed in its place and + * the next close request reaches this surface again. + * + * Arm and disarm are for drill-in history (#2582): while a panel has drill-in + * entries above its root, its watcher is disarmed, so Android back reaches + * `popstate` and pops one entry; at the root it is armed again. Escape keeps + * closing the panel at every depth (D52 N2), through the keydown fallback. + * + * DOM coordination only, shared first-party through `/internal`: not + * supported API. + */ + +/** The platform close watcher, as far as this helper uses it. */ +interface PlatformCloseWatcher { + onclose: ((event: Event) => void) | null; + destroy(): void; +} +type CloseWatcherConstructor = new () => PlatformCloseWatcher; + +export interface CloseRequestWatch { + /** Route close requests to the surface. A no-op while already armed. */ + arm(): void; + /** + * Let close requests pass to the page (Android back reaches `popstate`). + * Escape still closes the surface through the keydown fallback. + */ + disarm(): void; + /** Whether close requests currently reach the surface through a watcher. */ + readonly watching: boolean; + /** Stop for good: the watcher and the keydown fallback are removed. */ + destroy(): void; +} + +export interface CloseRequestOptions { + /** + * Handle Escape when no watcher is armed (default true). The overlay stack + * passes false: it keeps one document listener that hands Escape to its + * topmost entry only, so stacked surfaces never each take it. + */ + escape?: boolean; + /** Start disarmed (default armed). */ + armed?: boolean; +} + +function watcherConstructor(view: Window | null): CloseWatcherConstructor | null { + const candidate = (view as (Window & { CloseWatcher?: unknown }) | null)?.CloseWatcher; + return typeof candidate === "function" ? (candidate as CloseWatcherConstructor) : null; +} + +/** Watch close requests for one open surface in `document`; destroy it on close or unmount. */ +export function watchCloseRequests(document: Document, request: () => boolean, options: CloseRequestOptions = {}): CloseRequestWatch { + const Watcher = watcherConstructor(document.defaultView); + let armed = options.armed ?? true; + let destroyed = false; + let watcher: PlatformCloseWatcher | null = null; + + const create = () => { + if (!Watcher || !armed || destroyed || watcher) return; + const created = new Watcher(); + created.onclose = () => { + // The platform destroys a watcher once it closes; drop our reference + // first, so the surface's request can re-enter arm() or destroy(). + if (watcher === created) watcher = null; + if (destroyed) return; + const closed = request(); + if (!closed) create(); + }; + watcher = created; + }; + const release = () => { + const current = watcher; + watcher = null; + if (current) { + current.onclose = null; + current.destroy(); + } + }; + const keys = (event: KeyboardEvent) => { + // With an armed watcher, Escape is the platform's close request and + // arrives through the watcher; handling it here too would close twice. + if (watcher || destroyed || event.key !== "Escape" || event.defaultPrevented || event.isComposing) return; + event.preventDefault(); + request(); + }; + if (options.escape ?? true) document.addEventListener("keydown", keys); + create(); + + return { + arm() { + armed = true; + create(); + }, + disarm() { + armed = false; + release(); + }, + get watching() { + return watcher !== null; + }, + destroy() { + if (destroyed) return; + destroyed = true; + release(); + document.removeEventListener("keydown", keys); + }, + }; +} diff --git a/packages/ui-kit/src/internal/overlay-stack.ts b/packages/ui-kit/src/internal/overlay-stack.ts index 1539694125..106dbcfcee 100644 --- a/packages/ui-kit/src/internal/overlay-stack.ts +++ b/packages/ui-kit/src/internal/overlay-stack.ts @@ -1,18 +1,30 @@ +import { watchCloseRequests, type CloseRequestWatch } from "./close-request.js"; + /** DOM coordination only: each document owns one ordered overlay registry. */ interface Entry { id: symbol; modal: boolean; - escape: () => void; + /** A close request (Escape, Android back) for this entry; returns whether it closed. */ + escape: () => boolean; +} +interface Registered extends Entry { + /** + * A non-modal entry's close watcher (#2577). A modal `` receives + * close requests natively; a non-modal surface needs one of its own. + */ + watch: CloseRequestWatch | null; } -const stacks = new WeakMap void }>(); +const stacks = new WeakMap void }>(); export function registerOverlay(document: Document, entry: Entry): () => void { let stack = stacks.get(document); if (!stack) { - const entries: Entry[] = []; + const entries: Registered[] = []; const keys = (event: KeyboardEvent) => { const top = entries.at(-1); - if (event.key !== "Escape" || event.defaultPrevented || event.isComposing || !top || top.modal) return; + // A watching top entry receives Escape as the platform's close request, + // through its watcher: taking it here as well would close twice. + if (event.key !== "Escape" || event.defaultPrevented || event.isComposing || !top || top.modal || top.watch?.watching) return; event.preventDefault(); event.stopPropagation(); top.escape(); @@ -23,12 +35,16 @@ export function registerOverlay(document: Document, entry: Entry): () => void { } // Nested layout effects run child-first when opened in one commit. Keep // this same order as showModal(): the parent opens last and owns the top layer. - stack.entries.push(entry); + // One document listener hands Escape to the topmost entry only, so the + // watcher brings no keydown fallback of its own (`escape: false`). + const registered: Registered = { ...entry, watch: entry.modal ? null : watchCloseRequests(document, entry.escape, { escape: false }) }; + stack.entries.push(registered); let removed = false; return () => { if (removed) return; removed = true; - const index = stack.entries.indexOf(entry); + registered.watch?.destroy(); + const index = stack.entries.indexOf(registered); if (index !== -1) stack.entries.splice(index, 1); if (!stack.entries.length) { document.removeEventListener("keydown", stack.keys); diff --git a/packages/ui-kit/tests/overlay-stack.test.ts b/packages/ui-kit/tests/overlay-stack.test.ts index b110746fb7..d47e8bc938 100644 --- a/packages/ui-kit/tests/overlay-stack.test.ts +++ b/packages/ui-kit/tests/overlay-stack.test.ts @@ -8,8 +8,8 @@ test("only the last open entry receives document Escape; removal restores the pr const doc = win.document as unknown as Document; const first = Symbol(); const second = Symbol(); let a = 0; let b = 0; - const removeA = registerOverlay(doc, { id: first, modal: false, escape: () => a++ }); - const removeB = registerOverlay(doc, { id: second, modal: false, escape: () => b++ }); + const removeA = registerOverlay(doc, { id: first, modal: false, escape: () => (a++, true) }); + const removeB = registerOverlay(doc, { id: second, modal: false, escape: () => (b++, true) }); const escape = () => win.document.dispatchEvent(new win.KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true })); expect(isTopmost(doc, second)).toBe(true); escape(); @@ -22,8 +22,8 @@ test("a modal above a panel and a consumed Escape leave the panel alone", () => // Mutation: remove top.modal check → modal blocks panel assertion. const win = new Window(); const doc = win.document as unknown as Document; let calls = 0; - const remove = registerOverlay(doc, { id: Symbol(), modal: false, escape: () => calls++ }); - const removeModal = registerOverlay(doc, { id: Symbol(), modal: true, escape: () => calls++ }); + const remove = registerOverlay(doc, { id: Symbol(), modal: false, escape: () => (calls++, true) }); + const removeModal = registerOverlay(doc, { id: Symbol(), modal: true, escape: () => (calls++, true) }); win.document.dispatchEvent(new win.KeyboardEvent("keydown", { key: "Escape", cancelable: true })); expect(calls, "modal blocks panel").toBe(0); removeModal(); diff --git a/packages/ui-kit/vitest.config.ts b/packages/ui-kit/vitest.config.ts index 3c73ed6cfc..55e4aaaa1a 100644 --- a/packages/ui-kit/vitest.config.ts +++ b/packages/ui-kit/vitest.config.ts @@ -102,7 +102,7 @@ const railProject = (mode: "fine" | "coarse" | "mixed") => ({ // contrast (#974) and the palette's reason rows (#1106) are measured // under all three pointers as well, and so is FilterRow's default reach // (#4086). - include: ["tests/visual/native-buttons.visual.tsx", "tests/visual/filter-row-targets.visual.tsx", "tests/visual/side-rail-targets.visual.tsx", "tests/visual/button-hover-contrast.visual.tsx", "tests/visual/overlay-targets.visual.tsx", "tests/visual/session-strip.visual.tsx", "tests/visual/pending-follow-ups.visual.tsx", "tests/visual/palette-reasons.visual.tsx", "tests/visual/status-indicator-targets.visual.tsx", "../ui-react/tests/browser/desktop-navigation.pointer.tsx", "../ui-react/tests/browser/keyboard-hints.pointer.tsx", "../ui-react/tests/browser/phone-navigation.pointer.tsx", "../ui-react/tests/browser/destination-press.pointer.tsx", "../ui-react/tests/browser/working-sessions.pointer.tsx", "../ui-react/tests/browser/session-drafts.pointer.tsx", "../ui-react/tests/browser/navigation-reach.*.pointer.tsx", "../ui-react/tests/browser/hit-reach.*.pointer.tsx", "../ui-react/tests/browser/recordings-tray.offline.tsx", "../ui-react/tests/browser/dictation-notice.pointer.tsx", "../ui-react/tests/browser/attach-tooltip.pointer.tsx", "../ui-react/tests/browser/composer-mic.pointer.tsx", "../ui-react/tests/browser/overlay-stacking.pointer.tsx", "../ui-react/tests/browser/session-profile.pointer.tsx", "../ui-react/tests/browser/turn-budget.pointer.tsx"], + include: ["tests/visual/native-buttons.visual.tsx", "tests/visual/filter-row-targets.visual.tsx", "tests/visual/side-rail-targets.visual.tsx", "tests/visual/button-hover-contrast.visual.tsx", "tests/visual/overlay-targets.visual.tsx", "tests/visual/session-strip.visual.tsx", "tests/visual/pending-follow-ups.visual.tsx", "tests/visual/palette-reasons.visual.tsx", "tests/visual/status-indicator-targets.visual.tsx", "../ui-react/tests/browser/desktop-navigation.pointer.tsx", "../ui-react/tests/browser/keyboard-hints.pointer.tsx", "../ui-react/tests/browser/phone-navigation.pointer.tsx", "../ui-react/tests/browser/destination-press.pointer.tsx", "../ui-react/tests/browser/working-sessions.pointer.tsx", "../ui-react/tests/browser/session-drafts.pointer.tsx", "../ui-react/tests/browser/navigation-reach.*.pointer.tsx", "../ui-react/tests/browser/hit-reach.*.pointer.tsx", "../ui-react/tests/browser/recordings-tray.offline.tsx", "../ui-react/tests/browser/dictation-notice.pointer.tsx", "../ui-react/tests/browser/attach-tooltip.pointer.tsx", "../ui-react/tests/browser/composer-mic.pointer.tsx", "../ui-react/tests/browser/overlay-stacking.pointer.tsx", "../ui-react/tests/browser/close-requests.pointer.tsx", "../ui-react/tests/browser/session-profile.pointer.tsx", "../ui-react/tests/browser/turn-budget.pointer.tsx"], provide: { railPointer: mode, keyboardHintsLive: false }, browser: { enabled: true, diff --git a/packages/ui-react/src/components/files/file-panel.tsx b/packages/ui-react/src/components/files/file-panel.tsx index c1e4a29c7d..f14af4ee98 100644 --- a/packages/ui-react/src/components/files/file-panel.tsx +++ b/packages/ui-react/src/components/files/file-panel.tsx @@ -4,6 +4,7 @@ import type { ReceiptRow } from "@schlessera/brain-ui-kit"; import { ChevronDown, ChevronRight } from "lucide-react"; import { useFileStore } from "../../stores/file-store.js"; import { singleKey } from "../../lib/single-key.js"; +import { useCloseRequest } from "../../lib/use-close-request.js"; import { useUIStore } from "../../stores/ui-store.js"; import { useFinePointer } from "../../hooks/use-fine-pointer.js"; import { useMediaQuery } from "../../hooks/use-media-query.js"; @@ -73,16 +74,13 @@ export function FilePanel({ open, onClose }: { open: boolean; onClose: () => voi wasOpen.current = open; }, [open, panes, root, closeFile]); - useEffect(() => { - if (!open || !panes) return; - const onKey = (event: KeyboardEvent) => { - if (event.key !== "Escape" || event.defaultPrevented || openModal()) return; - event.preventDefault(); - dismiss(); - }; - document.addEventListener("keydown", onKey); - return () => document.removeEventListener("keydown", onKey); - }, [open, panes, dismiss]); + // The panes are no dialog: Escape and Android back reach them through the + // kit's close-request helper (#2577). The phone drawer is an Overlay. + useCloseRequest(open && panes, () => { + if (openModal()) return false; + dismiss(); + return true; + }); // Sync hash route to current file. When the panel closes, strip the // `#/files*` segment entirely so a reload doesn't reopen it. diff --git a/packages/ui-react/src/components/graph/graph-scene.tsx b/packages/ui-react/src/components/graph/graph-scene.tsx index bc1c6fee73..6bb446fa43 100644 --- a/packages/ui-react/src/components/graph/graph-scene.tsx +++ b/packages/ui-react/src/components/graph/graph-scene.tsx @@ -243,7 +243,7 @@ export function SceneBody() { {/* Accessible / mobile-friendly node list — the canvas itself is aria-hidden */} + {children(close)} + ; + } + const ui = createBrainUiRoot({ storage: null, request: async () => Response.json({}) }); + const renderer = createRoot(host); + ctx.onTestFinished(() => { flushSync(() => renderer.unmount()); ui.dispose(); host.remove(); }); + flushSync(() => renderer.render()); + await userEvent.click(host.querySelector("[data-test-open]")!); await frame(); + return { host, closes }; +} + +test("Escape in the share menu inside a pane closes only the menu", async ctx => { + spyCloseWatcher(ctx); + const s = await pane(ctx, () => true }, { id: "save", label: "Save the chart", run: async () => true }]} />); + await userEvent.click(s.host.querySelector('[aria-label="Share the chart"]')!); await frame(); + // The menu may draw in a portal: read the whole document. + await expect.poll(() => document.body.textContent, { message: "the menu is open" }).toContain("Copy the chart"); + await userEvent.keyboard("{Escape}"); await frame(); + expect(document.body.textContent, "the menu closed").not.toContain("Copy the chart"); + expect(s.closes, "PREVENTED_INNER_ESCAPE: the pane stays open").toEqual([]); + await userEvent.keyboard("{Escape}"); await frame(); + expect(s.closes, "the next Escape closes the pane").toHaveLength(1); +}); + +test("Escape in the passkey rename field inside a pane cancels only the rename", async ctx => { + spyCloseWatcher(ctx); + const keys = [{ id: "bow", label: "Odysseus’s bow", rpId: "localhost", createdAt: Date.UTC(2026, 6, 1), lastUsedAt: null, backedUp: false, deviceType: null, transports: null, aaguid: null }]; + const s = await pane(ctx, () => {}} onRename={() => {}} onDelete={() => {}} onSignOut={() => {}} />); + await userEvent.click(s.host.querySelector('[aria-label^="Rename"]')!); await frame(); + const field = s.host.querySelector("input")!; + expect(field, "the rename field is open").toBeTruthy(); + field.focus(); + await userEvent.keyboard("{Escape}"); await frame(); + expect(s.host.querySelector("input"), "the rename was cancelled").toBeNull(); + expect(s.closes, "PREVENTED_INNER_ESCAPE: the pane stays open").toEqual([]); +}); + +test("a dictation take that is finishing survives a close request; once it is not, the next one cancels it once", async ctx => { + const seen = spyCloseWatcher(ctx); + const host = document.createElement("div"); + document.body.append(host); + const voice = useVoiceStore.getState(); + ctx.onTestFinished(() => { useVoiceStore.setState(voice, true); }); + const cancels: number[] = []; + useVoiceStore.setState({ mode: "dictate", dictationGate: null, draining: true }); + const renderer = createRoot(host); + ctx.onTestFinished(() => { flushSync(() => renderer.unmount()); host.remove(); }); + // Mounted from a real press, as a take starts from the mic. + const start = document.createElement("button"); + start.textContent = "Dictate"; + start.onclick = () => flushSync(() => renderer.render( {}} onCancel={() => cancels.push(1)} />)); + host.append(start); + await userEvent.click(start); await frame(); + expect(host.querySelector('[data-dictation-field="D5"]'), "the take is finishing").not.toBeNull(); + await userEvent.keyboard("{Escape}"); await frame(); + expect(seen.closed, "the close request reached the field's watcher").toBe(1); + expect(cancels, "a finishing take is not cancelled").toEqual([]); + flushSync(() => useVoiceStore.setState({ draining: false })); + await frame(); + await userEvent.keyboard("{Escape}"); await frame(); + expect(cancels, "the re-armed watcher cancels the take once").toEqual([1]); + expect(seen.closed).toBe(2); +}); + +test("arm and disarm: a disarmed surface lets the close request reach the page, re-arming restores exactly one dismissal per request", async ctx => { + const seen = spyCloseWatcher(ctx); + // The page's own watcher, beneath the surface: what Android back reaches + // when no surface takes it (#2582's drill-in history, here a sentinel). + const pageWatcher = new (window as unknown as { CloseWatcher: new () => EventTarget & { destroy(): void } }).CloseWatcher(); + let reachedPage = 0; + pageWatcher.addEventListener("close", () => { reachedPage++; }); + ctx.onTestFinished(() => pageWatcher.destroy()); + // The surface opens from a real press, as a panel does, so its watcher has + // its own group. It stays open on every request (closedBy="none" style), + // so each request is counted and the watcher re-arms. + let dismissals = 0; + let watch: ReturnType | null = null; + const open = document.createElement("button"); + open.textContent = "Open the surface"; + open.onclick = () => { watch = watchCloseRequests(document, () => { dismissals++; return false; }, { escape: false }); }; + document.body.append(open); + ctx.onTestFinished(() => { watch?.destroy(); open.remove(); }); + await userEvent.click(open); + expect(watch!.watching).toBe(true); + + watch!.disarm(); + expect(watch!.watching, "disarmed").toBe(false); + await userEvent.keyboard("{Escape}"); await frame(); + expect(dismissals, "a disarmed surface ignores the close request").toBe(0); + expect(reachedPage, "it reached the page instead").toBe(1); + + // Re-arm (from a real press, as #2582's depth change follows one), then + // two requests: one dismissal each, nothing grouped or skipped. + const rearm = document.createElement("button"); + rearm.textContent = "Back at the root"; + rearm.onclick = () => watch!.arm(); + document.body.append(rearm); + ctx.onTestFinished(() => rearm.remove()); + await userEvent.click(rearm); + expect(watch!.watching, "re-armed").toBe(true); + await userEvent.keyboard("{Escape}"); await frame(); + expect(dismissals, "first request after re-arming").toBe(1); + await userEvent.keyboard("{Escape}"); await frame(); + expect(dismissals, "second request: one more, the re-armed watcher was not grouped away").toBe(2); + expect(reachedPage, "the page saw neither").toBe(1); + expect(seen.created, "one watcher per arming").toBeGreaterThanOrEqual(3); +}); + +test("a disarmed surface with the Escape fallback still closes on Escape, and the page does not also take it", async ctx => { + spyCloseWatcher(ctx); + const pageWatcher = new (window as unknown as { CloseWatcher: new () => EventTarget & { destroy(): void } }).CloseWatcher(); + let reachedPage = 0; + pageWatcher.addEventListener("close", () => { reachedPage++; }); + ctx.onTestFinished(() => pageWatcher.destroy()); + let dismissals = 0; + const watch = watchCloseRequests(document, () => { dismissals++; return true; }, { armed: false }); + ctx.onTestFinished(() => watch.destroy()); + await userEvent.keyboard("{Escape}"); await frame(); + expect(dismissals, "Escape closes it at any depth (D52 N2)").toBe(1); + expect(reachedPage, "one gesture, one action").toBe(0); +}); From 3611ae547a38cb8b5c9fa01809de6305cf9fd800 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 16:22:38 +0000 Subject: [PATCH 2/9] fix(ui-react): dictation gate notices take close requests too (#2577) The dictation sheet these notices replaced closed on Escape in its gate states as well (consent, a blocked take). DictationNotices kept its own Escape listener, so Android back on a gate notice still left the app. It now goes through the shared close-request helper, as the capture field does. The browser test also proves that a surface refusing request after request (a finishing take, closedBy="none") re-arms without joining the surface beneath it: eight refusals reach only the upper surface, and once it closes, the next request reaches the one beneath. Co-Authored-By: Claude Opus 5.5 --- .../src/components/voice/dictation-field.tsx | 16 +++--- .../tests/browser/close-requests.pointer.tsx | 52 ++++++++++++++++++- 2 files changed, 57 insertions(+), 11 deletions(-) diff --git a/packages/ui-react/src/components/voice/dictation-field.tsx b/packages/ui-react/src/components/voice/dictation-field.tsx index 1e3e217c96..407f176bee 100644 --- a/packages/ui-react/src/components/voice/dictation-field.tsx +++ b/packages/ui-react/src/components/voice/dictation-field.tsx @@ -123,16 +123,12 @@ export function DictationNotices({ onConfirm, onCancel, onOpenSettings, onRetry, else if (form === "Dx0") focusButton(ref.current, "OK"); }, [form]); - useEffect(() => { - if (!form) return; - const onKey = (event: KeyboardEvent) => { - if (event.key !== "Escape" || event.defaultPrevented) return; - event.preventDefault(); - onCancel(); - }; - document.addEventListener("keydown", onKey); - return () => document.removeEventListener("keydown", onKey); - }, [form, onCancel]); + // Esc, or Android back, is Cancel on a gate notice (#2577), as it was on + // the dictation sheet these notices replaced. + useCloseRequest(form !== null, () => { + onCancel(); + return true; + }); if (gate?.kind === "consent") { return ( diff --git a/packages/ui-react/tests/browser/close-requests.pointer.tsx b/packages/ui-react/tests/browser/close-requests.pointer.tsx index 27dffd1cc7..6311fe49b5 100644 --- a/packages/ui-react/tests/browser/close-requests.pointer.tsx +++ b/packages/ui-react/tests/browser/close-requests.pointer.tsx @@ -23,7 +23,7 @@ import { ChatPage } from "../../src/components/chat/chat-page.js"; import { SlidePanel } from "../../src/components/layout/slide-panel.js"; import { ShareMenu } from "../../src/components/share/share-menu.js"; import { PasskeyList } from "../../src/components/settings/passkey-list.js"; -import { DictationCapture } from "../../src/components/voice/dictation-field.js"; +import { DictationCapture, DictationNotices } from "../../src/components/voice/dictation-field.js"; import { useVoiceStore } from "../../src/voice/voice-store.js"; class FixtureSocket { @@ -247,6 +247,30 @@ test("a dictation take that is finishing survives a close request; once it is no expect(seen.closed).toBe(2); }); +test("a dictation gate notice takes a close request as Cancel, once", async ctx => { + const seen = spyCloseWatcher(ctx); + const host = document.createElement("div"); + document.body.append(host); + const voice = useVoiceStore.getState(); + ctx.onTestFinished(() => { useVoiceStore.setState(voice, true); }); + const cancels: number[] = []; + const renderer = createRoot(host); + ctx.onTestFinished(() => { flushSync(() => renderer.unmount()); host.remove(); }); + flushSync(() => renderer.render( {}} onCancel={() => { cancels.push(1); useVoiceStore.setState({ dictationGate: null }); }} onOpenSettings={() => {}} onRetry={() => {}} onDismiss={() => {}} />)); + // A blocked take's notice (Dx1: choose a service) opens from the mic press. + const start = document.createElement("button"); + start.textContent = "Dictate"; + start.onclick = () => flushSync(() => useVoiceStore.setState({ dictationGate: { kind: "blocked", reason: "choose", saved: null } })); + host.append(start); + await userEvent.click(start); await frame(); + expect(host.querySelector('[data-dictation-notice="Dx1"]'), "the blocked-take notice shows").not.toBeNull(); + expect(seen.created, "the notice holds a close watcher").toBeGreaterThan(0); + await userEvent.keyboard("{Escape}"); await frame(); + expect(cancels, "Cancel, once").toEqual([1]); + expect(seen.closed, "through the notice's watcher").toBe(1); + expect(host.querySelector('[data-dictation-notice="Dx1"]')).toBeNull(); +}); + test("arm and disarm: a disarmed surface lets the close request reach the page, re-arming restores exactly one dismissal per request", async ctx => { const seen = spyCloseWatcher(ctx); // The page's own watcher, beneath the surface: what Android back reaches @@ -291,6 +315,32 @@ test("arm and disarm: a disarmed surface lets the close request reach the page, expect(seen.created, "one watcher per arming").toBeGreaterThanOrEqual(3); }); +test("repeated refusals re-arm without joining the surface beneath: one action per request", async ctx => { + // A surface that refuses (a finishing take, closedBy="none") re-arms with a + // watcher created inside the close event, with no new user activation. It + // must stay its own step: the surface beneath (a pane under the take) is + // never closed along with it, however many requests it refuses. + spyCloseWatcher(ctx); + let lower = 0, upper = 0, upperCloses = false; + const openLower = document.createElement("button"); openLower.textContent = "Open the pane"; + const openUpper = document.createElement("button"); openUpper.textContent = "Start the take"; + document.body.append(openLower, openUpper); + let a: ReturnType | null = null, b: ReturnType | null = null; + openLower.onclick = () => { a = watchCloseRequests(document, () => { lower++; return true; }, { escape: false }); }; + openUpper.onclick = () => { b = watchCloseRequests(document, () => { upper++; return upperCloses; }, { escape: false }); }; + ctx.onTestFinished(() => { a?.destroy(); b?.destroy(); openLower.remove(); openUpper.remove(); }); + await userEvent.click(openLower); await userEvent.click(openUpper); + for (let i = 1; i <= 8; i++) { + await userEvent.keyboard("{Escape}"); await frame(); + expect([upper, lower], `refusal ${i} reached only the upper surface`).toEqual([i, 0]); + } + upperCloses = true; + await userEvent.keyboard("{Escape}"); await frame(); + expect([upper, lower], "the upper surface closes on its own").toEqual([9, 0]); + await userEvent.keyboard("{Escape}"); await frame(); + expect([upper, lower], "the next request reaches the surface beneath").toEqual([9, 1]); +}); + test("a disarmed surface with the Escape fallback still closes on Escape, and the page does not also take it", async ctx => { spyCloseWatcher(ctx); const pageWatcher = new (window as unknown as { CloseWatcher: new () => EventTarget & { destroy(): void } }).CloseWatcher(); From d783e90be09b7419384792a660b5ab7797768f9a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 16:24:24 +0000 Subject: [PATCH 3/9] fix(ui-react): drop the dictation field's unused effect import (#2577) Co-Authored-By: Claude Opus 5.5 --- packages/ui-react/src/components/voice/dictation-field.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-react/src/components/voice/dictation-field.tsx b/packages/ui-react/src/components/voice/dictation-field.tsx index 407f176bee..43d23febab 100644 --- a/packages/ui-react/src/components/voice/dictation-field.tsx +++ b/packages/ui-react/src/components/voice/dictation-field.tsx @@ -1,5 +1,5 @@ import { VoiceControlButton, VoiceField, VoiceNotice, VoiceText } from "@schlessera/brain-ui-kit"; -import { useEffect, useLayoutEffect, useRef } from "react"; +import { useLayoutEffect, useRef } from "react"; import { dictationNoticeForm } from "../../voice/dictation-failure.js"; import { providerAudioPolicy, providerMeta, providerRecipient, savedServiceName } from "../../voice/dictation-providers.js"; import { useVoiceStore } from "../../voice/voice-store.js"; From f1c11cd636d6831e174a8404447fd489cb8c6939 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 16:35:46 +0000 Subject: [PATCH 4/9] fix(ui-kit,ui-react): leave refused Escapes to the modal above; watch undismissable panes (#2577) - The Escape fallback now prevents the keydown only when the surface closed. It prevented before asking, so without CloseWatcher (or while disarmed) a modal opened over a Settings or Files pane never got its cancel and stayed open. - A pane that cannot be dismissed (closedBy="none", Settings while its navigation is protected) now holds a close watcher and refuses each request, re-armed, instead of letting Android back leave the app. Co-Authored-By: Claude Opus 5.5 --- packages/ui-kit/src/internal/close-request.ts | 6 ++- .../src/components/layout/slide-panel.tsx | 8 ++-- .../tests/browser/close-requests.pointer.tsx | 37 ++++++++++++++++++- 3 files changed, 44 insertions(+), 7 deletions(-) diff --git a/packages/ui-kit/src/internal/close-request.ts b/packages/ui-kit/src/internal/close-request.ts index bbdcafbd0c..486426ed5b 100644 --- a/packages/ui-kit/src/internal/close-request.ts +++ b/packages/ui-kit/src/internal/close-request.ts @@ -92,8 +92,10 @@ export function watchCloseRequests(document: Document, request: () => boolean, o // With an armed watcher, Escape is the platform's close request and // arrives through the watcher; handling it here too would close twice. if (watcher || destroyed || event.key !== "Escape" || event.defaultPrevented || event.isComposing) return; - event.preventDefault(); - request(); + // Prevented only when the surface closed. A refusal (a modal over it, + // closedBy="none", a finishing take) leaves the keydown for whatever + // takes it next: a dialog above needs it for its own cancel. + if (request()) event.preventDefault(); }; if (options.escape ?? true) document.addEventListener("keydown", keys); create(); diff --git a/packages/ui-react/src/components/layout/slide-panel.tsx b/packages/ui-react/src/components/layout/slide-panel.tsx index 266f23baf3..b8b797c5f9 100644 --- a/packages/ui-react/src/components/layout/slide-panel.tsx +++ b/packages/ui-react/src/components/layout/slide-panel.tsx @@ -42,9 +42,11 @@ export function SlidePanel({ children: ReactNode; }) { // A pane is no dialog, so Escape and Android back reach it through the - // kit's close-request helper (#2577). A drawer is an Overlay, which has its own. - useCloseRequest(open && mode === "pane" && closedBy !== "none", () => { - if (openModal()) return false; + // kit's close-request helper (#2577). A drawer is an Overlay, which has its + // own. A pane that cannot be dismissed (closedBy="none") still takes the + // request, so Android back does not leave the app, and refuses it. + useCloseRequest(open && mode === "pane", () => { + if (closedBy === "none" || openModal()) return false; onClose(); return true; }); diff --git a/packages/ui-react/tests/browser/close-requests.pointer.tsx b/packages/ui-react/tests/browser/close-requests.pointer.tsx index 6311fe49b5..2c3e68db5e 100644 --- a/packages/ui-react/tests/browser/close-requests.pointer.tsx +++ b/packages/ui-react/tests/browser/close-requests.pointer.tsx @@ -173,7 +173,7 @@ test("a modal over a destination panel takes the first close request, the panel }); /** A non-modal pane holding `children`, opened from a real button, for inner Escape consumers. */ -async function pane(ctx: TestContext, children: (close: () => void) => React.ReactNode) { +async function pane(ctx: TestContext, children: (close: () => void) => React.ReactNode, closedBy: "any" | "none" = "any") { await page.viewport(1024, 800); const host = document.createElement("div"); document.body.append(host); @@ -183,7 +183,7 @@ async function pane(ctx: TestContext, children: (close: () => void) => React.Rea const close = () => { closes.push(Date.now()); setOpen(false); }; return <> - {children(close)} + {children(close)} ; } const ui = createBrainUiRoot({ storage: null, request: async () => Response.json({}) }); @@ -207,6 +207,39 @@ test("Escape in the share menu inside a pane closes only the menu", async ctx => expect(s.closes, "the next Escape closes the pane").toHaveLength(1); }); +test("a pane that cannot be dismissed takes each close request and stays open, re-armed", async ctx => { + const seen = spyCloseWatcher(ctx); + const s = await pane(ctx, () =>

The suitors wait.

, "none"); + expect(seen.created, "a closedBy=none pane still holds a close watcher").toBeGreaterThan(0); + for (let i = 1; i <= 3; i++) { + await userEvent.keyboard("{Escape}"); await frame(); + expect(seen.closed, `request ${i} reached the pane's watcher`).toBe(i); + expect(s.closes, "the pane stays open").toEqual([]); + } + expect(document.querySelector('section[aria-label="Ithaca"]'), "still drawn").not.toBeNull(); +}); + +for (const watcher of [true, false]) test(`a modal opened over a pane takes Escape first${watcher ? "" : " (without CloseWatcher)"}, the pane the next`, async ctx => { + if (watcher) spyCloseWatcher(ctx); else withoutCloseWatcher(ctx); + const s = await pane(ctx, () =>

Penelope's loom.

); + const dialog = document.createElement("dialog"); + dialog.textContent = "The suitors' demands"; + document.body.append(dialog); + ctx.onTestFinished(() => dialog.remove()); + const open = document.createElement("button"); + open.textContent = "Show demands"; + open.onclick = () => dialog.showModal(); + document.body.append(open); + ctx.onTestFinished(() => open.remove()); + await userEvent.click(open); + expect(dialog.open).toBe(true); + await userEvent.keyboard("{Escape}"); await frame(); + expect(dialog.open, "the modal closed first").toBe(false); + expect(s.closes, "the pane stays open under it").toEqual([]); + await userEvent.keyboard("{Escape}"); await frame(); + expect(s.closes, "the next Escape closes the pane").toHaveLength(1); +}); + test("Escape in the passkey rename field inside a pane cancels only the rename", async ctx => { spyCloseWatcher(ctx); const keys = [{ id: "bow", label: "Odysseus’s bow", rpId: "localhost", createdAt: Date.UTC(2026, 6, 1), lastUsedAt: null, backedUp: false, deviceType: null, transports: null, aaguid: null }]; From 0ef0d7ad7d43c37ed3c7a958a9227d2b572f80f1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 16:53:05 +0000 Subject: [PATCH 5/9] test(ui-react): arm and disarm under a page watcher that stays armed (#2577) The page beneath the surface now arms itself again in its own close handler, with no user activation, as #2582's history helper will from popstate, and the surface re-arms from script, not from a press. A re-armed watcher that joined the page's group would now show: two requests after re-arming reach the surface only, and the page takes the next request alone once the surface is disarmed again. Co-Authored-By: Claude Opus 5.5 --- .../tests/browser/close-requests.pointer.tsx | 46 +++++++++++-------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/packages/ui-react/tests/browser/close-requests.pointer.tsx b/packages/ui-react/tests/browser/close-requests.pointer.tsx index 2c3e68db5e..8d4bba9c32 100644 --- a/packages/ui-react/tests/browser/close-requests.pointer.tsx +++ b/packages/ui-react/tests/browser/close-requests.pointer.tsx @@ -306,15 +306,22 @@ test("a dictation gate notice takes a close request as Cancel, once", async ctx test("arm and disarm: a disarmed surface lets the close request reach the page, re-arming restores exactly one dismissal per request", async ctx => { const seen = spyCloseWatcher(ctx); - // The page's own watcher, beneath the surface: what Android back reaches - // when no surface takes it (#2582's drill-in history, here a sentinel). - const pageWatcher = new (window as unknown as { CloseWatcher: new () => EventTarget & { destroy(): void } }).CloseWatcher(); + type Watcher = EventTarget & { destroy(): void }; + const Native = (window as unknown as { CloseWatcher: new () => Watcher }).CloseWatcher; + // The page beneath the surface, as #2582's history helper will be: it takes + // a close request (Android back reaching popstate) and arms itself again in + // that same handler, with no user activation. It stays beneath throughout, + // so a re-armed surface watcher that joined its group would show here. let reachedPage = 0; - pageWatcher.addEventListener("close", () => { reachedPage++; }); - ctx.onTestFinished(() => pageWatcher.destroy()); - // The surface opens from a real press, as a panel does, so its watcher has - // its own group. It stays open on every request (closedBy="none" style), - // so each request is counted and the watcher re-arms. + let pageWatcher: Watcher | null = null; + const armPage = () => { + pageWatcher = new Native(); + pageWatcher.addEventListener("close", () => { reachedPage++; armPage(); }); + }; + armPage(); + ctx.onTestFinished(() => pageWatcher?.destroy()); + // The surface opens from a real press, as a panel does. It stays open on + // every request (closedBy="none" style), so each request is counted. let dismissals = 0; let watch: ReturnType | null = null; const open = document.createElement("button"); @@ -331,21 +338,20 @@ test("arm and disarm: a disarmed surface lets the close request reach the page, expect(dismissals, "a disarmed surface ignores the close request").toBe(0); expect(reachedPage, "it reached the page instead").toBe(1); - // Re-arm (from a real press, as #2582's depth change follows one), then - // two requests: one dismissal each, nothing grouped or skipped. - const rearm = document.createElement("button"); - rearm.textContent = "Back at the root"; - rearm.onclick = () => watch!.arm(); - document.body.append(rearm); - ctx.onTestFinished(() => rearm.remove()); - await userEvent.click(rearm); + // Re-armed from script with no user activation, as #2582 will re-arm from + // popstate when the depth returns to the root. Then two requests: one + // dismissal each, the page beneath never, nothing grouped or skipped. + watch!.arm(); expect(watch!.watching, "re-armed").toBe(true); await userEvent.keyboard("{Escape}"); await frame(); - expect(dismissals, "first request after re-arming").toBe(1); + expect([dismissals, reachedPage], "first request after re-arming: the surface only").toEqual([1, 1]); + await userEvent.keyboard("{Escape}"); await frame(); + expect([dismissals, reachedPage], "second request: the surface only, not grouped with the page").toEqual([2, 1]); + // Disarm again: the page, still armed beneath, takes the next request alone. + watch!.disarm(); await userEvent.keyboard("{Escape}"); await frame(); - expect(dismissals, "second request: one more, the re-armed watcher was not grouped away").toBe(2); - expect(reachedPage, "the page saw neither").toBe(1); - expect(seen.created, "one watcher per arming").toBeGreaterThanOrEqual(3); + expect([dismissals, reachedPage], "disarmed again: the page only").toEqual([2, 2]); + expect(seen.created, "a watcher per arming and re-arming").toBeGreaterThanOrEqual(4); }); test("repeated refusals re-arm without joining the surface beneath: one action per request", async ctx => { From 5b28147989fd60b4fe074947296c4064d06b39b4 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 17:07:22 +0000 Subject: [PATCH 6/9] fix(ui-kit): only the topmost surface's Escape fallback acts (#2577) - A surface disarmed beneath an armed one (a drilled-in pane under a dictation take, once #2582 disarms) ran its Escape fallback and closed itself, suppressing the close request the surface above was armed for. The helper keeps each document's open surfaces in opening order, and only the topmost one's fallback acts. - overlay-stacking's pane-guard test dispatches synthetic Escapes, which never raise a close request; with the panes now armed it could no longer fail. It now runs where the keydown fallback is the path (without CloseWatcher), so the defaultPrevented, closedBy="none" and openModal() guards are each proven again. - The dictation field and its gate notices are now tested without CloseWatcher too, a finishing take included. Co-Authored-By: Claude Opus 5.5 --- packages/ui-kit/src/internal/close-request.ts | 16 +++++- .../tests/browser/close-requests.pointer.tsx | 56 +++++++++++++++++++ .../browser/overlay-stacking.pointer.tsx | 7 +++ 3 files changed, 78 insertions(+), 1 deletion(-) diff --git a/packages/ui-kit/src/internal/close-request.ts b/packages/ui-kit/src/internal/close-request.ts index 486426ed5b..511d48de34 100644 --- a/packages/ui-kit/src/internal/close-request.ts +++ b/packages/ui-kit/src/internal/close-request.ts @@ -55,6 +55,14 @@ export interface CloseRequestOptions { armed?: boolean; } +/** + * Each document's open surfaces, in opening order. Only the topmost one's + * Escape fallback acts: a surface disarmed beneath an armed one (a drilled-in + * pane under a dictation take) must not take the Escape that is the upper + * surface's close request. + */ +const opened = new WeakMap(); + function watcherConstructor(view: Window | null): CloseWatcherConstructor | null { const candidate = (view as (Window & { CloseWatcher?: unknown }) | null)?.CloseWatcher; return typeof candidate === "function" ? (candidate as CloseWatcherConstructor) : null; @@ -63,6 +71,10 @@ function watcherConstructor(view: Window | null): CloseWatcherConstructor | null /** Watch close requests for one open surface in `document`; destroy it on close or unmount. */ export function watchCloseRequests(document: Document, request: () => boolean, options: CloseRequestOptions = {}): CloseRequestWatch { const Watcher = watcherConstructor(document.defaultView); + const id = Symbol("close-request"); + const order = opened.get(document) ?? []; + opened.set(document, order); + order.push(id); let armed = options.armed ?? true; let destroyed = false; let watcher: PlatformCloseWatcher | null = null; @@ -91,7 +103,7 @@ export function watchCloseRequests(document: Document, request: () => boolean, o const keys = (event: KeyboardEvent) => { // With an armed watcher, Escape is the platform's close request and // arrives through the watcher; handling it here too would close twice. - if (watcher || destroyed || event.key !== "Escape" || event.defaultPrevented || event.isComposing) return; + if (watcher || destroyed || event.key !== "Escape" || event.defaultPrevented || event.isComposing || order.at(-1) !== id) return; // Prevented only when the surface closed. A refusal (a modal over it, // closedBy="none", a finishing take) leaves the keydown for whatever // takes it next: a dialog above needs it for its own cancel. @@ -116,6 +128,8 @@ export function watchCloseRequests(document: Document, request: () => boolean, o if (destroyed) return; destroyed = true; release(); + const index = order.indexOf(id); + if (index !== -1) order.splice(index, 1); document.removeEventListener("keydown", keys); }, }; diff --git a/packages/ui-react/tests/browser/close-requests.pointer.tsx b/packages/ui-react/tests/browser/close-requests.pointer.tsx index 8d4bba9c32..efe36f9dca 100644 --- a/packages/ui-react/tests/browser/close-requests.pointer.tsx +++ b/packages/ui-react/tests/browser/close-requests.pointer.tsx @@ -280,6 +280,62 @@ test("a dictation take that is finishing survives a close request; once it is no expect(seen.closed).toBe(2); }); +test("without CloseWatcher, Escape still cancels a take once, and a finishing take refuses it", async ctx => { + withoutCloseWatcher(ctx); + const host = document.createElement("div"); + document.body.append(host); + const voice = useVoiceStore.getState(); + ctx.onTestFinished(() => { useVoiceStore.setState(voice, true); }); + const cancels: number[] = []; + useVoiceStore.setState({ mode: "dictate", dictationGate: null, draining: true }); + const renderer = createRoot(host); + ctx.onTestFinished(() => { flushSync(() => renderer.unmount()); host.remove(); }); + flushSync(() => renderer.render( {}} onCancel={() => cancels.push(1)} />)); + await frame(); + await userEvent.keyboard("{Escape}"); await frame(); + expect(cancels, "D5 refuses the fallback's Escape").toEqual([]); + flushSync(() => useVoiceStore.setState({ draining: false })); + await frame(); + await userEvent.keyboard("{Escape}"); await frame(); + expect(cancels, "then Escape cancels the take once").toEqual([1]); +}); + +test("without CloseWatcher, Escape on a dictation gate notice is Cancel, once", async ctx => { + withoutCloseWatcher(ctx); + const host = document.createElement("div"); + document.body.append(host); + const voice = useVoiceStore.getState(); + ctx.onTestFinished(() => { useVoiceStore.setState(voice, true); }); + const cancels: number[] = []; + useVoiceStore.setState({ dictationGate: { kind: "blocked", reason: "choose", saved: null } }); + const renderer = createRoot(host); + ctx.onTestFinished(() => { flushSync(() => renderer.unmount()); host.remove(); }); + flushSync(() => renderer.render( {}} onCancel={() => { cancels.push(1); useVoiceStore.setState({ dictationGate: null }); }} onOpenSettings={() => {}} onRetry={() => {}} onDismiss={() => {}} />)); + await frame(); + expect(host.querySelector('[data-dictation-notice="Dx1"]')).not.toBeNull(); + await userEvent.keyboard("{Escape}"); await frame(); + expect(cancels, "Cancel, once").toEqual([1]); +}); + +test("a disarmed surface beneath an armed one leaves Escape to the surface above", async ctx => { + spyCloseWatcher(ctx); + let lower = 0, upper = 0; + const openLower = document.createElement("button"); openLower.textContent = "Open the pane"; + const openUpper = document.createElement("button"); openUpper.textContent = "Start the take"; + document.body.append(openLower, openUpper); + let a: ReturnType | null = null, b: ReturnType | null = null; + // The pane keeps its Escape fallback (it is disarmed, as #2582 will do when drilled in). + openLower.onclick = () => { a = watchCloseRequests(document, () => { lower++; return true; }); a.disarm(); }; + openUpper.onclick = () => { b = watchCloseRequests(document, () => { upper++; return true; }); }; + ctx.onTestFinished(() => { a?.destroy(); b?.destroy(); openLower.remove(); openUpper.remove(); }); + await userEvent.click(openLower); await userEvent.click(openUpper); + await userEvent.keyboard("{Escape}"); await frame(); + expect([upper, lower], "the armed surface above closes; the disarmed pane beneath does not").toEqual([1, 0]); + b!.destroy(); + await userEvent.keyboard("{Escape}"); await frame(); + expect([upper, lower], "with the upper gone, Escape reaches the pane's fallback").toEqual([1, 1]); +}); + test("a dictation gate notice takes a close request as Cancel, once", async ctx => { const seen = spyCloseWatcher(ctx); const host = document.createElement("div"); diff --git a/packages/ui-react/tests/browser/overlay-stacking.pointer.tsx b/packages/ui-react/tests/browser/overlay-stacking.pointer.tsx index 6e0189f7d8..fd3f324800 100644 --- a/packages/ui-react/tests/browser/overlay-stacking.pointer.tsx +++ b/packages/ui-react/tests/browser/overlay-stacking.pointer.tsx @@ -342,6 +342,13 @@ test("subagent Escape pops one level without remounting and focuses the new Back for (const destination of ["files", "settings"] as const) test(`${destination} pane: Escape respects inner prevention and modal stacking`, async ctx => { // Mutations: delete the pane listener, ignore defaultPrevented, or ignore openModal. + // The guards below are dispatched as synthetic (untrusted) Escapes, which + // never raise a close request: they are the keydown fallback's guards, so + // the test runs where that fallback is the path, without CloseWatcher + // (#2577). The watcher path's guards are in close-requests.pointer.tsx. + const closeWatcher = Object.getOwnPropertyDescriptor(window, "CloseWatcher"); + Reflect.deleteProperty(window, "CloseWatcher"); + ctx.onTestFinished(() => { if (closeWatcher) Object.defineProperty(window, "CloseWatcher", closeWatcher); }); const s = await mount(ctx, 1280); flushSync(() => { if (destination === "settings") s.ui.stores.ui.getState().setSettingsTab("appearance"); From ca679af05ec8b41efcc26050849e9a3606d97180 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 17:21:22 +0000 Subject: [PATCH 7/9] fix(ui-kit): arm a close watcher only while its surface is topmost (#2577) A new CloseWatcher goes on top of the platform's stack. Re-arming a surface beneath another open one (a pane back at its drill-in root under a live dictation take, once #2582 drives arm()) would let it take the next Back before the surface above. A surface now arms only while it is topmost; an arming beneath waits, and runs when the surfaces above it close. Co-Authored-By: Claude Opus 5.5 --- packages/ui-kit/src/internal/close-request.ts | 27 ++++++++++++------- .../tests/browser/close-requests.pointer.tsx | 26 ++++++++++++++++++ 2 files changed, 44 insertions(+), 9 deletions(-) diff --git a/packages/ui-kit/src/internal/close-request.ts b/packages/ui-kit/src/internal/close-request.ts index 511d48de34..9045b5cff9 100644 --- a/packages/ui-kit/src/internal/close-request.ts +++ b/packages/ui-kit/src/internal/close-request.ts @@ -56,12 +56,18 @@ export interface CloseRequestOptions { } /** - * Each document's open surfaces, in opening order. Only the topmost one's - * Escape fallback acts: a surface disarmed beneath an armed one (a drilled-in - * pane under a dictation take) must not take the Escape that is the upper - * surface's close request. + * Each document's open surfaces, in opening order, so the platform's watcher + * stack keeps the same order: + * - only the topmost surface's Escape fallback acts, so a surface disarmed + * beneath an armed one (a drilled-in pane under a dictation take) never + * takes the Escape that is the upper surface's close request; + * - a surface arms a new watcher only while it is topmost. A new watcher goes + * on top of the platform's stack, so arming one beneath another surface + * would let it take the next Back first. Its arming waits, and runs when + * the surfaces above it close (`wake`). */ -const opened = new WeakMap(); +interface Opened { id: symbol; wake: () => void } +const opened = new WeakMap(); function watcherConstructor(view: Window | null): CloseWatcherConstructor | null { const candidate = (view as (Window & { CloseWatcher?: unknown }) | null)?.CloseWatcher; @@ -74,13 +80,13 @@ export function watchCloseRequests(document: Document, request: () => boolean, o const id = Symbol("close-request"); const order = opened.get(document) ?? []; opened.set(document, order); - order.push(id); + const topmost = () => order.at(-1)?.id === id; let armed = options.armed ?? true; let destroyed = false; let watcher: PlatformCloseWatcher | null = null; const create = () => { - if (!Watcher || !armed || destroyed || watcher) return; + if (!Watcher || !armed || destroyed || watcher || !topmost()) return; const created = new Watcher(); created.onclose = () => { // The platform destroys a watcher once it closes; drop our reference @@ -103,12 +109,13 @@ export function watchCloseRequests(document: Document, request: () => boolean, o const keys = (event: KeyboardEvent) => { // With an armed watcher, Escape is the platform's close request and // arrives through the watcher; handling it here too would close twice. - if (watcher || destroyed || event.key !== "Escape" || event.defaultPrevented || event.isComposing || order.at(-1) !== id) return; + if (watcher || destroyed || event.key !== "Escape" || event.defaultPrevented || event.isComposing || !topmost()) return; // Prevented only when the surface closed. A refusal (a modal over it, // closedBy="none", a finishing take) leaves the keydown for whatever // takes it next: a dialog above needs it for its own cancel. if (request()) event.preventDefault(); }; + order.push({ id, wake: () => create() }); if (options.escape ?? true) document.addEventListener("keydown", keys); create(); @@ -128,9 +135,11 @@ export function watchCloseRequests(document: Document, request: () => boolean, o if (destroyed) return; destroyed = true; release(); - const index = order.indexOf(id); + const index = order.findIndex((entry) => entry.id === id); if (index !== -1) order.splice(index, 1); document.removeEventListener("keydown", keys); + // The surface now on top may have an arming waiting on this one. + order.at(-1)?.wake(); }, }; } diff --git a/packages/ui-react/tests/browser/close-requests.pointer.tsx b/packages/ui-react/tests/browser/close-requests.pointer.tsx index efe36f9dca..969e5707fd 100644 --- a/packages/ui-react/tests/browser/close-requests.pointer.tsx +++ b/packages/ui-react/tests/browser/close-requests.pointer.tsx @@ -336,6 +336,32 @@ test("a disarmed surface beneath an armed one leaves Escape to the surface above expect([upper, lower], "with the upper gone, Escape reaches the pane's fallback").toEqual([1, 1]); }); +test("re-arming a surface beneath another waits until the upper one closes", async ctx => { + const seen = spyCloseWatcher(ctx); + let lower = 0, upper = 0; + const openLower = document.createElement("button"); openLower.textContent = "Open the pane"; + const openUpper = document.createElement("button"); openUpper.textContent = "Start the take"; + document.body.append(openLower, openUpper); + let a: ReturnType | null = null, b: ReturnType | null = null; + openLower.onclick = () => { a = watchCloseRequests(document, () => { lower++; return true; }, { escape: false }); }; + openUpper.onclick = () => { b = watchCloseRequests(document, () => { upper++; return false; }, { escape: false }); }; + ctx.onTestFinished(() => { a?.destroy(); b?.destroy(); openLower.remove(); openUpper.remove(); }); + await userEvent.click(openLower); + // Drilled in (#2582): the pane is disarmed. Then a take opens above it. + a!.disarm(); + await userEvent.click(openUpper); + // Back at the pane's root while the take is still open: the pane re-arms. + a!.arm(); + expect(a!.watching, "the pane's arming waits beneath the take").toBe(false); + await userEvent.keyboard("{Escape}"); await frame(); + expect([upper, lower], "the take, on top, takes the request").toEqual([1, 0]); + b!.destroy(); + expect(a!.watching, "with the take gone, the pane's watcher is armed").toBe(true); + await userEvent.keyboard("{Escape}"); await frame(); + expect([upper, lower], "the next request reaches the pane").toEqual([1, 1]); + expect(seen.closed).toBe(2); +}); + test("a dictation gate notice takes a close request as Cancel, once", async ctx => { const seen = spyCloseWatcher(ctx); const host = document.createElement("div"); From 7a23304a9dbf43b8e6fae0bab4252f0f4f123937 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 17:37:12 +0000 Subject: [PATCH 8/9] fix(ui-kit): only the topmost open surface holds a close watcher (#2577) Disarming the topmost surface released only its own watcher, so a surface beneath that had armed earlier kept one, and Android back reached it instead of the page: a dictation take with a drilled-in pane above it (#2582) would be cancelled while the pane stayed drilled in. A surface opened above another now takes the watcher: the one beneath releases its own and stays armed, and arms again once the surfaces above it close. A close request therefore reaches the topmost surface or, when that is disarmed, the page, and never a surface beneath. Co-Authored-By: Claude Opus 5.5 --- packages/ui-kit/src/internal/close-request.ts | 24 +++++++------ .../tests/browser/close-requests.pointer.tsx | 36 ++++++++++++++++++- 2 files changed, 48 insertions(+), 12 deletions(-) diff --git a/packages/ui-kit/src/internal/close-request.ts b/packages/ui-kit/src/internal/close-request.ts index 9045b5cff9..03858c89be 100644 --- a/packages/ui-kit/src/internal/close-request.ts +++ b/packages/ui-kit/src/internal/close-request.ts @@ -56,17 +56,17 @@ export interface CloseRequestOptions { } /** - * Each document's open surfaces, in opening order, so the platform's watcher - * stack keeps the same order: - * - only the topmost surface's Escape fallback acts, so a surface disarmed - * beneath an armed one (a drilled-in pane under a dictation take) never - * takes the Escape that is the upper surface's close request; - * - a surface arms a new watcher only while it is topmost. A new watcher goes - * on top of the platform's stack, so arming one beneath another surface - * would let it take the next Back first. Its arming waits, and runs when - * the surfaces above it close (`wake`). + * Each document's open surfaces, in opening order. Only the topmost one holds + * a platform watcher, and only its Escape fallback acts: + * - a surface opened above another takes the watcher: the one beneath + * releases its own (`sleep`) and stays armed, and arms again (`wake`) once + * the surfaces above it close; + * - so a close request always reaches the topmost surface or, when that + * surface is disarmed (drilled in, #2582), the page, never a surface + * beneath: one Back is one step, innermost first; + * - and a surface beneath never takes the Escape that is the upper one's. */ -interface Opened { id: symbol; wake: () => void } +interface Opened { id: symbol; wake: () => void; sleep: () => void } const opened = new WeakMap(); function watcherConstructor(view: Window | null): CloseWatcherConstructor | null { @@ -115,7 +115,9 @@ export function watchCloseRequests(document: Document, request: () => boolean, o // takes it next: a dialog above needs it for its own cancel. if (request()) event.preventDefault(); }; - order.push({ id, wake: () => create() }); + // The surface beneath gives up its watcher to this one. + order.at(-1)?.sleep(); + order.push({ id, wake: () => create(), sleep: () => release() }); if (options.escape ?? true) document.addEventListener("keydown", keys); create(); diff --git a/packages/ui-react/tests/browser/close-requests.pointer.tsx b/packages/ui-react/tests/browser/close-requests.pointer.tsx index 969e5707fd..c659f2f390 100644 --- a/packages/ui-react/tests/browser/close-requests.pointer.tsx +++ b/packages/ui-react/tests/browser/close-requests.pointer.tsx @@ -362,6 +362,39 @@ test("re-arming a surface beneath another waits until the upper one closes", asy expect(seen.closed).toBe(2); }); +test("a disarmed surface above an armed one lets the close request reach the page, not the surface beneath", async ctx => { + spyCloseWatcher(ctx); + type Watcher = EventTarget & { destroy(): void }; + const Native = (window as unknown as { CloseWatcher: new () => Watcher }).CloseWatcher; + let reachedPage = 0; + let pageWatcher: Watcher | null = null; + const armPage = () => { pageWatcher = new Native(); pageWatcher.addEventListener("close", () => { reachedPage++; armPage(); }); }; + armPage(); + ctx.onTestFinished(() => pageWatcher?.destroy()); + let take = 0, pane = 0; + const startTake = document.createElement("button"); startTake.textContent = "Start the take"; + const openPane = document.createElement("button"); openPane.textContent = "Open the pane"; + document.body.append(startTake, openPane); + let a: ReturnType | null = null, b: ReturnType | null = null; + startTake.onclick = () => { a = watchCloseRequests(document, () => { take++; return true; }, { escape: false }); }; + openPane.onclick = () => { b = watchCloseRequests(document, () => { pane++; return true; }, { escape: false }); }; + ctx.onTestFinished(() => { a?.destroy(); b?.destroy(); startTake.remove(); openPane.remove(); }); + // A take is live, then a pane opens above it and drills in (#2582 disarms it). + await userEvent.click(startTake); await userEvent.click(openPane); + expect([a!.watching, b!.watching], "only the topmost surface holds a watcher").toEqual([false, true]); + b!.disarm(); + await userEvent.keyboard("{Escape}"); await frame(); + expect([take, pane, reachedPage], "Back pops the pane's drill-in: the page takes it, not the take beneath").toEqual([0, 0, 1]); + // Back at the pane's root: the pane closes on the next request, then the take. + b!.arm(); + await userEvent.keyboard("{Escape}"); await frame(); + expect([take, pane, reachedPage], "the pane closes").toEqual([0, 1, 1]); + b!.destroy(); + expect(a!.watching, "the take holds the watcher again").toBe(true); + await userEvent.keyboard("{Escape}"); await frame(); + expect([take, pane, reachedPage], "then the take").toEqual([1, 1, 1]); +}); + test("a dictation gate notice takes a close request as Cancel, once", async ctx => { const seen = spyCloseWatcher(ctx); const host = document.createElement("div"); @@ -448,7 +481,8 @@ test("repeated refusals re-arm without joining the surface beneath: one action p document.body.append(openLower, openUpper); let a: ReturnType | null = null, b: ReturnType | null = null; openLower.onclick = () => { a = watchCloseRequests(document, () => { lower++; return true; }, { escape: false }); }; - openUpper.onclick = () => { b = watchCloseRequests(document, () => { upper++; return upperCloses; }, { escape: false }); }; + // When the upper surface closes, its owner destroys the watch, as an unmount does. + openUpper.onclick = () => { b = watchCloseRequests(document, () => { upper++; if (upperCloses) queueMicrotask(() => b!.destroy()); return upperCloses; }, { escape: false }); }; ctx.onTestFinished(() => { a?.destroy(); b?.destroy(); openLower.remove(); openUpper.remove(); }); await userEvent.click(openLower); await userEvent.click(openUpper); for (let i = 1; i <= 8; i++) { From 0aa7cd2083003e018bd463279f3cf643e6eb33fa Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 17:52:06 +0000 Subject: [PATCH 9/9] fix(ui-kit): a drawer under another surface leaves Escape to it (#2577) The overlay stack's document Escape listener stepped aside only while its top drawer was watching. A surface opened after a phone drawer (a dictation field or notice) takes the drawer's watcher, so the stack still took Escape for the drawer and closed it beneath, while Android back closed the surface above. The watch now reports whether its surface is the topmost, and the stack leaves Escape to the surface above when its drawer is not. Co-Authored-By: Claude Opus 5.5 --- packages/ui-kit/src/internal/close-request.ts | 5 ++++ packages/ui-kit/src/internal/overlay-stack.ts | 6 ++-- .../tests/browser/close-requests.pointer.tsx | 30 +++++++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/packages/ui-kit/src/internal/close-request.ts b/packages/ui-kit/src/internal/close-request.ts index 03858c89be..8b1a890fa3 100644 --- a/packages/ui-kit/src/internal/close-request.ts +++ b/packages/ui-kit/src/internal/close-request.ts @@ -40,6 +40,8 @@ export interface CloseRequestWatch { disarm(): void; /** Whether close requests currently reach the surface through a watcher. */ readonly watching: boolean; + /** Whether this is the document's topmost open surface: the only one that takes close requests. */ + readonly topmost: boolean; /** Stop for good: the watcher and the keydown fallback are removed. */ destroy(): void; } @@ -133,6 +135,9 @@ export function watchCloseRequests(document: Document, request: () => boolean, o get watching() { return watcher !== null; }, + get topmost() { + return !destroyed && topmost(); + }, destroy() { if (destroyed) return; destroyed = true; diff --git a/packages/ui-kit/src/internal/overlay-stack.ts b/packages/ui-kit/src/internal/overlay-stack.ts index 106dbcfcee..021eee2cc8 100644 --- a/packages/ui-kit/src/internal/overlay-stack.ts +++ b/packages/ui-kit/src/internal/overlay-stack.ts @@ -23,8 +23,10 @@ export function registerOverlay(document: Document, entry: Entry): () => void { const keys = (event: KeyboardEvent) => { const top = entries.at(-1); // A watching top entry receives Escape as the platform's close request, - // through its watcher: taking it here as well would close twice. - if (event.key !== "Escape" || event.defaultPrevented || event.isComposing || !top || top.modal || top.watch?.watching) return; + // through its watcher: taking it here as well would close twice. An + // entry with a surface opened above it (a dictation field over a + // drawer) is not the topmost surface, so the Escape is that surface's. + if (event.key !== "Escape" || event.defaultPrevented || event.isComposing || !top || top.modal || top.watch?.watching || top.watch?.topmost === false) return; event.preventDefault(); event.stopPropagation(); top.escape(); diff --git a/packages/ui-react/tests/browser/close-requests.pointer.tsx b/packages/ui-react/tests/browser/close-requests.pointer.tsx index c659f2f390..2330aaf6a3 100644 --- a/packages/ui-react/tests/browser/close-requests.pointer.tsx +++ b/packages/ui-react/tests/browser/close-requests.pointer.tsx @@ -16,6 +16,7 @@ import { useState } from "react"; import { flushSync } from "react-dom"; import { createRoot } from "react-dom/client"; import { watchCloseRequests } from "@schlessera/brain-ui-kit/internal"; +import { Overlay } from "@schlessera/brain-ui-kit"; import { BrainUiProvider } from "../../src/root-context.js"; import { createBrainUiRoot } from "../../src/root.js"; import { AppShell } from "../../src/components/layout/app-shell.js"; @@ -395,6 +396,35 @@ test("a disarmed surface above an armed one lets the close request reach the pag expect([take, pane, reachedPage], "then the take").toEqual([1, 1, 1]); }); +for (const watcher of [true, false]) test(`a surface opened over a phone drawer takes Escape, not the drawer beneath${watcher ? "" : " (without CloseWatcher)"}`, async ctx => { + if (watcher) spyCloseWatcher(ctx); else withoutCloseWatcher(ctx); + await page.viewport(390, 800); + const host = document.createElement("div"); + document.body.append(host); + let drawerCloses = 0, surfaceCloses = 0; + function Drawer() { + const [open, setOpen] = useState(false); + return <> + + { drawerCloses++; setOpen(false); }}> +

Ithaca sessions

+
+ ; + } + const renderer = createRoot(host); + ctx.onTestFinished(() => { flushSync(() => renderer.unmount()); host.remove(); }); + flushSync(() => renderer.render()); + await userEvent.click(host.querySelector("[data-test-drawer]")!); await frame(); + expect(document.querySelector('[data-panel], [data-bk-overlay="panel"]'), "the drawer is open").not.toBeNull(); + // A surface opens above the drawer (a dictation notice arriving), from script. + let surface: ReturnType | null = watchCloseRequests(document, () => { surfaceCloses++; queueMicrotask(() => { surface?.destroy(); surface = null; }); return true; }); + ctx.onTestFinished(() => surface?.destroy()); + await userEvent.keyboard("{Escape}"); await frame(); + expect([surfaceCloses, drawerCloses], "the surface on top closes; the drawer beneath stays").toEqual([1, 0]); + await userEvent.keyboard("{Escape}"); await frame(); + expect([surfaceCloses, drawerCloses], "then the drawer").toEqual([1, 1]); +}); + test("a dictation gate notice takes a close request as Cancel, once", async ctx => { const seen = spyCloseWatcher(ctx); const host = document.createElement("div");