Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(settings): keep focus inside the pairing dialog and accounts sheet
Justice Led696995b29c9
diff --git a/src/components/AccountMenu.keys.dom.test.ts b/src/components/AccountMenu.keys.dom.test.tsnew file mode 100644index 0000000000..65589b2666--- /dev/null+++ b/src/components/AccountMenu.keys.dom.test.ts@@ -0,0 +1,23 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, expect, it, vi } from "vitest";+import { setLocale } from "@/lib/i18n";+import { AccountsSheet } from "./AccountMenu";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+afterEach(() => { document.body.innerHTML = ""; });++it("the accounts sheet takes focus when it opens, Escape closes it, and focus returns to what opened it", async () => {+ setLocale("en");+ const opener = document.createElement("button"); document.body.append(opener); opener.focus();+ const host = document.createElement("div"); document.body.append(host);+ const root = createRoot(host), onClose = vi.fn();+ await act(async () => { root.render(createElement(AccountsSheet, { onClose })); });+ const sheet = document.querySelector<HTMLElement>("[data-accounts-sheet]")!;+ expect(sheet.contains(document.activeElement)).toBe(true);+ await act(async () => { sheet.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true })); });+ expect(onClose).toHaveBeenCalledOnce();+ await act(async () => { root.unmount(); });+ expect(document.activeElement).toBe(opener);+});diff --git a/src/components/AccountMenu.tsx b/src/components/AccountMenu.tsxindex 7620ae319a..cb4a37130b 100644--- a/src/components/AccountMenu.tsx+++ b/src/components/AccountMenu.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import { Check, LogOut, Plus, UserRound, X } from "lucide-react";import type { AccountsView, AccountSwitchResult, RailOpenResult } from "../../electron/cloud-account.mjs";import { cn } from "@/lib/cn";@@ -8,6 +8,7 @@ import { usePlaces } from "@/lib/places";import { CLOSE, Heading, PRIMARY, QUIET, SCREEN, SHEET } from "./cloud-buy/parts";import { codeDigits, SignInScreen } from "./cloud-buy/SignInScreen";import { Layer } from "./Layer";+import { useModalDialog } from "../hooks/use-modal-dialog";import type { SidebarMenuItem } from "./SidebarPopoverMenu";export interface AccountsAccess {@@ -162,8 +163,10 @@ export function AccountsSheet({ onClose, adding = null, note: given = null }: {}, () => setNote(t("accounts.failed")));};const active = view?.active ?? null;+ const dialog = useRef<HTMLDivElement>(null);+ useModalDialog(dialog, onClose);return <Layer modal><div className="ui-scrim fixed inset-0 z-[60] flex items-center justify-center p-4" onMouseDown={(event) => event.target === event.currentTarget && onClose()}>- <div role="dialog" aria-modal="true" aria-labelledby="cloud-add-title" data-accounts-sheet className={cn(SHEET, "relative w-full max-w-[420px]")}>+ <div ref={dialog} tabIndex={-1} role="dialog" aria-modal="true" aria-labelledby="cloud-add-title" data-accounts-sheet className={cn(SHEET, "relative w-full max-w-[420px] outline-none")}><button type="button" onClick={onClose} aria-label={t("accounts.close")} className={cn(CLOSE, "absolute end-4 top-4 z-10")}><X size={16} /></button>{add !== null? <AddAccount start={add} onBack={() => (adding !== null ? onClose() : setAdd(null))} onDone={(said) => { setAdd(null); if (said) setNote(said); else onClose(); }} />diff --git a/src/components/Layer.tsx b/src/components/Layer.tsxindex 8729b50830..2c68f68816 100644--- a/src/components/Layer.tsx+++ b/src/components/Layer.tsx@@ -13,8 +13,6 @@ const never = () => () => {};** Render a Layer only while its content is shown: a mounted modal Layer counts as open. On the server, where React* cannot portal, the content stays in place.- *- * A `modal` layer joins the stack of open modals in the order they opened; see `useIsTopLayer`.*/export function Layer({ modal = false, children }: { modal?: boolean; children: ReactNode }) {const [order] = useState(() => ++opened);diff --git a/src/components/PhoneDevicesSection.keys.dom.test.ts b/src/components/PhoneDevicesSection.keys.dom.test.tsnew file mode 100644index 0000000000..de55a3e270--- /dev/null+++ b/src/components/PhoneDevicesSection.keys.dom.test.ts@@ -0,0 +1,57 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { setLocale } from "@/lib/i18n";+import type { CompanionState, PhoneSetupController } from "./PhoneSetupFlow";++vi.mock("@/state/store", () => ({ useStore: () => ({ state: { config: {} } }) }));+vi.mock("./PhoneSetupFlow", () => ({ PhoneSetupFlowView: () => null }));+const { PairDeviceDialog } = await import("./PhoneDevicesSection");++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+const off = { on: false, since: null };+const state = (wifiOn: boolean): CompanionState => ({ enabled: false, keepAwake: false, port: 8810, devices: [], pairing: null, notices: [],+ routes: { wifi: wifiOn ? { on: true, since: 1 } : off, relay: off, tailscale: off, https: off } });+let host: HTMLDivElement, root: Root, opener: HTMLButtonElement;+beforeEach(() => {+ setLocale("en");+ opener = document.createElement("button"); document.body.append(opener); opener.focus();+ host = document.createElement("div"); document.body.append(host);+ root = createRoot(host);+});+afterEach(() => { document.body.innerHTML = ""; });++const open = async (wifiOn: boolean) => {+ const c = { busy: false, act: vi.fn(), useLocal: vi.fn(), start: vi.fn(), cancel: vi.fn() } as unknown as PhoneSetupController;+ const onClose = vi.fn();+ await act(async () => { root.render(createElement(PairDeviceDialog, { c, state: state(wifiOn), onClose })); });+ return { c, onClose, dialog: document.querySelector<HTMLElement>("[data-pair-dialog]")! };+};+const press = async (target: Element, key: string, shiftKey = false) => {+ await act(async () => { target.dispatchEvent(new KeyboardEvent("keydown", { key, shiftKey, bubbles: true, cancelable: true })); });+};++it("opening the pairing dialog takes focus from the Settings button, Tab stays inside, and closing hands focus back", async () => {+ const { dialog, onClose } = await open(false);+ expect(dialog.contains(document.activeElement)).toBe(true);+ const controls = [...dialog.querySelectorAll<HTMLElement>("input, button")];+ controls.at(-1)!.focus();+ await press(controls.at(-1)!, "Tab");+ expect(document.activeElement).toBe(controls[0]);+ await press(controls[0]!, "Tab", true);+ expect(document.activeElement).toBe(controls.at(-1));+ await press(dialog, "Escape");+ expect(onClose).toHaveBeenCalledOnce();+ await act(async () => { root.unmount(); });+ expect(document.activeElement).toBe(opener);+});++it("Escape while the code is showing stops pairing, the same as Done", async () => {+ const { dialog, onClose, c } = await open(true);+ expect(dialog.dataset.pairDialog).toBe("pairing");+ await press(dialog, "Escape");+ expect(c.cancel).toHaveBeenCalledOnce();+ expect(onClose).toHaveBeenCalledOnce();+ await act(async () => { root.unmount(); });+});diff --git a/src/components/PhoneDevicesSection.tsx b/src/components/PhoneDevicesSection.tsxindex 9e7944a341..6ddcffdcc2 100644--- a/src/components/PhoneDevicesSection.tsx+++ b/src/components/PhoneDevicesSection.tsx@@ -21,6 +21,7 @@ import { PhonesList } from "./PhonesList";import { PairedPhones } from "./PairedPhones";import { Card, Switch } from "./SettingsPrimitives";import { Layer } from "./Layer";+import { useModalDialog } from "../hooks/use-modal-dialog";import { productName } from "../lib/brand";import { useStore } from "@/state/store";@@ -217,14 +218,17 @@ export function PairDeviceDialog({ c, state, onClose, secureAddress = false }: {if (secureAddress) start();}, [secureAddress, start]);const chosen = needed.filter((route) => picked[route]);+ const dialog = useRef<HTMLDivElement>(null);+ const dismiss = () => { if (step === "pairing") c.cancel(); onClose(); };+ useModalDialog(dialog, dismiss);const begin = async () => {for (const route of chosen) await c.act((bridge) => setRoute(bridge, route, true));setStep("pairing");c.useLocal();};return <Layer modal>- <div role="dialog" aria-modal="true" aria-label={step === "consent" ? t("devices.pair.title") : t("devices.pair.titlePhone")}- className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 p-4" data-pair-dialog={step}>+ <div ref={dialog} tabIndex={-1} role="dialog" aria-modal="true" aria-label={step === "consent" ? t("devices.pair.title") : t("devices.pair.titlePhone")}+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 p-4 outline-none" data-pair-dialog={step}><div className="flex max-h-full w-full max-w-[460px] flex-col gap-4 overflow-y-auto rounded-2xl bg-card p-5 shadow-xl"><div className="text-[15px] font-semibold text-ink">{step === "consent" ? t("devices.pair.title") : t("devices.pair.titlePhone")}</div>{step === "consent" ? (@@ -254,7 +258,7 @@ export function PairDeviceDialog({ c, state, onClose, secureAddress = false }: {<PhoneSetupFlowView controller={c} /><div className="text-[12px] leading-relaxed text-ink-secondary">{reachLine(state)}</div><div className="flex justify-end">- <button type="button" className={button} onClick={() => { c.cancel(); onClose(); }}>{t("devices.pair.done")}</button>+ <button type="button" className={button} onClick={dismiss}>{t("devices.pair.done")}</button></div></>)}