Skip to content

Your lightweight open-source personal agent.

fix(webui): scope sidebar autofocus to mobile navigation

Xubin Ren7a317c3968cf
diff --git a/webui/src/App.tsx b/webui/src/App.tsx
index 02e7f46ef..955829fce 100644
--- a/webui/src/App.tsx
+++ b/webui/src/App.tsx
@@ -1125,6 +1125,7 @@ function Shell({
const [sidebarWidth, setSidebarWidth] = useState(readSidebarWidth);
const [sidebarDragging, setSidebarDragging] = useState(false);
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
+ const mobileSidebarRef = useRef<HTMLDivElement>(null);
const [sessionSearchOpen, setSessionSearchOpen] = useState(false);
const mobileWorkbench = useMediaQuery("(max-width: 767px)");
const workbenchState = sidebarState.workbench;
@@ -2739,6 +2740,12 @@ function Shell({
onOpenChange={(open) => setMobileSidebarOpen(open)}
>
<SheetContent
+ ref={mobileSidebarRef}
+ onOpenAutoFocus={(event) => {
+ // Keep opening navigation from focusing the search tooltip trigger.
+ event.preventDefault();
+ mobileSidebarRef.current?.focus({ preventScroll: true });
+ }}
side="left"
showCloseButton={false}
aria-describedby={undefined}
diff --git a/webui/src/components/ui/sheet.tsx b/webui/src/components/ui/sheet.tsx
index 8af54f504..dcafcb179 100644
--- a/webui/src/components/ui/sheet.tsx
+++ b/webui/src/components/ui/sheet.tsx
@@ -74,33 +74,16 @@ const SheetContent = React.forwardRef<
children,
closeButtonClassName,
showCloseButton = true,
- onOpenAutoFocus,
...props
},
ref,
) => {
const { t } = useTranslation();
- const contentNode = React.useRef<HTMLDivElement | null>(null);
- const contentRef = React.useCallback(
- (node: HTMLDivElement | null) => {
- contentNode.current = node;
- if (typeof ref === "function") ref(node);
- else if (ref) ref.current = node;
- },
- [ref],
- );
return (
<SheetPortal>
<SheetOverlay />
<DialogPrimitive.Content
- ref={contentRef}
- onOpenAutoFocus={(event) => {
- if (onOpenAutoFocus) onOpenAutoFocus(event);
- else {
- event.preventDefault();
- contentNode.current?.focus({ preventScroll: true });
- }
- }}
+ ref={ref}
className={cn(
sheetVariants({ side }),
"data-[state=open]:animate-in data-[state=closed]:animate-out",
diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsx
index 17d1992bf..25e8a16e4 100644
--- a/webui/src/tests/app-layout.test.tsx
+++ b/webui/src/tests/app-layout.test.tsx
@@ -287,8 +287,10 @@ import {
fetchBootstrap,
} from "@/lib/bootstrap";
import App from "@/App";
+import { mockBrowserFocus } from "./browser-focus";
describe("App layout", () => {
+ let restoreBrowserFocus: (() => void) | undefined;
beforeEach(async () => {
await i18n.changeLanguage("en");
mockSessions = [];
@@ -342,6 +344,8 @@ describe("App layout", () => {
afterEach(() => {
cleanup();
+ restoreBrowserFocus?.();
+ restoreBrowserFocus = undefined;
Reflect.deleteProperty(window, "nanobotHost");
vi.useRealTimers();
vi.unstubAllGlobals();
@@ -2200,6 +2204,7 @@ describe("App layout", () => {
}, 15_000);
it("opens a mobile topic with one click and closes the drawer without a search tooltip", async () => {
+ restoreBrowserFocus = mockBrowserFocus();
const user = userEvent.setup();
mockSessions = ["First", "Second"].map((title, index) => ({
key: `websocket:mobile-${index}`,
diff --git a/webui/src/tests/browser-focus.ts b/webui/src/tests/browser-focus.ts
new file mode 100644
index 000000000..7fd0e6d34
--- /dev/null
+++ b/webui/src/tests/browser-focus.ts
@@ -0,0 +1,48 @@
+import { vi } from "vitest";
+
+// happy-dom 16 gives native controls tabIndex -1 and treats FILTER_SKIP like
+// FILTER_REJECT, hiding nested inputs/buttons from Radix's autofocus traversal.
+// Scope these browser-compatible shims to tests that exercise real focus order.
+export function mockBrowserFocus() {
+ const tabIndex = vi.spyOn(HTMLElement.prototype, "tabIndex", "get")
+ .mockImplementation(function (this: HTMLElement) {
+ const explicit = this.getAttribute("tabindex");
+ if (explicit !== null) return Number(explicit);
+ if (this.matches("button, input, select, textarea, a[href]")) return 0;
+ return -1;
+ });
+ const createTreeWalker = document.createTreeWalker.bind(document);
+ const treeWalker = vi.spyOn(document, "createTreeWalker").mockImplementation((...args) => {
+ const walker = createTreeWalker(...args);
+ walker.nextNode = function (this: TreeWalker): Node | null {
+ let node: Node | null = this.currentNode;
+ let verdict: number = NodeFilter.FILTER_ACCEPT;
+ while (node) {
+ if (verdict !== NodeFilter.FILTER_REJECT && node.firstChild) {
+ node = node.firstChild;
+ } else {
+ while (node && node !== this.root && !node.nextSibling) node = node.parentNode;
+ if (!node || node === this.root) return null;
+ node = node.nextSibling;
+ }
+ if (!node) return null;
+ verdict = NodeFilter.FILTER_SKIP;
+ if (this.whatToShow & (1 << (node.nodeType - 1))) {
+ verdict = typeof this.filter === "function"
+ ? this.filter(node)
+ : this.filter?.acceptNode(node) ?? NodeFilter.FILTER_ACCEPT;
+ }
+ if (verdict === NodeFilter.FILTER_ACCEPT) {
+ this.currentNode = node;
+ return node;
+ }
+ }
+ return null;
+ };
+ return walker;
+ });
+ return () => {
+ treeWalker.mockRestore();
+ tabIndex.mockRestore();
+ };
+}
diff --git a/webui/src/tests/prompt-navigator.test.tsx b/webui/src/tests/prompt-navigator.test.tsx
new file mode 100644
index 000000000..5928d3195
--- /dev/null
+++ b/webui/src/tests/prompt-navigator.test.tsx
@@ -0,0 +1,37 @@
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+import { PromptNavigator } from "@/components/thread/PromptNavigator";
+import { mockBrowserFocus } from "./browser-focus";
+
+let restoreBrowserFocus: () => void;
+beforeEach(() => {
+ restoreBrowserFocus = mockBrowserFocus();
+});
+
+afterEach(() => restoreBrowserFocus());
+
+it("lets users type into prompt search immediately after opening it", async () => {
+ const user = userEvent.setup();
+ const onJumpToPrompt = vi.fn();
+ render(<PromptNavigator messages={[
+ { id: "one", role: "user", content: "alpha", createdAt: Date.parse("2026-09-21T00:00:00Z") },
+ { id: "two", role: "user", content: "beta", createdAt: Date.parse("2026-09-21T00:01:00Z") },
+ ]} onJumpToPrompt={onJumpToPrompt} />);
+
+ await user.tab();
+ expect(screen.getByRole("button", { name: "Open prompt navigator" })).toHaveFocus();
+ await user.keyboard("{Enter}");
+ const search = await screen.findByRole("textbox", { name: "Search prompts" });
+ await waitFor(() => expect(search).toHaveFocus());
+ await user.keyboard("beta");
+ expect(search).toHaveValue("beta");
+ expect(screen.queryByRole("button", { name: "Jump to prompt: alpha" })).not.toBeInTheDocument();
+
+ await user.tab();
+ expect(screen.getByRole("button", { name: "Jump to prompt: beta" })).toHaveFocus();
+ await user.keyboard("{Enter}");
+ expect(onJumpToPrompt).toHaveBeenCalledWith("two");
+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
+});
diff --git a/webui/src/tests/sheet-autofocus.test.tsx b/webui/src/tests/sheet-autofocus.test.tsx
deleted file mode 100644
index 3bfb0adc4..000000000
--- a/webui/src/tests/sheet-autofocus.test.tsx
+++ /dev/null
@@ -1,141 +0,0 @@
-import { render, screen, waitFor, within } from "@testing-library/react";
-import userEvent from "@testing-library/user-event";
-import { createRef, type Ref } from "react";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { Sheet, SheetContent, SheetTitle, SheetTrigger } from "@/components/ui/sheet";
-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
-
-vi.mock("@/providers/ClientProvider", () => ({
- useClient: () => ({ client: { status: "idle", onStatus: () => () => {} } }),
-}));
-
-function noop() {}
-
-// Reproduces the #5770 chain: the mobile drawer autofocuses the search button
-// (Radix focus-scope default), and focusing a tooltip trigger with no preceding
-// pointerdown opens its tooltip.
-function DrawerWithSearchTooltip(props: {
- onOpenAutoFocus?: (event: Event) => void;
- contentRef?: Ref<HTMLDivElement>;
-}) {
- return (
- <TooltipProvider>
- <Sheet open onOpenChange={noop}>
- <SheetContent
- ref={props.contentRef}
- side="left"
- showCloseButton={false}
- aria-describedby={undefined}
- onOpenAutoFocus={props.onOpenAutoFocus}
- >
- <SheetTitle className="sr-only">Navigation</SheetTitle>
- <Tooltip>
- <TooltipTrigger asChild>
- <button type="button">search</button>
- </TooltipTrigger>
- <TooltipContent side="bottom">Search tip</TooltipContent>
- </Tooltip>
- </SheetContent>
- </Sheet>
- </TooltipProvider>
- );
-}
-
-describe("SheetContent autofocus", () => {
- // happy-dom reports tabIndex -1 for natively focusable elements without an
- // explicit tabindex attribute (browsers report 0), which makes Radix
- // getTabbableCandidates() find nothing. Stub browser behavior so the
- // autofocus path under test actually runs.
- const tabIndexDesc = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "tabIndex");
- beforeEach(() => {
- Object.defineProperty(HTMLElement.prototype, "tabIndex", {
- configurable: true,
- get(this: HTMLElement): number {
- const attr = this.getAttribute("tabindex");
- if (attr !== null) return Number(attr);
- if (/^(BUTTON|A|INPUT|SELECT|TEXTAREA)$/.test(this.tagName)) return 0;
- return -1;
- },
- });
- });
- afterEach(() => {
- if (tabIndexDesc) Object.defineProperty(HTMLElement.prototype, "tabIndex", tabIndexDesc);
- });
-
- it("does not steal focus into the search button or pop its tooltip on open (#5770)", async () => {
- render(<DrawerWithSearchTooltip />);
- const dialog = await screen.findByRole("dialog");
- await waitFor(() => expect(dialog).toHaveFocus());
- const searchButton = within(dialog).getByRole("button", { name: "search" });
- expect(searchButton).not.toHaveFocus();
- expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
- });
-
- it("honors a caller-supplied onOpenAutoFocus handler", async () => {
- const onOpenAutoFocus = vi.fn((event: Event) => event.preventDefault());
- render(<DrawerWithSearchTooltip onOpenAutoFocus={onOpenAutoFocus} />);
- await screen.findByRole("dialog");
- await waitFor(() => expect(onOpenAutoFocus).toHaveBeenCalled());
- });
-
- it("keeps the caller's explicit focus target", async () => {
- render(<DrawerWithSearchTooltip onOpenAutoFocus={(event) => {
- event.preventDefault();
- screen.getByRole("button", { name: "search" }).focus();
- }} />);
- await waitFor(() => expect(screen.getByRole("button", { name: "search" })).toHaveFocus());
- expect(await screen.findByRole("tooltip")).toHaveTextContent("Search tip");
- });
-
- it("allows callers to retain Radix's default autofocus", async () => {
- render(<DrawerWithSearchTooltip onOpenAutoFocus={noop} />);
- await waitFor(() => expect(screen.getByRole("button", { name: "search" })).toHaveFocus());
- });
-
- it("preserves object refs while focusing the container", async () => {
- const ref = createRef<HTMLDivElement>();
- const { unmount } = render(<DrawerWithSearchTooltip contentRef={ref} />);
- const dialog = await screen.findByRole("dialog");
- await waitFor(() => expect(dialog).toHaveFocus());
- expect(ref.current).toBe(dialog);
- unmount();
- expect(ref.current).toBeNull();
- });
-
- it("preserves callback refs on mount and unmount", async () => {
- const ref = vi.fn();
- const { unmount } = render(<DrawerWithSearchTooltip contentRef={ref} />);
- const dialog = await screen.findByRole("dialog");
- await waitFor(() => expect(dialog).toHaveFocus());
- expect(ref).toHaveBeenCalledWith(dialog);
- unmount();
- expect(ref).toHaveBeenLastCalledWith(null);
- });
-
- it("keeps keyboard focus inside the drawer and restores it on Escape", async () => {
- const user = userEvent.setup();
- render(
- <Sheet>
- <SheetTrigger>Open drawer</SheetTrigger>
- <SheetContent showCloseButton={false} aria-describedby={undefined}>
- <SheetTitle>Navigation</SheetTitle>
- <button>First action</button>
- <button>Last action</button>
- </SheetContent>
- </Sheet>,
- );
- const trigger = screen.getByRole("button", { name: "Open drawer" });
- await user.click(trigger);
- await waitFor(() => expect(screen.getByRole("dialog")).toHaveFocus());
- await user.tab();
- expect(screen.getByRole("button", { name: "First action" })).toHaveFocus();
- await user.tab();
- expect(screen.getByRole("button", { name: "Last action" })).toHaveFocus();
- await user.tab();
- expect(screen.getByRole("button", { name: "First action" })).toHaveFocus();
- await user.keyboard("{Escape}");
- await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
- await waitFor(() => expect(trigger).toHaveFocus());
- });
-});