A desktop coding agent with free access to frontier models.
TypeScript
feat: approval keyboard shortcuts
Samrat Talukdar43138f361f0c
diff --git a/apps/app/src/react-app/domains/session/chat/permission-approval-modal.tsx b/apps/app/src/react-app/domains/session/chat/permission-approval-modal.tsxindex dc8f54d0..359b7b82 100644--- a/apps/app/src/react-app/domains/session/chat/permission-approval-modal.tsx+++ b/apps/app/src/react-app/domains/session/chat/permission-approval-modal.tsx@@ -164,6 +164,67 @@ function isFocusableElement(element: HTMLElement) {return style.display !== "none" && style.visibility !== "hidden";}+type PermissionReply = "once" | "always" | "reject";++/** Keyboard shortcuts of the inline approval card. */+export const PERMISSION_SHORTCUTS: Record<PermissionReply, { key: string; label: string }> = {+ once: { key: "Y", label: "Y" },+ always: { key: "A", label: "A" },+ reject: { key: "N", label: "N" },+};++/** Text fields, selects and rich editors keep their keystrokes (the composer above all). */+export function isEditableTarget(target: EventTarget | null): boolean {+ if (!target || typeof (target as { closest?: unknown }).closest !== "function") return false;+ const element = target as Element;+ const tag = element.tagName?.toLowerCase();+ if (tag === "input" || tag === "textarea" || tag === "select") return true;+ if ((element as HTMLElement).isContentEditable) return true;+ return element.closest('[contenteditable]:not([contenteditable="false"])') !== null;+}++/**+ * The reply a key press asks for while an approval card is shown, or null:+ * Y allows once, A allows for the chat, N or Escape denies. Never while focus+ * is in an editable element, in another dialog or menu, or with a modifier.+ */+export function permissionShortcutReply(event: {+ key: string;+ altKey?: boolean;+ ctrlKey?: boolean;+ metaKey?: boolean;+ repeat?: boolean;+ isComposing?: boolean;+ defaultPrevented?: boolean;+ target: EventTarget | null;+}, activeElement: Element | null = typeof document === "undefined" ? null : document.activeElement): PermissionReply | null {+ if (event.defaultPrevented || event.repeat || event.isComposing) return null;+ if (event.altKey || event.ctrlKey || event.metaKey) return null;+ if (isEditableTarget(event.target) || isEditableTarget(activeElement)) return null;+ const inOverlay = (element: EventTarget | null) =>+ !!element+ && typeof (element as { closest?: unknown }).closest === "function"+ && (element as Element).closest('[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]') !== null;+ if (inOverlay(event.target) || inOverlay(activeElement)) return null;+ const key = event.key.length === 1 ? event.key.toLowerCase() : event.key;+ if (key === "y") return "once";+ if (key === "a") return "always";+ if (key === "n" || key === "Escape") return "reject";+ return null;+}++function ShortcutHint(props: { label: string }) {+ return (+ <kbd+ aria-hidden="true"+ data-permission-shortcut={props.label}+ className="ml-1 rounded border border-current/25 px-1 font-sans text-[10px] leading-4 opacity-70"+ >+ {props.label}+ </kbd>+ );+}+function describePermissionRequest(permission: PendingPermission): PermissionPresentation {const patterns = permission.patterns.filter((pattern) => pattern.trim().length > 0);if (permission.permission === "doom_loop") {@@ -381,6 +442,30 @@ export function PermissionApprovalModal(props: PermissionApprovalModalProps) {export function PermissionApprovalPanel(props: PermissionApprovalModalProps) {const presentation = useMemo(() => describePermissionRequest(props.permission), [props.permission]);+ const { busy, respondPermission } = props;+ const permissionId = props.permission.id;+ // One reply per request: a held key or a second press before the card goes away is ignored.+ const repliedRef = useRef<string | null>(null);+ const rootRef = useRef<HTMLDivElement | null>(null);++ useEffect(() => {+ if (busy || !respondPermission) return;+ const onKeyDown = (event: globalThis.KeyboardEvent) => {+ const reply = permissionShortcutReply(event);+ if (!reply || repliedRef.current === permissionId) return;+ // With several chats side by side, the one holding focus answers its own card.+ const surface = '[data-session-surface-id]';+ const focusedSurface = document.activeElement?.closest(surface) ?? null;+ const ownSurface = rootRef.current?.closest(surface) ?? null;+ if (focusedSurface && ownSurface && focusedSurface !== ownSurface) return;+ event.preventDefault();+ event.stopImmediatePropagation();+ repliedRef.current = permissionId;+ respondPermission(permissionId, reply);+ };+ window.addEventListener("keydown", onKeyDown);+ return () => window.removeEventListener("keydown", onKeyDown);+ }, [busy, respondPermission, permissionId]);const metadata =props.permission.metadata && typeof props.permission.metadata === "object"? props.permission.metadata@@ -389,7 +474,7 @@ export function PermissionApprovalPanel(props: PermissionApprovalModalProps) {const Icon = presentation.isDoomLoop ? RefreshCcw : ShieldCheck;return (- <div className="overflow-hidden border-b border-dls-border bg-transparent">+ <div ref={rootRef} data-permission-panel={permissionId} className="overflow-hidden border-b border-dls-border bg-transparent"><div className="flex flex-col gap-3 px-4 py-3 sm:flex-row sm:items-center sm:justify-between"><div className="flex min-w-0 items-start gap-3"><div className="mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-xl border border-dls-border bg-dls-hover text-dls-secondary">@@ -420,18 +505,24 @@ export function PermissionApprovalPanel(props: PermissionApprovalModalProps) {className="border-red-7/25 text-red-11 hover:bg-red-1/40"onClick={() => props.respondPermission?.(props.permission.id, "reject")}disabled={props.busy || !props.respondPermission}+ aria-keyshortcuts="N Escape"+ data-permission-reply="reject"><XCircle data-icon="inline-start" />{t("session.deny")}+ <ShortcutHint label={PERMISSION_SHORTCUTS.reject.label} /></Button><Buttontype="button"size="sm"onClick={() => props.respondPermission?.(props.permission.id, "once")}disabled={props.busy || !props.respondPermission}+ aria-keyshortcuts="Y"+ data-permission-reply="once"><Clock3 data-icon="inline-start" />{t("session.allow_once")}+ <ShortcutHint label={PERMISSION_SHORTCUTS.once.label} /></Button><Buttontype="button"@@ -439,9 +530,12 @@ export function PermissionApprovalPanel(props: PermissionApprovalModalProps) {size="sm"onClick={() => props.respondPermission?.(props.permission.id, "always")}disabled={props.busy || !props.respondPermission}+ aria-keyshortcuts="A"+ data-permission-reply="always"><Check data-icon="inline-start" />{t("session.allow_for_session")}+ <ShortcutHint label={PERMISSION_SHORTCUTS.always.label} /></Button></div></div>diff --git a/apps/app/tests/permission-approval-modal.test.ts b/apps/app/tests/permission-approval-modal.test.tsindex ca1f803c..b792526c 100644--- a/apps/app/tests/permission-approval-modal.test.ts+++ b/apps/app/tests/permission-approval-modal.test.ts@@ -83,7 +83,7 @@ describe("permission approval modal helpers", () => {}),);- expect(buttonText(html)).toEqual(["Deny", "Allow once", "Allow for session"]);+ expect(buttonText(html)).toEqual(["DenyN", "Allow onceY", "Allow for sessionA"]);});test("uses readable labels for generic permission titles", () => {@@ -115,7 +115,7 @@ describe("permission approval modal helpers", () => {expect(html).toContain("Requested by OmniRush browser task");expect(html.toLowerCase()).not.toContain("opencode");expect(permission).toEqual(original);- expect(buttonText(html)).toEqual(["Deny", "Allow once", "Allow for session"]);+ expect(buttonText(html)).toEqual(["DenyN", "Allow onceY", "Allow for sessionA"]);});test("identifies a permission requested by a child session", () => {diff --git a/apps/app/tests/permission-approval-shortcuts.test.tsx b/apps/app/tests/permission-approval-shortcuts.test.tsxnew file mode 100644index 00000000..bf3a74a0--- /dev/null+++ b/apps/app/tests/permission-approval-shortcuts.test.tsx@@ -0,0 +1,137 @@+/** @jsxImportSource react */+import { afterEach, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";++import type { PendingPermission } from "../src/app/types";++if (typeof globalThis.window === "undefined" || typeof globalThis.document === "undefined") {+ GlobalRegistrator.register({ url: "http://localhost/" });+}+Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", { configurable: true, value: true });++const { PermissionApprovalPanel, permissionShortcutReply } = await import("../src/react-app/domains/session/chat/permission-approval-modal");++function pendingPermission(id = "permission-1"): PendingPermission {+ return {+ id,+ sessionID: "session-1",+ permission: "bash",+ patterns: ["git push origin main"],+ metadata: {},+ always: { session: false, project: false },+ receivedAt: 1,+ protocol: "legacy",+ };+}++const mounted: { root: Root; container: HTMLElement }[] = [];++async function mount(props: { busy?: boolean; id?: string } = {}) {+ const replies: string[] = [];+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ mounted.push({ root, container });+ await act(async () => root.render(+ <PermissionApprovalPanel+ permission={pendingPermission(props.id)}+ busy={props.busy}+ respondPermission={(id, reply) => replies.push(`${id}:${reply}`)}+ />,+ ));+ return { container, replies };+}++async function press(key: string, target: EventTarget = document.body, init: KeyboardEventInit = {}) {+ await act(async () => {+ target.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...init }));+ });+}++afterEach(async () => {+ for (const { root, container } of mounted.splice(0)) {+ await act(async () => root.unmount());+ container.remove();+ }+ document.body.innerHTML = "";+});++test("Y allows once, A allows for the chat, N and Escape deny", async () => {+ for (const [key, reply] of [["y", "once"], ["Y", "once"], ["a", "always"], ["n", "reject"], ["Escape", "reject"]] as const) {+ const { replies } = await mount({ id: `p-${key}` });+ await press(key);+ expect({ key, replies }).toEqual({ key, replies: [`p-${key}:${reply}`] });+ // One reply per request, even when the key is pressed again before the card goes away.+ await press(key);+ expect(replies).toHaveLength(1);+ for (const { root, container } of mounted.splice(0)) {+ await act(async () => root.unmount());+ container.remove();+ }+ }+});++test("shows the keys on the buttons", async () => {+ const { container } = await mount();+ const hints = [...container.querySelectorAll("kbd")].map((element) => element.textContent);+ expect(hints).toEqual(["N", "Y", "A"]);+ expect(container.querySelector('[data-permission-reply="once"]')?.getAttribute("aria-keyshortcuts")).toBe("Y");+ expect(container.querySelector('[data-permission-reply="reject"]')?.getAttribute("aria-keyshortcuts")).toBe("N Escape");+});++test("never takes keystrokes from the composer or other text fields", async () => {+ const { replies } = await mount();+ const textarea = document.createElement("textarea");+ const input = document.createElement("input");+ const select = document.createElement("select");+ const editor = document.createElement("div");+ editor.setAttribute("contenteditable", "true");+ const inner = document.createElement("span");+ editor.append(inner);+ document.body.append(textarea, input, select, editor);+ for (const field of [textarea, input, select, editor, inner]) {+ await press("y", field);+ await press("Escape", field);+ }+ textarea.focus();+ await press("a");+ expect(replies).toEqual([]);+ // Focus elsewhere: the card answers again.+ textarea.blur();+ await press("y");+ expect(replies).toEqual(["permission-1:once"]);+});++test("ignores modifier chords, other keys, other dialogs and a busy card", async () => {+ const { replies } = await mount();+ await press("y", document.body, { metaKey: true });+ await press("a", document.body, { ctrlKey: true });+ await press("n", document.body, { altKey: true });+ await press("x");+ await press("Enter");+ const dialog = document.createElement("div");+ dialog.setAttribute("role", "dialog");+ const button = document.createElement("button");+ dialog.append(button);+ document.body.append(dialog);+ await press("y", button);+ expect(replies).toEqual([]);++ const busy = await mount({ busy: true, id: "busy" });+ await press("y");+ expect(busy.replies).toEqual([]);+});++test("permissionShortcutReply reads the key, not the layout of the page", () => {+ const body = document.body;+ expect(permissionShortcutReply({ key: "y", target: body }, body)).toBe("once");+ expect(permissionShortcutReply({ key: "a", target: body }, body)).toBe("always");+ expect(permissionShortcutReply({ key: "N", target: body }, body)).toBe("reject");+ expect(permissionShortcutReply({ key: "Escape", target: body }, body)).toBe("reject");+ expect(permissionShortcutReply({ key: "y", target: body, repeat: true }, body)).toBeNull();+ expect(permissionShortcutReply({ key: "y", target: body, isComposing: true }, body)).toBeNull();+ expect(permissionShortcutReply({ key: "y", target: body, defaultPrevented: true }, body)).toBeNull();+ expect(permissionShortcutReply({ key: "y", target: body, shiftKey: true } as never, body)).toBe("once");+});