Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(ui): zoom the whole app window with Ctrl + Plus / Minus / 0
rubenluetke10-beep26ad57eac386
diff --git a/docs/os-parity.md b/docs/os-parity.mdindex 6f9a884a44..0d121175fa 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -144,6 +144,22 @@ audio are not established by the portable tests. See[workspace architecture](igentic-workspaces.md) for the product and executioncontract.+## Whole-window zoom (2026-10-01, T2)++Ctrl + `+` / `-` / `0` (Command on macOS; rebindable under Settings → Keyboard+shortcuts) zoom the whole app window. The level goes to the WebView engine,+never to CSS `zoom`, so `100vh` layouts reflow instead of overflowing:+Windows sets WebView2 `ZoomFactor` on the UI thread, macOS 11+ sets+WKWebView `pageZoom` on the main thread, Linux sets WebKitGTK+`zoom_level` on the GLib loop (`jarvis/ui/window_zoom.py`). The Qt backend,+macOS 10.x, a browser tab and a headless server answer `ok: false`; the page+then leaves the keys alone (a browser keeps its own zoom). `+` and `-` are+matched by the character typed, so German and US layouts both work+(`lib/appZoom.ts`). Windows verified live on the Dev instance; macOS and+Linux branches are unit-tested with fakes only. Tests:+`tests/unit/ui/test_window_zoom.py`, `src/lib/appZoom.test.ts`,+`src/hooks/useAppZoom.test.tsx`.+## Window caption (2026-09-21, T2)The desktop window is frameless on Windows, macOS and Linux. The page drawsdiff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex 368272d21d..cc4b7876db 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -4947,6 +4947,19 @@ class DesktopApp:logger.exception("Could not read whether the window is maximized")return run_window_command(window, action, maximized=maximized)+ def set_window_zoom(self, factor: float, view: str | None) -> dict[str, Any]:+ """Zoom one live window's page. Worker-thread safe.++ A detached view targets that window. Anything else targets the main+ window. See ``jarvis.ui.window_zoom`` for the per-engine details.+ """+ from jarvis.ui.window_zoom import set_window_zoom++ window = self._detached_windows.get(view) if view else None+ if window is None:+ window = self._window+ return set_window_zoom(window, factor)+def _arm_window_frame(self, window: Any) -> None:"""Let a frameless Windows window still be resized from its edges.diff --git a/jarvis/ui/web/desktop_routes.py b/jarvis/ui/web/desktop_routes.pyindex 87560855d7..2d9f1a175c 100644--- a/jarvis/ui/web/desktop_routes.py+++ b/jarvis/ui/web/desktop_routes.py@@ -193,6 +193,30 @@ async def window_command(body: WindowCommandBody, request: Request) -> dict[str,return {"ok": False, "reason": "command_failed"}+class WindowZoomBody(BaseModel):+ factor: float = Field(ge=0.25, le=5.0)+ view: str | None = Field(default=None, max_length=64)++[email protected]("/zoom", operation_id="zoom")+async def window_zoom(body: WindowZoomBody, request: Request) -> dict[str, Any]:+ """Zoom the page of the window the page is showing (1.0 = 100 %).++ Real engine zoom, the way a browser's Ctrl + `+` works. A browser tab or a+ headless server answers ``ok: false``; the page then leaves zoom to the+ browser. ``view`` names a detached window. Omitted, the main window is used.+ """+ desktop = getattr(request.app.state, "desktop_app", None)+ fn = getattr(desktop, "set_window_zoom", None)+ if not callable(fn):+ return {"ok": False, "reason": "no_desktop_shell"}+ try:+ return await asyncio.to_thread(fn, body.factor, body.view or None)+ except Exception as exc: # noqa: BLE001+ log.warning("window zoom failed: %s", exc, exc_info=True)+ return {"ok": False, "reason": "zoom_failed"}++@router.post("/fullscreen", operation_id="fullscreen")async def window_fullscreen(body: FullscreenBody, request: Request) -> dict[str, Any]:"""Enter or leave native desktop fullscreen."""diff --git a/jarvis/ui/web/frontend/src/App.tsx b/jarvis/ui/web/frontend/src/App.tsxindex a8f4efd8cb..d226677154 100644--- a/jarvis/ui/web/frontend/src/App.tsx+++ b/jarvis/ui/web/frontend/src/App.tsx@@ -48,6 +48,7 @@ const QuickSwitcher = lazy(() =>);import { eventMatchesChord } from "@/lib/quickSwitchChord";import { useQuickSwitchSettings } from "@/store/quickSwitchSettings";+import { useAppZoom } from "@/hooks/useAppZoom";import { useQuickSwitcher } from "@/store/quickSwitcher";import { JarvisDock } from "@/components/JarvisDock";import { CliConnectPoller } from "@/components/CliConnectPoller";@@ -153,6 +154,12 @@ export default function App() {useAssistantNameSeed();useCodingMode();useFileDropGuard();+ /*+ * Ctrl + `+` / `-` / `0` zoom the whole window, like a browser — real engine+ * zoom through the desktop shell. Chords and on/off live under Settings →+ * Keyboard shortcuts. See hooks/useAppZoom.+ */+ useAppZoom();/** A reload puts the user back on the section they were on.*diff --git a/jarvis/ui/web/frontend/src/components/ShortcutOverlay.tsx b/jarvis/ui/web/frontend/src/components/ShortcutOverlay.tsxindex 259b74f091..03c9e1bf66 100644--- a/jarvis/ui/web/frontend/src/components/ShortcutOverlay.tsx+++ b/jarvis/ui/web/frontend/src/components/ShortcutOverlay.tsx@@ -15,6 +15,8 @@ import * as Dialog from "@radix-ui/react-dialog";import { Keyboard, X } from "lucide-react";import { useKeybinds } from "@/hooks/useHotkey";import { useQuickSwitchSettings } from "@/store/quickSwitchSettings";+import { useAppZoomSettings } from "@/store/appZoomSettings";+import { appZoomCaps, type AppZoomIntent } from "@/lib/appZoom";import { detectKeyboardPlatform } from "@/views/settings/keyboardLayout";import {SHORTCUT_AREAS,@@ -26,6 +28,12 @@ import {import { cn } from "@/lib/utils";import { useT } from "@/i18n";+const APP_ZOOM_SETTING_INTENT: Record<string, AppZoomIntent | undefined> = {+ app_zoom_in: "in",+ app_zoom_out: "out",+ app_zoom_reset: "reset",+};+/** One keycap. Colours come from theme tokens, so it reads in both modes. */function Cap({ children }: { children: React.ReactNode }) {return (@@ -72,6 +80,7 @@ function ShortcutRow({ shortcut, isMac }: { shortcut: Shortcut; isMac: boolean }const t = useT();const { config } = useKeybinds();const quickSwitch = useQuickSwitchSettings();+ const appZoom = useAppZoomSettings();let chord: React.ReactNode;if (shortcut.kind === "fixed") {@@ -90,11 +99,14 @@ function ShortcutRow({ shortcut, isMac }: { shortcut: Shortcut; isMac: boolean });} else if (shortcut.kind === "app") {// A per-device setting: show what this machine uses, or that it is off.- chord = quickSwitch.enabled && quickSwitch.combo ? (- <Chord keys={comboTokens(quickSwitch.combo)} isMac={isMac} />+ const zoomIntent = APP_ZOOM_SETTING_INTENT[shortcut.setting];+ const on = zoomIntent ? appZoom.enabled : quickSwitch.enabled;+ const combo = zoomIntent ? appZoom.bindings[zoomIntent] : quickSwitch.combo;+ chord = on && combo ? (+ zoomIntent ? <Chord keys={appZoomCaps(combo)} isMac={false} /> : <Chord keys={comboTokens(combo)} isMac={isMac} />) : (<span className="text-xs italic text-muted-foreground">- {t(quickSwitch.enabled ? "shortcut_overlay.unassigned" : "shortcut_overlay.off")}+ {t(on ? "shortcut_overlay.unassigned" : "shortcut_overlay.off")}</span>);} else {diff --git a/jarvis/ui/web/frontend/src/hooks/useAppZoom.test.tsx b/jarvis/ui/web/frontend/src/hooks/useAppZoom.test.tsxnew file mode 100644index 0000000000..2a89a912be--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useAppZoom.test.tsx@@ -0,0 +1,115 @@+/**+ * Ctrl + Plus / Minus / 0 zoom the desktop window through the shell, and leave+ * the keys alone wherever they belong to someone else.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, renderHook, waitFor } from "@testing-library/react";++import { useAppZoom, useAppZoomSupport } from "./useAppZoom";+import {+ APP_ZOOM_STORAGE_KEY,+ readAppZoomSettings,+ useAppZoomSettings,+} from "@/store/appZoomSettings";++type Host = { __JARVIS_EMBEDDED_DESKTOP?: boolean };++function answer(body: unknown) {+ return vi.fn(async () => new Response(JSON.stringify(body), { status: 200 }));+}++function sentFactors(fetchMock: ReturnType<typeof vi.fn>): number[] {+ return fetchMock.mock.calls.map((call) => JSON.parse(String((call[1] as RequestInit).body)).factor);+}++describe("useAppZoom", () => {+ beforeEach(() => {+ window.localStorage.removeItem(APP_ZOOM_STORAGE_KEY);+ useAppZoomSettings.setState(readAppZoomSettings());+ useAppZoomSupport.setState({ support: "unknown" });+ (window as Host).__JARVIS_EMBEDDED_DESKTOP = true;+ });+ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ delete (window as Host).__JARVIS_EMBEDDED_DESKTOP;+ });++ it("zooms the window in on Ctrl+Plus (German key) and out on Ctrl+Minus", async () => {+ const fetchMock = answer({ ok: true, zoom: 1 });+ vi.stubGlobal("fetch", fetchMock);+ renderHook(() => useAppZoom());+ await waitFor(() => expect(useAppZoomSupport.getState().support).toBe("native"));++ expect(fireEvent.keyDown(document.body, { key: "+", code: "BracketRight", ctrlKey: true })).toBe(false);+ expect(useAppZoomSettings.getState().level).toBe(1.1);+ fireEvent.keyDown(document.body, { key: "-", code: "Slash", ctrlKey: true });+ fireEvent.keyDown(document.body, { key: "-", code: "Slash", ctrlKey: true });+ expect(useAppZoomSettings.getState().level).toBe(0.9);+ fireEvent.keyDown(document.body, { key: "0", code: "Digit0", ctrlKey: true });+ expect(useAppZoomSettings.getState().level).toBe(1);++ await waitFor(() => expect(sentFactors(fetchMock)).toEqual([1, 1.1, 1, 0.9, 1]));+ expect(readAppZoomSettings().level).toBe(1);+ });++ it("re-applies a remembered level when the window opens", async () => {+ useAppZoomSettings.getState().setLevel(1.25);+ const fetchMock = answer({ ok: true, zoom: 1.25 });+ vi.stubGlobal("fetch", fetchMock);+ renderHook(() => useAppZoom());+ await waitFor(() => expect(sentFactors(fetchMock)).toEqual([1.25]));+ });++ it("yields to a terminal pane that claimed the chord first", async () => {+ vi.stubGlobal("fetch", answer({ ok: true, zoom: 1 }));+ const terminal = (event: Event) => event.stopPropagation();+ window.addEventListener("keydown", terminal, true);+ renderHook(() => useAppZoom());++ fireEvent.keyDown(document.body, { key: "+", code: "BracketRight", ctrlKey: true });+ expect(useAppZoomSettings.getState().level).toBe(1);+ window.removeEventListener("keydown", terminal, true);+ });++ it("leaves the keys to a recorder that is capturing", async () => {+ vi.stubGlobal("fetch", answer({ ok: true, zoom: 1 }));+ const recorder = document.createElement("div");+ recorder.setAttribute("data-keybind-recording", "true");+ document.body.appendChild(recorder);+ renderHook(() => useAppZoom());++ expect(fireEvent.keyDown(document.body, { key: "+", code: "BracketRight", ctrlKey: true })).toBe(true);+ expect(useAppZoomSettings.getState().level).toBe(1);+ recorder.remove();+ });++ it("leaves the keys to the browser in a browser tab", () => {+ delete (window as Host).__JARVIS_EMBEDDED_DESKTOP;+ const fetchMock = answer({ ok: false });+ vi.stubGlobal("fetch", fetchMock);+ renderHook(() => useAppZoom());++ expect(fireEvent.keyDown(document.body, { key: "+", code: "BracketRight", ctrlKey: true })).toBe(true);+ expect(fetchMock).not.toHaveBeenCalled();+ expect(useAppZoomSupport.getState().support).toBe("browser");+ });++ it("stops claiming the keys when the engine cannot zoom", async () => {+ vi.stubGlobal("fetch", answer({ ok: false, reason: "zoom_unsupported" }));+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ renderHook(() => useAppZoom());+ await waitFor(() => expect(useAppZoomSupport.getState().support).toBe("unsupported"));++ expect(fireEvent.keyDown(document.body, { key: "+", code: "BracketRight", ctrlKey: true })).toBe(true);+ warn.mockRestore();+ });++ it("does nothing when switched off", () => {+ vi.stubGlobal("fetch", answer({ ok: true, zoom: 1 }));+ useAppZoomSettings.getState().setEnabled(false);+ renderHook(() => useAppZoom());++ expect(fireEvent.keyDown(document.body, { key: "+", code: "BracketRight", ctrlKey: true })).toBe(true);+ });+});diff --git a/jarvis/ui/web/frontend/src/hooks/useAppZoom.ts b/jarvis/ui/web/frontend/src/hooks/useAppZoom.tsnew file mode 100644index 0000000000..dc1e00f2c2--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useAppZoom.ts@@ -0,0 +1,103 @@+/**+ * Ctrl + `+` / `-` / `0` (or whatever chords are set under Settings →+ * Keyboard shortcuts) zoom the whole app window, the way they zoom a browser.+ *+ * ## Real window zoom, not CSS+ *+ * The level is handed to the desktop shell, which sets the WebView engine's own+ * page zoom (see `jarvis/ui/window_zoom.py`). CSS `zoom` on the page would be+ * the easy route and the wrong one: it scales `100vh` layouts past the window+ * edge and misplaces popovers. The engine zoom shrinks the CSS viewport+ * instead, so every layout simply reflows.+ *+ * ## Where it does nothing on purpose+ *+ * * A browser tab: the browser already zooms with these keys, persistently and+ * per site. The keys are left to it.+ * * A desktop shell whose engine cannot zoom (the Qt backend): the shell says+ * so on the first try, and the keys are left alone from then on, so the+ * chord never looks swallowed.+ * * A focused terminal pane of the Agentic IDE: there Ctrl + `+` / `-` makes+ * the terminal text bigger, the way every terminal does. That bridge sits on+ * `window` in the capture phase and stops the event before it reaches this+ * one, which is registered on `document` for exactly that ordering.+ * * While a shortcut recorder is capturing keys.+ */+import { useEffect } from "react";+import { create } from "zustand";++import { hasEmbeddedDesktopBridge } from "@/components/voice/BrowserRealtimeControl";+import { appZoomIntentFor, nextAppZoom } from "@/lib/appZoom";+import { useAppZoomSettings } from "@/store/appZoomSettings";+import { useEventStore } from "@/store/events";++/** Whether this window's engine zooms: unknown until the first answer. */+export type AppZoomSupport = "unknown" | "native" | "browser" | "unsupported";++export const useAppZoomSupport = create<{ support: AppZoomSupport }>(() => ({+ support: "unknown",+}));++function windowView(): string | null {+ const { solo, activeSection } = useEventStore.getState();+ return solo ? activeSection : null;+}++async function applyWindowZoom(level: number): Promise<void> {+ try {+ const res = await fetch("/api/window/zoom", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ factor: level, view: windowView() }),+ });+ const body = (res.ok ? await res.json() : null) as { ok?: boolean; reason?: string } | null;+ if (body?.ok) {+ useAppZoomSupport.setState({ support: "native" });+ return;+ }+ // A failure on an engine that zoomed before is a hiccup, not a verdict.+ if (useAppZoomSupport.getState().support !== "native") {+ useAppZoomSupport.setState({ support: "unsupported" });+ }+ console.warn("Window zoom unavailable:", body?.reason ?? res.status);+ } catch (error: unknown) {+ console.warn("Window zoom failed", error);+ }+}++export function useAppZoom(): void {+ const enabled = useAppZoomSettings((s) => s.enabled);+ const bindings = useAppZoomSettings((s) => s.bindings);+ const level = useAppZoomSettings((s) => s.level);+ const embedded = hasEmbeddedDesktopBridge();++ useEffect(() => {+ if (!embedded) useAppZoomSupport.setState({ support: "browser" });+ }, [embedded]);++ // Apply the level to THIS window — on start (the window opens at 100 %), on+ // every step, and when another window changed it through storage.+ useEffect(() => {+ if (!embedded) return;+ void applyWindowZoom(level);+ }, [embedded, level]);++ useEffect(() => {+ if (!embedded || !enabled) return;+ const onKeyDown = (event: KeyboardEvent) => {+ if (useAppZoomSupport.getState().support === "unsupported") return;+ if (document.querySelector('[data-keybind-recording="true"]')) return;+ const intent = appZoomIntentFor(event, bindings);+ if (intent === null) return;+ // Also stops the WebView's own accelerator, which is on in debug builds.+ // Not stopped from propagating: the key tester on the Keyboard shortcuts+ // page listens further down and names what the chord did.+ event.preventDefault();+ const { level: current, setLevel } = useAppZoomSettings.getState();+ const next = nextAppZoom(current, intent);+ if (next !== current) setLevel(next);+ };+ document.addEventListener("keydown", onKeyDown, true);+ return () => document.removeEventListener("keydown", onKeyDown, true);+ }, [embedded, enabled, bindings]);+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex fcdbea4521..ce2684b775 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -1621,6 +1621,9 @@"zoom_in": "Terminaltext größer","zoom_out": "Terminaltext kleiner","zoom_reset": "Terminaltextgröße zurücksetzen",+ "app_zoom_in": "Ganze App vergrößern",+ "app_zoom_out": "Ganze App verkleinern",+ "app_zoom_reset": "App-Zoom auf 100 % zurücksetzen","open_overlay": "Diese Liste öffnen","quick_switch": "Schnell zu jedem Bereich springen"}@@ -2671,6 +2674,21 @@"problem_app_reserved": "Jarvis nutzt diese Kombination schon (Kopieren, Einfügen, Rückgängig oder die Wiki- und Docs-Suche). Wähle eine andere.","problem_voice_taken": "Ein Sprach-Kürzel nutzt genau diese Kombination schon und reagiert vor der Schnellsuche. Wähle eine andere."},+ "app_zoom": {+ "title": "Zoom",+ "description": "Macht alles im Jarvis-Fenster größer oder kleiner, so wie Strg + Plus im Browser. Funktioniert mit deutscher und englischer Tastatur: Plus und Minus werden als das Zeichen gelesen, das du tippst, egal wo die Taste liegt.",+ "level_label": "Aktuelle Größe",+ "in_label": "Hineinzoomen",+ "out_label": "Herauszoomen",+ "reset_label": "Zurück auf 100 %",+ "problem_typing_key": "Diese Taste allein würde bei jedem Tippen zoomen. Nimm Strg, Alt oder Command dazu — oder eine Funktionstaste wie F9.",+ "problem_os_reserved": "Die Windows-Taste gehört dem System (Windows + Plus öffnet die Bildschirmlupe). Wähle eine Kombination mit Strg oder Alt.",+ "problem_duplicate": "Ein anderer Zoom-Schritt nutzt genau diese Kombination schon.",+ "problem_quick_switch": "Die Schnellsuche nutzt genau diese Kombination schon.",+ "note_terminal": "Im Agentic IDE ändern Strg + Plus und Strg + Minus stattdessen die Schriftgröße der Terminals.",+ "note_browser": "In einem Browser-Tab gilt der Zoom des Browsers — diese Tasten zoomen nur das Jarvis-Desktopfenster.",+ "note_unsupported": "Dieses Fenster kann auf diesem System nicht zoomen. Die Tasten bleiben frei."+ },"keybinds": {"title": "Sprach-Tastenkürzel","description": "Lege die Tasten für Anruf und Auflegen fest. Klick auf Aufnehmen und drücke deine Kombination — oder klick die Tasten auf der Bildschirm-Tastatur an. Die Tastenkürzel fürs Diktat findest du im Sprachbereich unter Tastenkürzel. Änderungen greifen sofort.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 27cb931086..173117a052 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -1654,6 +1654,9 @@"zoom_in": "Larger terminal text","zoom_out": "Smaller terminal text","zoom_reset": "Reset terminal text size",+ "app_zoom_in": "Zoom the whole app in",+ "app_zoom_out": "Zoom the whole app out",+ "app_zoom_reset": "Reset the app zoom to 100 %","open_overlay": "Open this list","quick_switch": "Quick switch to any section"}@@ -2704,6 +2707,21 @@"problem_app_reserved": "Jarvis already uses this combination (copy, paste, undo or the Wiki and Docs search). Pick another one.","problem_voice_taken": "A voice shortcut already uses exactly this combination, and it fires before the quick switcher can. Pick another one."},+ "app_zoom": {+ "title": "Zoom",+ "description": "Make everything in the Jarvis window bigger or smaller, the way Ctrl + Plus zooms a browser. Works with German and English keyboards: Plus and Minus are read as the characters you type, wherever they sit.",+ "level_label": "Current size",+ "in_label": "Zoom in",+ "out_label": "Zoom out",+ "reset_label": "Back to 100 %",+ "problem_typing_key": "This key alone would zoom every time you type it. Add Ctrl, Alt or Command — or use a function key such as F9.",+ "problem_os_reserved": "The Windows key belongs to the system (Windows + Plus opens the magnifier). Pick a chord with Ctrl or Alt.",+ "problem_duplicate": "Another zoom step already uses exactly this combination.",+ "problem_quick_switch": "The quick switcher already uses exactly this combination.",+ "note_terminal": "In the Agentic IDE, Ctrl + Plus and Ctrl + Minus change the terminal text size instead.",+ "note_browser": "In a browser tab, your browser's own zoom applies — these keys only zoom the Jarvis desktop window.",+ "note_unsupported": "This window cannot zoom on this system. The keys are left alone."+ },"keybinds": {"title": "Voice Keybinds","description": "Set the keys for starting a call and for hanging up. Click Record and press your combination — or click keys on the on-screen keyboard. The dictation shortcuts live in the voice section, under Shortcuts. Changes apply instantly.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 51cc835bb8..b9520c9858 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -1621,6 +1621,9 @@"zoom_in": "Texto del terminal más grande","zoom_out": "Texto del terminal más pequeño","zoom_reset": "Restablecer el tamaño del texto",+ "app_zoom_in": "Acercar toda la aplicación",+ "app_zoom_out": "Alejar toda la aplicación",+ "app_zoom_reset": "Restablecer el zoom de la aplicación al 100 %","open_overlay": "Abrir esta lista","quick_switch": "Saltar rápido a cualquier sección"}@@ -2671,6 +2674,21 @@"problem_app_reserved": "Jarvis ya usa esta combinación (copiar, pegar, deshacer o la búsqueda de Wiki y Docs). Elige otra.","problem_voice_taken": "Un atajo de voz ya usa exactamente esta combinación y se activa antes que el cambio rápido. Elige otra."},+ "app_zoom": {+ "title": "Zoom",+ "description": "Agranda o reduce todo lo que hay en la ventana de Jarvis, como Ctrl + Más en un navegador. Funciona con teclados alemanes e ingleses: Más y Menos se leen como el carácter que escribes, esté donde esté la tecla.",+ "level_label": "Tamaño actual",+ "in_label": "Acercar",+ "out_label": "Alejar",+ "reset_label": "Volver al 100 %",+ "problem_typing_key": "Esta tecla sola haría zoom cada vez que la escribes. Añade Ctrl, Alt o Command, o usa una tecla de función como F9.",+ "problem_os_reserved": "La tecla Windows pertenece al sistema (Windows + Más abre la lupa). Elige una combinación con Ctrl o Alt.",+ "problem_duplicate": "Otro paso de zoom ya usa exactamente esta combinación.",+ "problem_quick_switch": "El cambio rápido ya usa exactamente esta combinación.",+ "note_terminal": "En el Agentic IDE, Ctrl + Más y Ctrl + Menos cambian en su lugar el tamaño del texto de los terminales.",+ "note_browser": "En una pestaña del navegador se aplica el zoom del propio navegador; estas teclas solo hacen zoom en la ventana de escritorio de Jarvis.",+ "note_unsupported": "Esta ventana no puede hacer zoom en este sistema. Las teclas quedan libres."+ },"keybinds": {"title": "Atajos de voz","description": "Configura las teclas para llamar y colgar. Pulsa Grabar y presiona tu combinación — o haz clic en las teclas del teclado en pantalla. Los atajos de dictado están en la sección de voz, en Atajos. Los cambios se aplican al instante.",diff --git a/jarvis/ui/web/frontend/src/lib/appZoom.test.ts b/jarvis/ui/web/frontend/src/lib/appZoom.test.tsnew file mode 100644index 0000000000..aa9f2f6116--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/appZoom.test.ts@@ -0,0 +1,126 @@+import { describe, expect, it } from "vitest";++import {+ appZoomCaps,+ appZoomComboFromEvent,+ appZoomComboProblem,+ appZoomIntentFor,+ defaultAppZoomBindings,+ nextAppZoom,+ snapAppZoom,+ type AppZoomKeyEvent,+} from "./appZoom";++const PC = defaultAppZoomBindings("pc");+const MAC = defaultAppZoomBindings("mac");++function key(init: Partial<AppZoomKeyEvent> & Pick<AppZoomKeyEvent, "key" | "code">): AppZoomKeyEvent {+ return { ctrlKey: false, metaKey: false, altKey: false, shiftKey: false, ...init };+}++describe("the default chords on a German keyboard", () => {+ it("zooms in with the Plus key, which US calls BracketRight", () => {+ expect(appZoomIntentFor(key({ key: "+", code: "BracketRight", ctrlKey: true }), PC)).toBe("in");+ });++ it("zooms out with the Minus key, which US calls Slash", () => {+ expect(appZoomIntentFor(key({ key: "-", code: "Slash", ctrlKey: true }), PC)).toBe("out");+ });++ it("does not read Ctrl+Shift+0 (the = sign there) as zoom in or reset", () => {+ expect(appZoomIntentFor(key({ key: "=", code: "Digit0", ctrlKey: true, shiftKey: true }), PC)).toBeNull();+ });++ it("ignores AltGr+Plus, the tilde", () => {+ const altGr = key({ key: "~", code: "BracketRight", ctrlKey: true, altKey: true });+ expect(appZoomIntentFor(altGr, PC)).toBeNull();+ const reported = { ...key({ key: "+", code: "BracketRight", ctrlKey: true }), getModifierState: (k: string) => k === "AltGraph" };+ expect(appZoomIntentFor(reported, PC)).toBeNull();+ });+});++describe("the default chords on a US keyboard", () => {+ it("zooms in with Ctrl+= and with Ctrl+Shift+= (the + sign)", () => {+ expect(appZoomIntentFor(key({ key: "=", code: "Equal", ctrlKey: true }), PC)).toBe("in");+ expect(appZoomIntentFor(key({ key: "+", code: "Equal", ctrlKey: true, shiftKey: true }), PC)).toBe("in");+ });++ it("zooms out with Ctrl+- and Ctrl+_", () => {+ expect(appZoomIntentFor(key({ key: "-", code: "Minus", ctrlKey: true }), PC)).toBe("out");+ expect(appZoomIntentFor(key({ key: "_", code: "Minus", ctrlKey: true, shiftKey: true }), PC)).toBe("out");+ });++ it("resets with Ctrl+0 but not Ctrl+Shift+0", () => {+ expect(appZoomIntentFor(key({ key: "0", code: "Digit0", ctrlKey: true }), PC)).toBe("reset");+ expect(appZoomIntentFor(key({ key: ")", code: "Digit0", ctrlKey: true, shiftKey: true }), PC)).toBeNull();+ });+});++describe("the numeric keypad", () => {+ it("counts on every layout, NumLock or not", () => {+ expect(appZoomIntentFor(key({ key: "+", code: "NumpadAdd", ctrlKey: true }), PC)).toBe("in");+ expect(appZoomIntentFor(key({ key: "-", code: "NumpadSubtract", ctrlKey: true }), PC)).toBe("out");+ expect(appZoomIntentFor(key({ key: "0", code: "Numpad0", ctrlKey: true }), PC)).toBe("reset");+ expect(appZoomIntentFor(key({ key: "Insert", code: "NumpadInsert", ctrlKey: true }), PC)).toBe("reset");+ });+});++describe("the platform modifier", () => {+ it("is Command on a Mac and Ctrl elsewhere", () => {+ expect(appZoomIntentFor(key({ key: "=", code: "Equal", metaKey: true }), MAC)).toBe("in");+ expect(appZoomIntentFor(key({ key: "=", code: "Equal", ctrlKey: true }), MAC)).toBeNull();+ expect(appZoomIntentFor(key({ key: "+", code: "BracketRight", metaKey: true }), PC)).toBeNull();+ });++ it("plain typing never zooms", () => {+ expect(appZoomIntentFor(key({ key: "+", code: "BracketRight" }), PC)).toBeNull();+ });+});++describe("recording", () => {+ it("stores Plus and Minus as characters, without the Shift a layout needs", () => {+ expect(appZoomComboFromEvent(key({ key: "+", code: "Equal", ctrlKey: true, shiftKey: true }), "pc")).toBe("ctrl+plus");+ expect(appZoomComboFromEvent(key({ key: "-", code: "Slash", ctrlKey: true }), "pc")).toBe("ctrl+minus");+ });++ it("stores letters by position and keeps Shift", () => {+ expect(appZoomComboFromEvent(key({ key: "Z", code: "KeyZ", ctrlKey: true, shiftKey: true }), "pc")).toBe("ctrl+shift+z");+ });++ it("waits while only modifiers are held", () => {+ expect(appZoomComboFromEvent(key({ key: "Control", code: "ControlLeft", ctrlKey: true }), "pc")).toBeNull();+ });++ it("a recorded custom chord matches back", () => {+ const combo = appZoomComboFromEvent(key({ key: "ArrowUp", code: "ArrowUp", altKey: true }), "pc");+ expect(appZoomIntentFor(key({ key: "ArrowUp", code: "ArrowUp", altKey: true }), { ...PC, in: combo! })).toBe("in");+ });++ it("refuses typing keys, the Windows key and duplicates", () => {+ expect(appZoomComboProblem("plus", [], "pc")).toBe("typing_key");+ expect(appZoomComboProblem("f9", [], "pc")).toBeNull();+ expect(appZoomComboProblem("win+plus", [], "pc")).toBe("os_reserved");+ expect(appZoomComboProblem("cmd+plus", [], "mac")).toBeNull();+ expect(appZoomComboProblem("ctrl+minus", ["control+minus"], "pc")).toBe("duplicate");+ });+});++describe("levels", () => {+ it("steps along the browser ladder and stops at its ends", () => {+ expect(nextAppZoom(1, "in")).toBe(1.1);+ expect(nextAppZoom(1, "out")).toBe(0.9);+ expect(nextAppZoom(3, "in")).toBe(3);+ expect(nextAppZoom(0.5, "out")).toBe(0.5);+ expect(nextAppZoom(1.75, "reset")).toBe(1);+ });++ it("snaps a stray stored value", () => {+ expect(snapAppZoom(1.12)).toBe(1.1);+ expect(snapAppZoom(Number.NaN)).toBe(1);+ });+});++it("draws the chord as keycaps", () => {+ expect(appZoomCaps("ctrl+plus", "pc")).toEqual(["Ctrl", "+"]);+ expect(appZoomCaps("cmd+minus", "mac")).toEqual(["⌘", "-"]);+});diff --git a/jarvis/ui/web/frontend/src/lib/appZoom.ts b/jarvis/ui/web/frontend/src/lib/appZoom.tsnew file mode 100644index 0000000000..77726ed7db--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/appZoom.ts@@ -0,0 +1,225 @@+/**+ * Whole-app zoom: which keys zoom the window in, out and back to 100 %, and+ * which zoom level comes next.+ *+ * ## Why the keys are read as characters, not as key positions+ *+ * Every other in-app chord (the quick switcher, the voice keys) is matched by+ * physical key position, `event.code`. That cannot work for zoom: `+` sits on+ * its own key on a German keyboard (the one US calls `]`) but is Shift+`=` on+ * a US one, and `-` is US `/` on a German board. A chord saved as a position+ * would mean a different key on the next keyboard. So `+` and `-` are matched+ * by the CHARACTER the key types (`event.key`), with both spellings of each+ * step accepted the way browsers do:+ *+ * * zoom in: `+` (any layout), `=` on the key US calls Equal, keypad `+`;+ * * zoom out: `-` (any layout), `_` on the key US calls Minus, keypad `-`;+ * * Shift is ignored for `+` and `-`, because typing `+` needs Shift on many+ * layouts and not on others.+ *+ * Letters, digits and F-keys keep the position rule of the other in-app chords,+ * so a recorded Ctrl+Z means the same key it did when it was recorded.+ *+ * ## AltGr+ *+ * Windows reports AltGr as Ctrl+Alt. AltGr+`+` is `~` on a German keyboard, a+ * character people type all day; it counts as Alt here and so never matches a+ * plain Ctrl chord.+ *+ * Kept free of React and of the recorder modules: the app shell checks every+ * keystroke against it, so it ships in the startup chunk.+ */+import { hostChordPlatform, parseChord, type ChordPlatform } from "@/lib/quickSwitchChord";++export type AppZoomIntent = "in" | "out" | "reset";++export const APP_ZOOM_INTENTS: readonly AppZoomIntent[] = ["in", "out", "reset"];++export type AppZoomBindings = Record<AppZoomIntent, string>;++/** Chrome's own zoom ladder, so every step lands on a familiar number. */+export const APP_ZOOM_LEVELS: readonly number[] = [+ 0.5, 0.67, 0.75, 0.8, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3,+];++export function defaultAppZoomBindings(platform: ChordPlatform = hostChordPlatform()): AppZoomBindings {+ const mod = platform === "mac" ? "cmd" : "ctrl";+ return { in: `${mod}+plus`, out: `${mod}+minus`, reset: `${mod}+0` };+}++/** Snap any stored value onto the ladder, so a hand-edited level still steps cleanly. */+export function snapAppZoom(level: number): number {+ if (!Number.isFinite(level)) return 1;+ return APP_ZOOM_LEVELS.reduce((best, step) =>+ Math.abs(step - level) < Math.abs(best - level) ? step : best,+ );+}++export function nextAppZoom(level: number, intent: AppZoomIntent): number {+ if (intent === "reset") return 1;+ const index = APP_ZOOM_LEVELS.indexOf(snapAppZoom(level));+ const next = intent === "in" ? index + 1 : index - 1;+ return APP_ZOOM_LEVELS[Math.min(APP_ZOOM_LEVELS.length - 1, Math.max(0, next))];+}++/** Keys whose identity is the character they type, not their position. */+const CHARACTER_KEYS = new Set(["plus", "minus"]);++const NAMED_CODES: Record<string, string> = {+ Space: "space",+ ArrowUp: "up",+ ArrowDown: "down",+ ArrowLeft: "left",+ ArrowRight: "right",+ Insert: "insert",+ Delete: "delete",+ Home: "home",+ End: "end",+ PageUp: "page_up",+ PageDown: "page_down",+ Enter: "enter",+ NumpadEnter: "enter",+ Tab: "tab",+ Backspace: "backspace",+};++export interface AppZoomKeyEvent {+ key: string;+ code: string;+ ctrlKey: boolean;+ metaKey: boolean;+ altKey: boolean;+ shiftKey: boolean;+ getModifierState?(key: string): boolean;+}++/**+ * The token for the key this event pressed, or null for modifiers and keys a+ * zoom chord cannot use. Numpad digits count as the digit, so keypad 0 resets+ * whether NumLock is on or not.+ */+export function appZoomKeyToken(event: Pick<AppZoomKeyEvent, "key" | "code">): string | null {+ const { key, code } = event;+ if (code === "NumpadAdd") return "plus";+ if (code === "NumpadSubtract") return "minus";+ if (/^Numpad[0-9]$/.test(code)) return code.slice(6);+ if (code === "NumpadInsert") return "0"; // keypad 0 with NumLock off+ if (key === "+" || (key === "=" && code === "Equal")) return "plus";+ if (key === "-" || (key === "_" && code === "Minus")) return "minus";+ if (/^Key[A-Z]$/.test(code)) return code.slice(3).toLowerCase();+ if (/^Digit[0-9]$/.test(code)) return code.slice(5);+ if (/^F[0-9]{1,2}$/.test(code)) return code.toLowerCase();+ return NAMED_CODES[code] ?? null;+}++interface HeldModifiers {+ ctrl: boolean;+ alt: boolean;+ shift: boolean;+ meta: boolean;+}++function heldModifiers(event: AppZoomKeyEvent): HeldModifiers {+ const altGr = event.getModifierState?.("AltGraph") === true;+ return {+ ctrl: event.ctrlKey && !altGr,+ alt: event.altKey || altGr,+ shift: event.shiftKey,+ meta: event.metaKey,+ };+}++/** Does this keydown press exactly `combo`? Shift is free for `+` and `-`. */+export function appZoomChordMatches(event: AppZoomKeyEvent, combo: string): boolean {+ const { mods, keys } = parseChord(combo);+ if (keys.length !== 1) return false;+ const token = appZoomKeyToken(event);+ if (token === null || token !== keys[0]) return false;+ const held = heldModifiers(event);+ return (Object.keys(held) as (keyof HeldModifiers)[]).every((m) => {+ if (m === "shift" && CHARACTER_KEYS.has(token)) return true;+ return held[m] === mods.has(m);+ });+}++/** Which zoom step this keydown asks for, or null when it is none of them. */+export function appZoomIntentFor(event: AppZoomKeyEvent, bindings: AppZoomBindings): AppZoomIntent | null {+ for (const intent of APP_ZOOM_INTENTS) {+ const combo = bindings[intent];+ if (combo && appZoomChordMatches(event, combo)) return intent;+ }+ return null;+}++/**+ * The combo a recorder should store for this keydown, or null while only+ * modifiers are held. Shift is dropped for `+` and `-` (see above).+ */+export function appZoomComboFromEvent(+ event: AppZoomKeyEvent,+ platform: ChordPlatform = hostChordPlatform(),+): string | null {+ const token = appZoomKeyToken(event);+ if (token === null) return null;+ const held = heldModifiers(event);+ const mods: string[] = [];+ if (held.ctrl) mods.push("ctrl");+ if (held.alt) mods.push("alt");+ if (held.shift && !CHARACTER_KEYS.has(token)) mods.push("shift");+ if (held.meta) mods.push(platform === "mac" ? "cmd" : "win");+ return [...mods, token].join("+");+}++/** Why a recorded chord cannot zoom; null when it can. */+export type AppZoomComboProblem =+ /** No Ctrl, Alt or ⌘ (and not an F-key): it would fire while typing. */+ | "typing_key"+ /** The Windows key belongs to the desktop shell (Win+`+` is the magnifier). */+ | "os_reserved"+ /** Another zoom step already uses exactly this chord. */+ | "duplicate";++function foldedChord(combo: string): string {+ const { mods, keys } = parseChord(combo);+ return [...[...mods].sort(), ...keys].join("+");+}++export function appZoomComboProblem(+ combo: string,+ others: readonly string[],+ platform: ChordPlatform = hostChordPlatform(),+): AppZoomComboProblem | null {+ const { mods, keys } = parseChord(combo);+ const key = keys[0] ?? "";+ if (platform === "pc" && mods.has("meta")) return "os_reserved";+ const realModifier = mods.has("ctrl") || mods.has("alt") || mods.has("meta");+ if (!realModifier && !/^f[0-9]{1,2}$/.test(key)) return "typing_key";+ const mine = foldedChord(combo);+ if (others.some((other) => other && foldedChord(other) === mine)) return "duplicate";+ return null;+}++const KEY_LABEL: Record<string, string> = {+ plus: "+",+ minus: "-",+ space: "Space",+ up: "↑",+ down: "↓",+ left: "←",+ right: "→",+ page_up: "PgUp",+ page_down: "PgDn",+};++const MAC_GLYPH: Record<string, string> = { ctrl: "⌃", alt: "⌥", shift: "⇧", meta: "⌘" };+const PC_NAME: Record<string, string> = { ctrl: "Ctrl", alt: "Alt", shift: "Shift", meta: "Win" };+const MOD_ORDER = ["ctrl", "alt", "shift", "meta"] as const;++/** The chord as keycap labels ("Ctrl", "+"; "⌘", "-" on a Mac). */+export function appZoomCaps(combo: string, platform: ChordPlatform = hostChordPlatform()): string[] {+ const { mods, keys } = parseChord(combo);+ const names = platform === "mac" ? MAC_GLYPH : PC_NAME;+ const label = (token: string) =>+ KEY_LABEL[token] ?? (token.length === 1 ? token.toUpperCase() : token[0].toUpperCase() + token.slice(1));+ return [...MOD_ORDER.filter((m) => mods.has(m)).map((m) => names[m]), ...keys.map(label)];+}diff --git a/jarvis/ui/web/frontend/src/lib/shortcutRegistry.ts b/jarvis/ui/web/frontend/src/lib/shortcutRegistry.tsindex 65bc5ad717..b3a4a70a86 100644--- a/jarvis/ui/web/frontend/src/lib/shortcutRegistry.ts+++ b/jarvis/ui/web/frontend/src/lib/shortcutRegistry.ts@@ -58,12 +58,13 @@ export interface FixedShortcut extends ShortcutBase {/*** An in-app shortcut whose chord is a per-device preference (the quick- * switcher). Like a rebindable entry it carries no keys — the overlay reads the- * live setting, including whether the shortcut is switched off.+ * switcher, the whole-app zoom). Like a rebindable entry it carries no keys —+ * the overlay reads the live setting, including whether the shortcut is+ * switched off.*/export interface AppSettingShortcut extends ShortcutBase {kind: "app";- setting: "quick_switch";+ setting: "quick_switch" | "app_zoom_in" | "app_zoom_out" | "app_zoom_reset";}export type Shortcut = RebindableShortcut | FixedShortcut | AppSettingShortcut;@@ -119,6 +120,24 @@ export const SHORTCUTS: readonly Shortcut[] = [setting: "quick_switch",labelKey: "shortcut_overlay.workspace.quick_switch",},+ {+ kind: "app",+ area: "workspace",+ setting: "app_zoom_in",+ labelKey: "shortcut_overlay.workspace.app_zoom_in",+ },+ {+ kind: "app",+ area: "workspace",+ setting: "app_zoom_out",+ labelKey: "shortcut_overlay.workspace.app_zoom_out",+ },+ {+ kind: "app",+ area: "workspace",+ setting: "app_zoom_reset",+ labelKey: "shortcut_overlay.workspace.app_zoom_reset",+ },] as const;/** Areas in the order the overlay renders them. */diff --git a/jarvis/ui/web/frontend/src/store/appZoomSettings.ts b/jarvis/ui/web/frontend/src/store/appZoomSettings.tsnew file mode 100644index 0000000000..6157e1f40a--- /dev/null+++ b/jarvis/ui/web/frontend/src/store/appZoomSettings.ts@@ -0,0 +1,92 @@+/**+ * Whole-app zoom: whether the keys are on, which chords they are, and the+ * current level.+ *+ * Stored in the browser's own storage, like the quick switcher: zoom lives+ * entirely inside the window and the backend never needs to know it. Every+ * window of the app shares one origin, so a level set in one window reaches+ * the others through the `storage` event — the same way a browser zooms every+ * tab of one site together.+ *+ * An unreadable value falls back to "on, platform default chords, 100 %".+ */+import { create } from "zustand";+import {+ APP_ZOOM_INTENTS,+ defaultAppZoomBindings,+ snapAppZoom,+ type AppZoomBindings,+ type AppZoomIntent,+} from "@/lib/appZoom";++export const APP_ZOOM_STORAGE_KEY = "jarvis.appZoom.v1";++interface StoredAppZoom {+ enabled: boolean;+ /** "" means deliberately unassigned (the row's clear button). */+ bindings: AppZoomBindings;+ level: number;+}++function defaults(): StoredAppZoom {+ return { enabled: true, bindings: defaultAppZoomBindings(), level: 1 };+}++export function readAppZoomSettings(): StoredAppZoom {+ try {+ const raw = window.localStorage.getItem(APP_ZOOM_STORAGE_KEY);+ if (!raw) return defaults();+ const parsed = JSON.parse(raw) as Partial<StoredAppZoom>;+ const fallback = defaultAppZoomBindings();+ const bindings = { ...fallback };+ for (const intent of APP_ZOOM_INTENTS) {+ const value = parsed.bindings?.[intent];+ if (typeof value === "string") bindings[intent] = value;+ }+ return {+ enabled: typeof parsed.enabled === "boolean" ? parsed.enabled : true,+ bindings,+ level: typeof parsed.level === "number" ? snapAppZoom(parsed.level) : 1,+ };+ } catch {+ return defaults();+ }+}++function write(value: StoredAppZoom): void {+ try {+ window.localStorage.setItem(APP_ZOOM_STORAGE_KEY, JSON.stringify(value));+ } catch {+ /* storage unavailable — the choice holds for this session only */+ }+}++interface AppZoomSettingsState extends StoredAppZoom {+ setEnabled: (enabled: boolean) => void;+ setBinding: (intent: AppZoomIntent, combo: string) => void;+ setLevel: (level: number) => void;+}++export const useAppZoomSettings = create<AppZoomSettingsState>((set, get) => {+ const persist = (patch: Partial<StoredAppZoom>) => {+ const { enabled, bindings, level } = { ...get(), ...patch };+ write({ enabled, bindings, level });+ set(patch);+ };+ return {+ ...readAppZoomSettings(),+ setEnabled: (enabled) => persist({ enabled }),+ setBinding: (intent, combo) =>+ persist({ bindings: { ...get().bindings, [intent]: combo.trim().toLowerCase() } }),+ setLevel: (level) => persist({ level: snapAppZoom(level) }),+ };+});++// Another window changed it: take the new value over.+if (typeof window !== "undefined") {+ window.addEventListener("storage", (event) => {+ if (event.key === APP_ZOOM_STORAGE_KEY) {+ useAppZoomSettings.setState(readAppZoomSettings());+ }+ });+}diff --git a/jarvis/ui/web/frontend/src/views/ShortcutsView.tsx b/jarvis/ui/web/frontend/src/views/ShortcutsView.tsxindex e4622189a5..9bcab66725 100644--- a/jarvis/ui/web/frontend/src/views/ShortcutsView.tsx+++ b/jarvis/ui/web/frontend/src/views/ShortcutsView.tsx@@ -31,6 +31,9 @@ import { detectKeyboardPlatform } from "@/views/settings/keyboardLayout";import { ACTION_LABEL_KEY, ComboChips, formatCombo } from "@/views/settings/KeybindRow";import { KeybindsPanel } from "@/views/settings/KeybindsPanel";import { QuickSwitchKeybind } from "@/views/settings/QuickSwitchKeybind";+import { AppZoomKeybinds } from "@/views/settings/AppZoomKeybinds";+import { appZoomIntentFor } from "@/lib/appZoom";+import { useAppZoomSettings } from "@/store/appZoomSettings";import { eventMatchesChord } from "@/lib/quickSwitchChord";import { isTextEntryTarget } from "@/lib/shortcutOverlayTrigger";import { keyLabel, shortcutsForArea, type FixedShortcut } from "@/lib/shortcutRegistry";@@ -39,6 +42,12 @@ import { cn } from "@/lib/utils";const DICTATION_ACTIONS: readonly KeybindAction[] = ["dictate", "dictate_toggle", "paste_last"];+const APP_ZOOM_LABEL = {+ in: "settings_view.app_zoom.in_label",+ out: "settings_view.app_zoom.out_label",+ reset: "settings_view.app_zoom.reset_label",+} as const;+const ZOOM_LABEL = {in: "shortcut_overlay.workspace.zoom_in",out: "shortcut_overlay.workspace.zoom_out",@@ -95,6 +104,7 @@ function KeyTester({ config }: { config: KeybindsConfig | null }) {const t = useT();const isMac = detectKeyboardPlatform() === "mac";const quickSwitch = useQuickSwitchSettings();+ const appZoom = useAppZoomSettings();const [pressed, setPressed] = useState<Pressed | null>(null);useEffect(() => {@@ -122,8 +132,11 @@ function KeyTester({ config }: { config: KeybindsConfig | null }) {let meaningKey: string | null = "";const zoom = zoomIntentFor(event, { isMac });+ const appZoomIntent = appZoom.enabled ? appZoomIntentFor(event, appZoom.bindings) : null;if (quickSwitch.enabled && quickSwitch.combo && eventMatchesChord(event, quickSwitch.combo)) {meaningKey = "settings_view.quick_switch.title";+ } else if (appZoomIntent) {+ meaningKey = APP_ZOOM_LABEL[appZoomIntent];} else if (zoom) {meaningKey = ZOOM_LABEL[zoom];} else if (event.key === "?" && !event.ctrlKey && !event.metaKey && !event.altKey) {@@ -142,7 +155,7 @@ function KeyTester({ config }: { config: KeybindsConfig | null }) {};window.addEventListener("keydown", onKeyDown);return () => window.removeEventListener("keydown", onKeyDown);- }, [config, quickSwitch.enabled, quickSwitch.combo, isMac]);+ }, [config, quickSwitch.enabled, quickSwitch.combo, appZoom.enabled, appZoom.bindings, isMac]);const ghost = quickSwitch.combo ? formatCombo(quickSwitch.combo).split(" + ") : ["Ctrl", "Space"];@@ -309,6 +322,7 @@ export function ShortcutsView() {hint={t("shortcuts_view.section_app_hint")}><QuickSwitchKeybind voiceConfig={config} />+ <AppZoomKeybinds /></SectionCard><SectionCardtestId="shortcuts-section-calls"diff --git a/jarvis/ui/web/frontend/src/views/settings/AppZoomKeybinds.test.tsx b/jarvis/ui/web/frontend/src/views/settings/AppZoomKeybinds.test.tsxnew file mode 100644index 0000000000..fab9d1a05e--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/settings/AppZoomKeybinds.test.tsx@@ -0,0 +1,92 @@+/**+ * Settings → Keyboard shortcuts: the zoom chords are recorded by character, so+ * Plus and Minus can be set on any keyboard layout.+ */+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";++import { AppZoomKeybinds } from "./AppZoomKeybinds";+import { useAppZoomSupport } from "@/hooks/useAppZoom";+import { defaultAppZoomBindings } from "@/lib/appZoom";+import {+ APP_ZOOM_STORAGE_KEY,+ readAppZoomSettings,+ useAppZoomSettings,+} from "@/store/appZoomSettings";+import {+ QUICK_SWITCH_STORAGE_KEY,+ readQuickSwitchSettings,+ useQuickSwitchSettings,+} from "@/store/quickSwitchSettings";++describe("AppZoomKeybinds", () => {+ beforeEach(() => {+ window.localStorage.removeItem(APP_ZOOM_STORAGE_KEY);+ window.localStorage.removeItem(QUICK_SWITCH_STORAGE_KEY);+ useAppZoomSettings.setState(readAppZoomSettings());+ useQuickSwitchSettings.setState(readQuickSwitchSettings());+ useAppZoomSupport.setState({ support: "native" });+ });+ afterEach(cleanup);++ it("records a new zoom-in chord and remembers it", () => {+ render(<AppZoomKeybinds />);+ fireEvent.click(screen.getByTestId("app-zoom-record-in"));+ expect(screen.getByTestId("app-zoom-row-in").getAttribute("data-keybind-recording")).toBe("true");++ fireEvent.keyDown(window, { key: "ArrowUp", code: "ArrowUp", altKey: true });+ expect(useAppZoomSettings.getState().bindings.in).toBe("alt+up");+ expect(readAppZoomSettings().bindings.in).toBe("alt+up");+ expect(screen.getByTestId("app-zoom-row-in").hasAttribute("data-keybind-recording")).toBe(false);+ });++ it("records Plus on a German keyboard without the layout's key position", () => {+ useAppZoomSettings.getState().setBinding("in", "f9");+ render(<AppZoomKeybinds />);+ fireEvent.click(screen.getByTestId("app-zoom-record-in"));+ fireEvent.keyDown(window, { key: "+", code: "BracketRight", ctrlKey: true });+ expect(useAppZoomSettings.getState().bindings.in).toBe("ctrl+plus");+ });++ it("refuses a chord another step uses, and keeps the old one", () => {+ render(<AppZoomKeybinds />);+ const before = useAppZoomSettings.getState().bindings.in;+ fireEvent.click(screen.getByTestId("app-zoom-record-in"));+ fireEvent.keyDown(window, { key: "-", code: "Minus", ctrlKey: true });+ expect(useAppZoomSettings.getState().bindings.in).toBe(before);+ expect(screen.getByRole("alert").textContent).toMatch(/zoom step/i);+ });++ it("refuses the quick switcher's chord", () => {+ render(<AppZoomKeybinds />);+ fireEvent.click(screen.getByTestId("app-zoom-record-reset"));+ fireEvent.keyDown(window, { key: " ", code: "Space", ctrlKey: true });+ expect(screen.getByRole("alert").textContent).toMatch(/quick switcher/i);+ });++ it("cancels on Escape and resets to the default", () => {+ useAppZoomSettings.getState().setBinding("out", "alt+down");+ render(<AppZoomKeybinds />);+ fireEvent.click(screen.getByTestId("app-zoom-record-out"));+ fireEvent.keyDown(window, { key: "Escape", code: "Escape" });+ expect(useAppZoomSettings.getState().bindings.out).toBe("alt+down");++ fireEvent.click(screen.getByText("Reset to default"));+ expect(useAppZoomSettings.getState().bindings.out).toBe(defaultAppZoomBindings().out);+ });++ it("steps the size with its buttons and resets on the percentage", () => {+ render(<AppZoomKeybinds />);+ fireEvent.click(screen.getByTestId("app-zoom-step-in"));+ expect(screen.getByTestId("app-zoom-level").textContent).toBe("110 %");+ fireEvent.click(screen.getByTestId("app-zoom-level"));+ expect(useAppZoomSettings.getState().level).toBe(1);+ });++ it("explains that a browser tab keeps its own zoom", () => {+ useAppZoomSupport.setState({ support: "browser" });+ render(<AppZoomKeybinds />);+ expect(screen.queryByTestId("app-zoom-level")).toBeNull();+ expect(screen.getByTestId("app-zoom-note").textContent).toMatch(/browser/i);+ });+});diff --git a/jarvis/ui/web/frontend/src/views/settings/AppZoomKeybinds.tsx b/jarvis/ui/web/frontend/src/views/settings/AppZoomKeybinds.tsxnew file mode 100644index 0000000000..49a495ffe4--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/settings/AppZoomKeybinds.tsx@@ -0,0 +1,257 @@+/**+ * The Keyboard shortcuts page's zoom block: on/off, the current size, and the+ * three chords (bigger, smaller, back to 100 %).+ *+ * It has its own small recorder instead of the shared voice-key recorder, and+ * that is deliberate: the shared one records physical key positions and knows+ * no punctuation, because a global OS hotkey cannot use it. Zoom needs `+` and+ * `-`, which sit on different keys on a German and a US keyboard, so this+ * recorder reads the character the key types (see lib/appZoom).+ *+ * The value goes into the browser's storage (store/appZoomSettings), like the+ * quick switcher's chord: zoom is an in-window shortcut, not a global hotkey.+ */+import { Fragment, useEffect, useState } from "react";+import { Minus, Pencil, Plus, X } from "lucide-react";++import { Button } from "@/components/ui/button";+import { Switch } from "@/components/ui/switch";+import { useAppZoomSupport } from "@/hooks/useAppZoom";+import { useT } from "@/i18n";+import {+ APP_ZOOM_INTENTS,+ appZoomCaps,+ appZoomComboFromEvent,+ appZoomComboProblem,+ defaultAppZoomBindings,+ nextAppZoom,+ type AppZoomComboProblem,+ type AppZoomIntent,+} from "@/lib/appZoom";+import { useAppZoomSettings } from "@/store/appZoomSettings";+import { useQuickSwitchSettings } from "@/store/quickSwitchSettings";+import { parseChord } from "@/lib/quickSwitchChord";++const LABEL_KEY: Record<AppZoomIntent, string> = {+ in: "settings_view.app_zoom.in_label",+ out: "settings_view.app_zoom.out_label",+ reset: "settings_view.app_zoom.reset_label",+};++const PROBLEM_KEY: Record<AppZoomComboProblem | "quick_switch", string> = {+ typing_key: "settings_view.app_zoom.problem_typing_key",+ os_reserved: "settings_view.app_zoom.problem_os_reserved",+ duplicate: "settings_view.app_zoom.problem_duplicate",+ quick_switch: "settings_view.app_zoom.problem_quick_switch",+};++function sameChord(a: string, b: string): boolean {+ const fold = (combo: string) => {+ const { mods, keys } = parseChord(combo);+ return [...[...mods].sort(), ...keys].join("+");+ };+ return Boolean(a && b) && fold(a) === fold(b);+}++export function ZoomCaps({ combo }: { combo: string }) {+ return (+ <span className="inline-flex items-center gap-1">+ {appZoomCaps(combo).map((cap, i) => (+ <Fragment key={`${cap}-${i}`}>+ {i > 0 && <span className="text-muted-foreground/50">+</span>}+ <kbd className="rounded border border-border bg-muted px-1.5 py-0.5 font-mono text-micro text-foreground shadow-[inset_0_-1px_0_rgba(0,0,0,0.35)]">+ {cap}+ </kbd>+ </Fragment>+ ))}+ </span>+ );+}++function ZoomChordRow({ intent }: { intent: AppZoomIntent }) {+ const t = useT();+ const bindings = useAppZoomSettings((s) => s.bindings);+ const setBinding = useAppZoomSettings((s) => s.setBinding);+ const quickSwitch = useQuickSwitchSettings();+ const [recording, setRecording] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const combo = bindings[intent];+ const fallback = defaultAppZoomBindings()[intent];++ useEffect(() => {+ if (!recording) return;+ const onKeyDown = (event: KeyboardEvent) => {+ event.preventDefault();+ event.stopPropagation();+ if (event.key === "Escape") {+ setRecording(false);+ return;+ }+ const next = appZoomComboFromEvent(event);+ if (next === null) return; // only modifiers so far+ const others = APP_ZOOM_INTENTS.filter((other) => other !== intent).map((other) => bindings[other]);+ const problem = appZoomComboProblem(next, others);+ if (problem) {+ setError(t(PROBLEM_KEY[problem]));+ return;+ }+ if (quickSwitch.enabled && sameChord(next, quickSwitch.combo)) {+ setError(t(PROBLEM_KEY.quick_switch));+ return;+ }+ setError(null);+ setBinding(intent, next);+ setRecording(false);+ };+ // Capture on window: ahead of the zoom itself, the quick switcher and any+ // terminal pane, so the keys land here while recording.+ window.addEventListener("keydown", onKeyDown, true);+ return () => window.removeEventListener("keydown", onKeyDown, true);+ }, [recording, intent, bindings, quickSwitch.enabled, quickSwitch.combo, setBinding, t]);++ return (+ <div+ className="flex flex-col gap-1 py-2.5"+ data-testid={`app-zoom-row-${intent}`}+ data-keybind-recording={recording ? "true" : undefined}+ >+ <div className="flex items-center justify-between gap-3">+ <span className="min-w-0 text-sm text-foreground">{t(LABEL_KEY[intent])}</span>+ <div className="flex shrink-0 items-center gap-1.5">+ {recording ? (+ <span className="text-sm italic text-muted-foreground" aria-live="polite">+ {t("settings_view.keybinds.recording")}+ </span>+ ) : combo ? (+ <ZoomCaps combo={combo} />+ ) : (+ <span className="text-sm italic text-muted-foreground">{t("shortcut_overlay.unassigned")}</span>+ )}+ <Button+ type="button"+ size="icon"+ variant="ghost"+ className="h-8 w-8"+ data-testid={`app-zoom-record-${intent}`}+ aria-label={recording ? t("settings_view.keybinds.stop") : t("settings_view.keybinds.record")}+ title={recording ? t("settings_view.keybinds.stop") : t("settings_view.keybinds.record")}+ onClick={() => {+ setError(null);+ setRecording((r) => !r);+ }}+ >+ {recording ? <X /> : <Pencil />}+ </Button>+ <Button+ type="button"+ size="icon"+ variant="ghost"+ className="h-8 w-8"+ data-testid={`app-zoom-clear-${intent}`}+ aria-label={t("settings_view.keybinds.clear")}+ title={t("settings_view.keybinds.clear")}+ disabled={!combo || recording}+ onClick={() => setBinding(intent, "")}+ >+ <X />+ </Button>+ </div>+ </div>+ {error && (+ <p className="text-sm text-destructive" role="alert">+ {error}+ </p>+ )}+ {!recording && combo !== fallback && (+ <button+ type="button"+ className="self-end text-micro text-muted-foreground underline hover:text-foreground"+ onClick={() => {+ setError(null);+ setBinding(intent, fallback);+ }}+ >+ {t("settings_view.keybinds.reset")}+ </button>+ )}+ </div>+ );+}++export function AppZoomKeybinds() {+ const t = useT();+ const enabled = useAppZoomSettings((s) => s.enabled);+ const level = useAppZoomSettings((s) => s.level);+ const setEnabled = useAppZoomSettings((s) => s.setEnabled);+ const setLevel = useAppZoomSettings((s) => s.setLevel);+ const support = useAppZoomSupport((s) => s.support);+ const label = t("settings_view.app_zoom.title");+ const percent = `${Math.round(level * 100)} %`;+ const stepper = support !== "browser" && support !== "unsupported";++ return (+ <div className="mt-4 space-y-stack border-t border-border pt-4" data-testid="app-zoom-settings">+ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ <p className="text-base font-medium text-foreground">{label}</p>+ <p className="mt-0.5 text-sm text-muted-foreground">{t("settings_view.app_zoom.description")}</p>+ </div>+ <Switch checked={enabled} onCheckedChange={setEnabled} aria-label={label} data-testid="app-zoom-enabled" />+ </div>+ {stepper && (+ <div className="flex items-center justify-between gap-3">+ <span className="text-sm text-foreground">{t("settings_view.app_zoom.level_label")}</span>+ <div className="flex items-center gap-1">+ <Button+ type="button"+ size="icon"+ variant="outline"+ className="h-8 w-8"+ aria-label={t("settings_view.app_zoom.out_label")}+ data-testid="app-zoom-step-out"+ disabled={level <= nextAppZoom(level, "out")}+ onClick={() => setLevel(nextAppZoom(level, "out"))}+ >+ <Minus />+ </Button>+ <button+ type="button"+ className="min-w-16 rounded-md px-2 py-1 text-center font-mono text-sm tabular-nums text-foreground hover:bg-secondary"+ title={t("settings_view.app_zoom.reset_label")}+ data-testid="app-zoom-level"+ onClick={() => setLevel(1)}+ >+ {percent}+ </button>+ <Button+ type="button"+ size="icon"+ variant="outline"+ className="h-8 w-8"+ aria-label={t("settings_view.app_zoom.in_label")}+ data-testid="app-zoom-step-in"+ disabled={level >= nextAppZoom(level, "in")}+ onClick={() => setLevel(nextAppZoom(level, "in"))}+ >+ <Plus />+ </Button>+ </div>+ </div>+ )}+ {enabled && (+ <div className="divide-y divide-border">+ {APP_ZOOM_INTENTS.map((intent) => (+ <ZoomChordRow key={intent} intent={intent} />+ ))}+ </div>+ )}+ <p className="text-sm text-muted-foreground" data-testid="app-zoom-note">+ {support === "browser"+ ? t("settings_view.app_zoom.note_browser")+ : support === "unsupported"+ ? t("settings_view.app_zoom.note_unsupported")+ : t("settings_view.app_zoom.note_terminal")}+ </p>+ </div>+ );+}diff --git a/jarvis/ui/window_zoom.py b/jarvis/ui/window_zoom.pynew file mode 100644index 0000000000..3616340420--- /dev/null+++ b/jarvis/ui/window_zoom.py@@ -0,0 +1,124 @@+"""Zoom a desktop window's whole page, the way Ctrl + `+` zooms a browser.++The page asks for a zoom factor; this module hands it to the WebView engine+that draws the window. That is real page zoom, not a CSS trick: the engine+shrinks the CSS viewport, so `100vh` layouts, popovers and pointer coordinates+all stay correct at every level.++pywebview does not expose zoom, so each engine is reached through the native+view pywebview keeps per window (``BrowserView.instances[uid]``). Only the+platform module that is already running is looked at — nothing here imports a+GUI toolkit, so a headless server never pays for one:++* Windows (WebView2): ``ZoomFactor`` on the WinForms control, set on the UI+ thread through ``Form.Invoke``.+* macOS (WKWebView): ``setPageZoom:`` (macOS 11+), queued on the main thread.+* Linux (WebKitGTK): ``set_zoom_level``, queued on the GLib main loop.++Anything else (the Qt backend, a browser tab, a headless host) answers+``ok: false`` with a reason; the page then leaves zoom to the browser.+"""++from __future__ import annotations++import math+import sys+from typing import Any++from loguru import logger++ZOOM_MIN = 0.5+ZOOM_MAX = 3.0+++def clamp_zoom(factor: float) -> float:+ """Keep a requested factor inside the range every engine accepts."""+ if not math.isfinite(factor):+ return 1.0+ return round(min(ZOOM_MAX, max(ZOOM_MIN, factor)), 3)+++def _browser_view(module_name: str, window: Any) -> Any | None:+ """The native view pywebview keeps for ``window`` in a loaded platform module."""+ module = sys.modules.get(module_name)+ if module is None:+ return None+ view_cls = getattr(module, "BrowserView", None)+ instances = getattr(view_cls, "instances", None)+ if not isinstance(instances, dict):+ return None+ return instances.get(getattr(window, "uid", None))+++def _zoom_winforms(form: Any, factor: float) -> bool:+ webview = getattr(form, "webview", None)+ # The legacy MSHTML control has no ZoomFactor; only WebView2 does. Asked of+ # the CLASS: reading the property on the instance is a COM call, and off the+ # UI thread it fails with E_NOINTERFACE.+ if webview is None or not hasattr(type(webview), "ZoomFactor"):+ return False+ from System import ( # type: ignore[import-not-found] # pythonnet, loaded by pywebview+ Func,+ Type,+ )++ def _apply() -> None:+ webview.ZoomFactor = factor++ if getattr(form, "InvokeRequired", False):+ form.Invoke(Func[Type](_apply))+ else:+ _apply()+ return True+++def _zoom_cocoa(view: Any, factor: float) -> bool:+ webview = getattr(view, "webview", None)+ # pageZoom arrived with macOS 11; older systems only have pinch magnify,+ # which does not reflow the page and so is not offered.+ if webview is None or not webview.respondsToSelector_("setPageZoom:"):+ return False+ from PyObjCTools import AppHelper # type: ignore[import-not-found]++ AppHelper.callAfter(webview.setPageZoom_, factor)+ return True+++def _zoom_gtk(view: Any, factor: float) -> bool:+ webview = getattr(view, "webview", None)+ if webview is None or not hasattr(webview, "set_zoom_level"):+ return False+ from gi.repository import GLib # type: ignore[import-not-found]++ def _apply() -> bool:+ webview.set_zoom_level(factor)+ return False # run once++ GLib.idle_add(_apply)+ return True+++_ENGINES = (+ ("webview.platforms.winforms", _zoom_winforms),+ ("webview.platforms.cocoa", _zoom_cocoa),+ ("webview.platforms.gtk", _zoom_gtk),+)+++def set_window_zoom(window: Any, factor: float) -> dict[str, Any]:+ """Zoom ``window``'s page to ``factor`` (1.0 = 100 %). Worker-thread safe."""+ if window is None:+ return {"ok": False, "reason": "no_window"}+ zoom = clamp_zoom(factor)+ for module_name, apply in _ENGINES:+ view = _browser_view(module_name, window)+ if view is None:+ continue+ try:+ if apply(view, zoom):+ return {"ok": True, "zoom": zoom}+ except Exception: # noqa: BLE001 — reported to the page, which falls back+ logger.exception("Window zoom failed on {}", module_name)+ return {"ok": False, "reason": "zoom_failed"}+ return {"ok": False, "reason": "zoom_unsupported"}+ return {"ok": False, "reason": "zoom_unsupported"}diff --git a/tests/unit/ui/test_window_zoom.py b/tests/unit/ui/test_window_zoom.pynew file mode 100644index 0000000000..76edc110a1--- /dev/null+++ b/tests/unit/ui/test_window_zoom.py@@ -0,0 +1,193 @@+"""Whole-window zoom reaches the WebView engine of the window that asked."""++import sys+import types+from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.ui.web.desktop_routes import router+from jarvis.ui.window_zoom import ZOOM_MAX, ZOOM_MIN, clamp_zoom, set_window_zoom+++class GtkWebView:+ def __init__(self) -> None:+ self.levels: list[float] = []++ def set_zoom_level(self, level: float) -> None:+ self.levels.append(level)+++class CocoaWebView:+ def __init__(self, page_zoom: bool = True) -> None:+ self.page_zoom = page_zoom+ self.zooms: list[float] = []++ def respondsToSelector_(self, selector: str) -> bool: # noqa: N802 — Objective-C name+ return self.page_zoom and selector == "setPageZoom:"++ def setPageZoom_(self, factor: float) -> None: # noqa: N802 — Objective-C name+ self.zooms.append(factor)+++def _install(monkeypatch: pytest.MonkeyPatch, name: str, module: types.ModuleType) -> None:+ monkeypatch.setitem(sys.modules, name, module)+++def _platform(monkeypatch: pytest.MonkeyPatch, name: str, uid: str, view: object) -> None:+ module = types.ModuleType(name)+ module.BrowserView = type("BrowserView", (), {"instances": {uid: view}})+ _install(monkeypatch, name, module)++[email protected](autouse=True)+def _no_real_engines(monkeypatch: pytest.MonkeyPatch) -> None:+ for name in ("webview.platforms.winforms", "webview.platforms.cocoa", "webview.platforms.gtk"):+ monkeypatch.delitem(sys.modules, name, raising=False)+++def test_clamp_keeps_factors_in_range():+ assert clamp_zoom(1.1) == 1.1+ assert clamp_zoom(0.01) == ZOOM_MIN+ assert clamp_zoom(99) == ZOOM_MAX+ assert clamp_zoom(float("nan")) == 1.0+++def test_no_window_and_no_engine():+ assert set_window_zoom(None, 1.2)["reason"] == "no_window"+ assert set_window_zoom(SimpleNamespace(uid="main"), 1.2)["reason"] == "zoom_unsupported"+++def test_gtk_zoom_is_queued_on_the_main_loop(monkeypatch: pytest.MonkeyPatch):+ queued: list = []+ gi = types.ModuleType("gi")+ repository = types.ModuleType("gi.repository")+ repository.GLib = SimpleNamespace(idle_add=queued.append)+ gi.repository = repository+ _install(monkeypatch, "gi", gi)+ _install(monkeypatch, "gi.repository", repository)+ webview = GtkWebView()+ _platform(monkeypatch, "webview.platforms.gtk", "main", SimpleNamespace(webview=webview))++ assert set_window_zoom(SimpleNamespace(uid="main"), 1.25) == {"ok": True, "zoom": 1.25}+ assert webview.levels == [] # not on the caller's thread+ assert queued[0]() is False # runs once+ assert webview.levels == [1.25]+++def test_cocoa_zoom_needs_page_zoom(monkeypatch: pytest.MonkeyPatch):+ called: list = []+ helper = types.ModuleType("PyObjCTools")+ helper.AppHelper = SimpleNamespace(callAfter=lambda fn, arg: called.append((fn, arg)))+ _install(monkeypatch, "PyObjCTools", helper)+ webview = CocoaWebView()+ _platform(monkeypatch, "webview.platforms.cocoa", "main", SimpleNamespace(webview=webview))++ assert set_window_zoom(SimpleNamespace(uid="main"), 0.8)["ok"] is True+ fn, arg = called[0]+ fn(arg)+ assert webview.zooms == [0.8]++ old = CocoaWebView(page_zoom=False)+ _platform(monkeypatch, "webview.platforms.cocoa", "main", SimpleNamespace(webview=old))+ assert set_window_zoom(SimpleNamespace(uid="main"), 0.8)["reason"] == "zoom_unsupported"+++def test_only_the_asking_window_is_zoomed(monkeypatch: pytest.MonkeyPatch):+ gi = types.ModuleType("gi")+ repository = types.ModuleType("gi.repository")+ repository.GLib = SimpleNamespace(idle_add=lambda fn: fn())+ gi.repository = repository+ _install(monkeypatch, "gi", gi)+ _install(monkeypatch, "gi.repository", repository)+ webview = GtkWebView()+ _platform(monkeypatch, "webview.platforms.gtk", "main", SimpleNamespace(webview=webview))++ assert set_window_zoom(SimpleNamespace(uid="detached"), 2.0)["reason"] == "zoom_unsupported"+ assert webview.levels == []+++def test_engine_error_is_reported_not_raised(monkeypatch: pytest.MonkeyPatch):+ class Broken:+ def set_zoom_level(self, level: float) -> None:+ raise RuntimeError("engine gone")++ gi = types.ModuleType("gi")+ repository = types.ModuleType("gi.repository")+ repository.GLib = SimpleNamespace(idle_add=lambda fn: fn())+ gi.repository = repository+ _install(monkeypatch, "gi", gi)+ _install(monkeypatch, "gi.repository", repository)+ _platform(monkeypatch, "webview.platforms.gtk", "main", SimpleNamespace(webview=Broken()))++ assert set_window_zoom(SimpleNamespace(uid="main"), 1.5)["reason"] == "zoom_failed"+++def test_route_without_and_with_a_desktop_shell():+ app = FastAPI()+ app.include_router(router)+ client = TestClient(app)+ denied = client.post("/api/window/zoom", json={"factor": 1.1}).json()+ assert denied["reason"] == "no_desktop_shell"+ assert client.post("/api/window/zoom", json={"factor": 50}).status_code == 422++ seen: list = []++ def zoom(factor: float, view: str | None) -> dict:+ seen.append((factor, view))+ return {"ok": True, "zoom": factor}++ app.state.desktop_app = SimpleNamespace(set_window_zoom=zoom)+ body = client.post("/api/window/zoom", json={"factor": 1.25, "view": "agentic-ide"}).json()+ assert body == {"ok": True, "zoom": 1.25}+ assert seen == [(1.25, "agentic-ide")]+ operation = app.openapi()["paths"]["/api/window/zoom"]["post"]+ assert operation["operationId"] == "zoom"+++class WebView2:+ """Reading ZoomFactor off the UI thread is a COM error on the real control."""++ def __init__(self) -> None:+ self.on_ui_thread = False+ self._zoom = 1.0++ @property+ def ZoomFactor(self) -> float: # noqa: N802 — .NET name+ if not self.on_ui_thread:+ raise RuntimeError("E_NOINTERFACE")+ return self._zoom++ @ZoomFactor.setter+ def ZoomFactor(self, value: float) -> None: # noqa: N802 — .NET name+ if not self.on_ui_thread:+ raise RuntimeError("E_NOINTERFACE")+ self._zoom = value+++class Form:+ InvokeRequired = True++ def __init__(self, webview: WebView2) -> None:+ self.webview = webview++ def Invoke(self, delegate) -> None: # noqa: N802 — .NET name+ self.webview.on_ui_thread = True+ try:+ delegate()+ finally:+ self.webview.on_ui_thread = False+++def test_webview2_zoom_runs_on_the_ui_thread(monkeypatch: pytest.MonkeyPatch):+ system = types.ModuleType("System")+ system.Type = object+ system.Func = {object: lambda fn: fn}+ _install(monkeypatch, "System", system)+ webview = WebView2()+ _platform(monkeypatch, "webview.platforms.winforms", "main", Form(webview))++ assert set_window_zoom(SimpleNamespace(uid="main"), 1.5) == {"ok": True, "zoom": 1.5}+ assert webview._zoom == 1.5