diff --git a/CONTEXT.md b/CONTEXT.md index c0266ee..4dd730b 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -85,9 +85,13 @@ The single `http://:/` URL a phone types into its browser to re _Avoid_: connection URL, daemon URL **Health issue**: -Something the daemon knows is wrong on the host that makes input fail silently, today a missing OS permission (macOS Accessibility). Reported by the platform backend, pushed to every client as a `health` frame (full list on change; an empty list means healthy), shown as a banner above the grid, and listed under `/diag`'s `health` block. Not the same as `GET /health` (host identity) or `focus.healthy` (is context switching working). See issue #195. +Something the daemon knows is wrong on the host that makes input fail silently, today a missing OS permission (macOS Accessibility, or Automation of System Events). Reported by the platform backend (from proactive checks plus refusals seen at action time, #196), pushed to every client as a `health` frame (full list on change; an empty list means healthy), shown as a banner above the grid, and listed under `/diag`'s `health` block. Not the same as `GET /health` (host identity) or `focus.healthy` (is context switching working). See issue #195. An action the OS refuses for the same cause also gets an **Action error**. _Avoid_: warning, alert, permission error +**Action error**: +The daemon's reply to one session when the OS refused an action that session triggered, today a macOS key press blocked for want of Accessibility or Automation (`reason: "permission_denied"`). Sent as an `action_error` frame to the requesting session only, shown as a toast, recorded as `outcome="permission_denied"` in `/actions/recent` and `/metrics`. Its `issue_id` names the **Health issue** that carries the fix steps. See issue #196. +_Avoid_: permission error, failure toast + ### Session screen state (issue #160) **Screen locked**: diff --git a/README.md b/README.md index 438a522..33b225f 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ Pre-alpha, but usable day-to-day. Here's what deckd can do today and what's stil - [x] **Chrome media indicator** — the media icon sprouts a pulsing green dot whenever a media player is playing (passive playback indicator), independent of the browser view. - [x] **Now playing** — control any supported media player (Spotify, Firefox, VLC, etc.) from a dedicated chrome view, with album art, per-player transport controls, and now-playing metadata. - [x] **Session lock awareness** — when the desktop session locks, the phone swaps to a "Screen locked" takeover and the daemon refuses presses / injection / trackpad / window raising (`--allow-while-locked` opts out); a plain screen blank keeps input live so a press wakes the machine. -- [x] **Missing-permission warnings** — when an OS permission deckd needs is missing (today: macOS Accessibility), the phone shows a banner naming what won't work and how to fix it, and clears it by itself once you grant the permission. +- [x] **Missing-permission warnings** — when an OS permission deckd needs is missing (today: macOS Accessibility and Automation → System Events), the phone shows a banner naming what won't work and how to fix it, and clears it by itself once you grant the permission. A key press the OS refuses toasts straight away. - [x] **Running programs list** — tap a deck-grid icon in the bottom chrome to open a list of every open window on the host, labeled by the deck the window would match. Tap a row to raise (focus) that window and close the list. Enumeration and raise are GNOME-only today (via the focus extension); other backends show the list's "unsupported on this platform" empty state. - [x] **VLC media widgets** — full VLC control surface with play/pause, seek, volume, album art. Configurable art sources (VLC embedded art + iTunes fallback). - [x] **Live sensor widgets** — meter and stats widgets pushed to the client in real time (CPU %, memory %, swap %, root disk %), bound to daemon-side sensor sources. diff --git a/client/src/ActionErrorToast.test.tsx b/client/src/ActionErrorToast.test.tsx new file mode 100644 index 0000000..e47bac1 --- /dev/null +++ b/client/src/ActionErrorToast.test.tsx @@ -0,0 +1,30 @@ +/** Toast for an action the OS refused (issue #196). + * + * The daemon answers a key press macOS blocked (missing Accessibility or + * Automation) with an ``action_error`` frame; the toast shows its message + * right away. The banner carries the fix steps, so the toast only says what + * happened and can be dismissed. + */ +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { ActionErrorToast } from "./ActionErrorToast"; + +afterEach(cleanup); + +const MESSAGE = "Key press blocked: deckd.app needs Accessibility permission."; + +describe("ActionErrorToast", () => { + it("shows the daemon's message in a polite live region", () => { + const { container } = render( {}} />); + expect(screen.getByText(MESSAGE)).toBeTruthy(); + expect(container.querySelector('[aria-live="polite"]')).not.toBeNull(); + }); + + it("offers Dismiss, and no Retry: a retry would be refused the same way", () => { + const onDismiss = vi.fn(); + render(); + expect(screen.queryByRole("button", { name: "Retry" })).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "Dismiss" })); + expect(onDismiss).toHaveBeenCalledOnce(); + }); +}); diff --git a/client/src/ActionErrorToast.tsx b/client/src/ActionErrorToast.tsx new file mode 100644 index 0000000..e316f26 --- /dev/null +++ b/client/src/ActionErrorToast.tsx @@ -0,0 +1,26 @@ +/** Non-blocking toast for an action the OS refused (issue #196). + * + * The daemon answers a key press macOS blocked for want of a permission + * with an ``action_error`` frame; this shows its message straight away. + * The health banner, raised at the same time, carries the fix steps, so the + * toast only says what happened. No Retry: the OS would refuse it the same + * way until the grant lands. Shares the media toast's look and placement. + */ +export function ActionErrorToast({ + message, + onDismiss, +}: { + message: string; + onDismiss: () => void; +}) { + return ( +
+ {message} + + + +
+ ); +} diff --git a/client/src/App.test.tsx b/client/src/App.test.tsx index 2ebf1a2..0ea6132 100644 --- a/client/src/App.test.tsx +++ b/client/src/App.test.tsx @@ -16,7 +16,7 @@ */ import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { ClientMessage, ServerChromeMedia, ServerDeck, ServerMediaError, ServerState } from "./protocol"; +import type { ClientMessage, ServerChromeMedia, ServerDeck, ServerMediaError, ServerActionError, ServerState } from "./protocol"; /** Replace the real socket hook with a controllable fake. The chrome * icon's job is to call ``send`` with the right message; the test @@ -42,6 +42,7 @@ const cancelReconnect = vi.fn(); const retryNow = vi.fn(); let sessionStateHandler: ((m: ServerState) => void) | null = null; let mediaErrorHandler: ((m: ServerMediaError) => void) | null = null; +let actionErrorHandler: ((m: ServerActionError) => void) | null = null; vi.mock("./socket", () => ({ useDeckdSocket: ( deckCb: (m: ServerDeck) => void, @@ -52,12 +53,15 @@ vi.mock("./socket", () => ({ _runningWindowsCb: unknown, sessionStateCb: ((m: ServerState) => void) | undefined, mediaErrorCb: ((m: ServerMediaError) => void) | undefined, + _healthCb: unknown, + actionErrorCb: ((m: ServerActionError) => void) | undefined, _options: unknown, ) => { onDeck.mockImplementation(deckCb); chromeMediaHandler = chromeMediaCb ?? null; sessionStateHandler = sessionStateCb ?? null; mediaErrorHandler = mediaErrorCb ?? null; + actionErrorHandler = actionErrorCb ?? null; return { get status() { return mockStatus; @@ -1421,3 +1425,60 @@ describe("App — media error toast", () => { expect(send.mock.calls.length).toBe(before); }); }); + +/* ------------------------------------------------------------------------- + * Action refused by the OS (issue #196): a key press macOS blocked for want + * of a permission toasts at once; a media failure after it takes its place. + * --------------------------------------------------------------------- */ + +describe("App — action error toast", () => { + afterEach(cleanup); + beforeEach(() => { + send.mockReset(); + actionErrorHandler = null; + mediaErrorHandler = null; + mockStatus = "open"; + window.history.replaceState(null, "", "/?demo=mpris"); + }); + + const blocked: ServerActionError = { + type: "action_error", + id: "new-window", + reason: "permission_denied", + issue_id: "automation_system_events_missing", + message: "Key press blocked: deckd.app needs Automation permission to control System Events.", + }; + + it("shows the message and announces it", () => { + render(); + act(() => actionErrorHandler?.(blocked)); + expect(screen.getAllByText(blocked.message).length).toBeGreaterThan(0); + expect(screen.getByRole("status").textContent).toBe(blocked.message); + }); + + it("dismisses", () => { + render(); + act(() => actionErrorHandler?.(blocked)); + fireEvent.click(screen.getByRole("button", { name: "Dismiss" })); + expect(document.querySelector(".media-error-toast")).toBeNull(); + }); + + it("the newer failure replaces the older toast", () => { + render(); + act(() => actionErrorHandler?.(blocked)); + act(() => + mediaErrorHandler?.({ + type: "media_error", + id: "mpris.vlc", + player: "VLC media player", + message: "player disappeared", + retryable: true, + }), + ); + expect(document.querySelectorAll(".media-error-toast").length).toBe(1); + expect(screen.getByText(/player disappeared/)).toBeTruthy(); + act(() => actionErrorHandler?.(blocked)); + expect(document.querySelectorAll(".media-error-toast").length).toBe(1); + expect(screen.queryByText(/player disappeared/)).toBeNull(); + }); +}); diff --git a/client/src/App.tsx b/client/src/App.tsx index 94f578e..f58220b 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -42,6 +42,7 @@ import type { HealthIssue, ServerHealth, ServerMediaError, + ServerActionError, ServerRunningWindows, ServerState, WindowListEntry, @@ -53,6 +54,7 @@ import { ReflowHelp } from "./ReflowHelp"; import { ConfirmModal } from "./ConfirmModal"; import { ConnectionOverlay } from "./ConnectionOverlay"; import { MediaErrorToast } from "./MediaErrorToast"; +import { ActionErrorToast } from "./ActionErrorToast"; import { HealthBanner } from "./HealthBanner"; import type { Widget, ConfirmRequestMessage, MediaCommandMessage } from "./protocol"; import { wireWindowsToServer } from "./protocol"; @@ -216,7 +218,18 @@ export function App() { const lastMediaCommandRef = useRef< Record >({}); - const onMediaError = useCallback((m: ServerMediaError) => setMediaError(m), []); + // Action refused by the OS (issue #196): a key press macOS blocked for + // want of Accessibility / Automation. Both toasts sit in the same spot, + // so the newer failure replaces the older one, whichever kind it is. + const [actionError, setActionError] = useState(null); + const onMediaError = useCallback((m: ServerMediaError) => { + setActionError(null); + setMediaError(m); + }, []); + const onActionError = useCallback((m: ServerActionError) => { + setMediaError(null); + setActionError(m); + }, []); // Daemon health issues (issue #195): missing OS permissions that make // input fail silently. The daemon pushes the full list on change, so // the latest frame is the whole truth; empty means healthy. @@ -272,6 +285,7 @@ export function App() { onSessionState, onMediaError, onHealth, + onActionError, { enabled: !demoDeck && !isPlayground }, ); const playgroundSocket = usePlaygroundDaemon( @@ -706,6 +720,11 @@ export function App() { // eslint-disable-next-line react-hooks/set-state-in-effect setLiveText(`Media error: ${mediaError.player || mediaError.id}`); }, [mediaError]); + useEffect(() => { + if (!actionError) return; + // eslint-disable-next-line react-hooks/set-state-in-effect + setLiveText(actionError.message); + }, [actionError]); // Chrome app-identity badge (ADR-0007): the daemon relays an // optional ``display_name`` / ``theme`` / ``icon`` per deck; the @@ -1190,6 +1209,14 @@ export function App() { onDismiss={() => setMediaError(null)} /> ) : null} + {/* Key press refused by the OS (issue #196). The health banner has + the fix steps; this says what just happened. */} + {actionError ? ( + setActionError(null)} + /> + ) : null} ); } diff --git a/client/src/HealthBanner.stories.tsx b/client/src/HealthBanner.stories.tsx index 888156d..0085534 100644 --- a/client/src/HealthBanner.stories.tsx +++ b/client/src/HealthBanner.stories.tsx @@ -40,3 +40,27 @@ export const Warning: Story = () => ( /> ); + +/** The macOS Automation issue (#196), worded like + * ``deckd.platform_macos._automation_missing_issue`` for the packaged app. */ +const AUTOMATION: HealthIssue = { + id: "automation_system_events_missing", + severity: "error", + title: "Automation permission missing", + detail: + "macOS isn't letting deckd.app control System Events, so key buttons do nothing and the deck may not follow the app in front.", + fix_steps: [ + "On the Mac, open System Settings → Privacy & Security → Automation.", + "Under deckd.app, turn on System Events.", + "If deckd.app isn't listed, or System Events is already on, run `tccutil reset AppleEvents com.deckd.daemon` in Terminal, then click OK when macOS asks to let it control System Events.", + "This warning clears by itself a few seconds after the grant.", + ], + affects: ["key", "focus"], +}; + +/** Both grants missing: one banner each, Accessibility first. */ +export const BothMissing: Story = () => ( +
+ {}} /> +
+); diff --git a/client/src/HealthBanner.test.tsx b/client/src/HealthBanner.test.tsx index 9a7f8b1..de80b88 100644 --- a/client/src/HealthBanner.test.tsx +++ b/client/src/HealthBanner.test.tsx @@ -57,6 +57,13 @@ describe("HealthBanner", () => { expect(screen.getAllByRole("listitem").length).toBe(2); }); + it("names the deck-following that a missing Automation grant breaks (issue #196)", () => { + render(); + const text = screen.getByRole("alert").textContent; + expect(text).toContain("key presses, switching decks with the app in front"); + expect(text).not.toContain("focus"); + }); + it("falls back to the raw key for an unknown primitive", () => { render(); expect(screen.getByRole("alert").textContent).toContain("teleport"); diff --git a/client/src/HealthBanner.tsx b/client/src/HealthBanner.tsx index df1b8d2..fd4a1a7 100644 --- a/client/src/HealthBanner.tsx +++ b/client/src/HealthBanner.tsx @@ -8,6 +8,7 @@ const AFFECTS_LABELS: Record = { scroll: "scrolling", key: "key presses", raise_window: "raising windows from the list", + focus: "switching decks with the app in front", }; function describeAffects(affects: string[]): string { diff --git a/client/src/protocol.generated.ts b/client/src/protocol.generated.ts index 6599f42..65ad1ef 100644 --- a/client/src/protocol.generated.ts +++ b/client/src/protocol.generated.ts @@ -261,6 +261,32 @@ export type MediaErrorMessage = { retryable?: boolean; }; +/** + * Daemon -> client push: an action this session triggered was refused + * by the OS (issue #196). + * + * Sent only to the *requesting* session, like ``media_error``: the + * failure is a consequence of one session's press. Today the one + * ``reason`` is ``permission_denied`` (macOS refused the keystroke for + * want of Accessibility or Automation); the client shows ``message`` + * as a toast. ``issue_id`` names the :class:`HealthIssue` with the fix + * steps, which the daemon raises at the same time. ``id`` is the + * pressed widget's id, ``None`` for manual-control keys and typed text. + * + */ +export type ActionErrorMessage = { + + type: "action_error"; + + id?: string | null; + + reason: "permission_denied"; + + issue_id: string; + + message: string; +}; + /** * Daemon -> client push: the chrome media icon's passive * playback-state snapshot (issue #47). @@ -465,13 +491,13 @@ export type RunningWindowsMessage = { * One thing the daemon knows is broken on this host (issue #195). * * Platform-neutral: a backend mints these from whatever it can probe - * (macOS Accessibility trust today; Automation, Linux ``uinput`` access - * are follow-ups). ``id`` is a stable machine key (``accessibility_missing``) - * the client can dedupe and dismiss by. ``fix_steps`` are complete, + * (macOS Accessibility trust and Automation of System Events today; + * Linux ``uinput`` access is a follow-up). ``id`` is a stable machine + * key (``accessibility_missing``) the client can dedupe and dismiss by. ``fix_steps`` are complete, * user-facing sentences that name the exact app to grant and the * Settings path. ``affects`` lists the input primitives that silently * fail while the issue stands (``pointer``, ``scroll``, ``key``, - * ``raise_window``, ...). + * ``raise_window``, ``focus``, ...). * */ export type HealthIssue = { @@ -509,7 +535,7 @@ export type HealthMessage = { issues: HealthIssue[]; }; -export type ServerMessage = DeckMessage | StateMessage | BrightnessMessage | WidgetUpdateMessage | MediaStateMessage | MediaErrorMessage | ChromeMediaMessage | EventMessage | MacroResultMessage | ConfirmRequestMessage | RunningWindowsMessage | HealthMessage | ErrorMessage; +export type ServerMessage = DeckMessage | StateMessage | BrightnessMessage | WidgetUpdateMessage | MediaStateMessage | MediaErrorMessage | ActionErrorMessage | ChromeMediaMessage | EventMessage | MacroResultMessage | ConfirmRequestMessage | RunningWindowsMessage | HealthMessage | ErrorMessage; export type HelloMessage = { diff --git a/client/src/protocol.ts b/client/src/protocol.ts index 8eaead5..b8f5f37 100644 --- a/client/src/protocol.ts +++ b/client/src/protocol.ts @@ -28,6 +28,7 @@ import type { ChromeMediaMessage, ErrorMessage, MediaErrorMessage, + ActionErrorMessage, MacroResultMessage, ConfirmRequestMessage, RunningWindowsMessage, @@ -61,6 +62,7 @@ export type { WidgetUpdateMessage, MediaStateMessage, MediaErrorMessage, + ActionErrorMessage, ChromeMediaMessage, EventMessage, MacroResultMessage, @@ -200,6 +202,7 @@ export type ServerWidgetUpdate = WidgetUpdateMessage; export type ServerChromeMedia = ChromeMediaMessage; export type ServerError = ErrorMessage; export type ServerMediaError = MediaErrorMessage; +export type ServerActionError = ActionErrorMessage; export type ServerMacroResult = MacroResultMessage; export type ServerConfirmRequest = ConfirmRequestMessage; export type ServerHealth = HealthMessage; diff --git a/client/src/socket.test.ts b/client/src/socket.test.ts index 424a7e5..bc139ee 100644 --- a/client/src/socket.test.ts +++ b/client/src/socket.test.ts @@ -119,6 +119,27 @@ describe("useDeckdSocket — reconnect feedback (issue #64)", () => { expect(onHealth).toHaveBeenCalledWith(frame); }); + it("routes an action_error frame to onActionError (issue #196)", async () => { + const onActionError = vi.fn(); + renderHook(() => + useDeckdSocket( + noop, noop, noop, undefined, undefined, undefined, undefined, undefined, undefined, onActionError, + ), + ); + await waitFor(() => expect(FakeWebSocket.instances.length).toBe(1)); + const ws = FakeWebSocket.instances[0]; + act(() => ws.open()); + const frame = { + type: "action_error", + id: "new-window", + reason: "permission_denied", + issue_id: "accessibility_missing", + message: "Key press blocked: deckd.app needs Accessibility permission.", + }; + act(() => ws.onmessage?.({ data: JSON.stringify(frame) })); + expect(onActionError).toHaveBeenCalledWith(frame); + }); + it("a new connection resets health to empty before the daemon's replay", async () => { // A healthy daemon sends no ``health`` frame on connect, so an issue // that cleared while we were disconnected (e.g. the user quit and diff --git a/client/src/socket.ts b/client/src/socket.ts index 7c58c33..9cc0a80 100644 --- a/client/src/socket.ts +++ b/client/src/socket.ts @@ -1,5 +1,5 @@ import { useCallback, useEffect, useRef, useState } from "react"; -import type { ClientMessage, ServerChromeMedia, ServerConfirmRequest, ServerDeck, ServerHealth, ServerMediaError, ServerMessage, ServerRunningWindows, ServerState, ServerWidgetUpdate, MediaState } from "./protocol"; +import type { ClientMessage, ServerActionError, ServerChromeMedia, ServerConfirmRequest, ServerDeck, ServerHealth, ServerMediaError, ServerMessage, ServerRunningWindows, ServerState, ServerWidgetUpdate, MediaState } from "./protocol"; import { wireDeckToServer, wireWindowsToServer } from "./protocol"; type Status = "connecting" | "open" | "closed" | "unauthorized"; @@ -61,6 +61,7 @@ export function useDeckdSocket( onSessionState?: (m: ServerState) => void, onMediaError?: (m: ServerMediaError) => void, onHealth?: (m: ServerHealth) => void, + onActionError?: (m: ServerActionError) => void, options: { enabled?: boolean } = {}, ) { const { enabled = true } = options; @@ -196,6 +197,11 @@ export function useDeckdSocket( else if (msg.type === "health" && onHealth) { onHealth(msg); } + // Issue #196: the OS refused an action this session triggered + // (a key press macOS blocked for want of a grant). Toast it. + else if (msg.type === "action_error" && onActionError) { + onActionError(msg); + } else if (msg.type === "error" && msg.reason === "unauthorized") { // Wrong/absent password: stop reconnecting and prompt the user. unauthorizedRef.current = true; @@ -265,7 +271,7 @@ export function useDeckdSocket( if (timer) window.clearTimeout(timer); wsRef.current?.close(); }; - }, [onDeck, onWidgetUpdate, onMediaState, onChromeMedia, onConfirmRequest, onRunningWindows, onSessionState, onMediaError, onHealth, enabled, gen]); + }, [onDeck, onWidgetUpdate, onMediaState, onChromeMedia, onConfirmRequest, onRunningWindows, onSessionState, onMediaError, onHealth, onActionError, enabled, gen]); const send = (msg: ClientMessage) => { const ws = wsRef.current; diff --git a/daemon/deckd/actions.py b/daemon/deckd/actions.py index 7b18d7f..965e57b 100644 --- a/daemon/deckd/actions.py +++ b/daemon/deckd/actions.py @@ -508,18 +508,38 @@ async def _text_paste(text: str, ctx: ActionContext, restore_clipboard: bool, log.warning("[text paste] failed to write clipboard: %s", exc) return + from .input import PermissionDenied + sink = ctx.key_sink if sink is not None: from .input import parse_key_combo ctrlv = parse_key_combo("ctrl+v") - sink.emit_key(ctrlv) + try: + sink.emit_key(ctrlv) + except PermissionDenied: + # Refused (#196): nothing was pasted, so put the user's clipboard + # back now (no delay needed) before the refusal reaches the toast. + await _restore_clipboard(previous, copy_tool, restore_clipboard, paste_tool, 0) + raise log.info("[text paste] pasted %d chars via ctrl+v", len(text)) else: log.info("[text paste log] text=%r (no sink wired)", text) + await _restore_clipboard(previous, copy_tool, restore_clipboard, paste_tool, restore_delay_ms) + + +async def _restore_clipboard( + previous: str | None, + copy_tool: str, + restore_clipboard: bool, + paste_tool: str | None, + delay_ms: int, +) -> None: + """Write ``previous`` back to the clipboard after ``delay_ms``, if asked to.""" if restore_clipboard and previous is not None and paste_tool is not None: - await asyncio.sleep(restore_delay_ms / 1000.0) + if delay_ms: + await asyncio.sleep(delay_ms / 1000.0) try: proc = await asyncio.create_subprocess_exec( *_clipboard_write_args(copy_tool), @@ -550,10 +570,17 @@ class MacroOutcome: async def execute_macro(macro: Macro, ctx: ActionContext) -> MacroOutcome: + from .input import PermissionDenied + steps = macro.steps for i, step in enumerate(steps): try: await _run_step(step, ctx) + except PermissionDenied: + # The OS refused a keystroke for want of a grant (#196). Every + # later key step would be refused the same way, even with + # ``continue_on_error``, so stop and let the server toast it. + raise except Exception as exc: err = f"{type(exc).__name__}: {exc}" log.warning("macro step %d failed: %s", i, err) diff --git a/daemon/deckd/diagnostics.py b/daemon/deckd/diagnostics.py index 0a91a8e..db074ec 100644 --- a/daemon/deckd/diagnostics.py +++ b/daemon/deckd/diagnostics.py @@ -59,7 +59,9 @@ class ActionRecord: deck_id: str widget_id: str primitive: str # "shell" | "key" | "dbus" | "terminal" - outcome: str # "ok" | "error" | "guard_dropped" | "no_sink" | "no_widget" | "skipped" + # "ok" | "error" | "guard_dropped" | "lock_dropped" | "no_sink" | + # "no_widget" | "skipped" | "permission_denied" | a macro outcome + outcome: str command_text: str | None # None on the wire error: str | None # None on the wire diff --git a/daemon/deckd/input.py b/daemon/deckd/input.py index c1b19ed..cf20982 100644 --- a/daemon/deckd/input.py +++ b/daemon/deckd/input.py @@ -8,6 +8,23 @@ log = logging.getLogger("deckd.input") +class PermissionDenied(Exception): + """The OS refused a synthetic input event for want of a permission (#196). + + Raised by a sink when it can tell the failure apart from any other + (macOS: osascript's ``-1743`` / ``(1002)``), so the server can tell the + requesting client right away instead of the press vanishing into a log. + ``issue_id`` matches the :class:`~deckd.protocol.HealthIssue` the + backend reports for the same cause; ``message`` is the user-facing + sentence the client shows as-is. + """ + + def __init__(self, issue_id: str, message: str) -> None: + super().__init__(message) + self.issue_id = issue_id + self.message = message + + class ScrollSink(Protocol): def emit_scroll(self, delta: int) -> None: """Emit one high-resolution vertical wheel delta.""" diff --git a/daemon/deckd/platform_macos.py b/daemon/deckd/platform_macos.py index c5c0ab3..9209100 100644 --- a/daemon/deckd/platform_macos.py +++ b/daemon/deckd/platform_macos.py @@ -13,7 +13,7 @@ ``ApplicationServices`` Accessibility raise the chosen one. Window numbers are stable for a window's lifetime and serve as the opaque ``window_id`` sent to the client. Accessibility consent is gated by -``MacKeySink._check_accessibility`` at keysink startup. +``MacKeySink._check_system_events`` at keysink startup. Capability matrix (sketch): @@ -40,21 +40,29 @@ from __future__ import annotations import asyncio +import ctypes +import functools import logging import os +import re import subprocess import sys -from collections.abc import AsyncIterator, Sequence +import threading +from collections.abc import AsyncIterator, Callable, Sequence from types import ModuleType from typing import Any from .macos_app import BUNDLE_ID -from .input import MODIFIER_MAP, KeySink, ScrollSink, name_from_keycode +from .input import MODIFIER_MAP, KeySink, PermissionDenied, ScrollSink, name_from_keycode from .platform import AppInfo, PlatformBackend, RaiseWindowFailed, WindowInfo, _run from .protocol import HealthIssue log = logging.getLogger("deckd.platform_macos") +# Health-issue ids for the two System Events grants (#195, #196). +ACCESSIBILITY_MISSING = "accessibility_missing" +AUTOMATION_MISSING = "automation_system_events_missing" + def _load_quartz() -> tuple[ModuleType | None, bool]: """Lazy import of ``pyobjc-framework-Quartz``. Returns ``(module, available)``. @@ -148,7 +156,7 @@ def _accessibility_missing_issue(app: str, bundle_id: str | None) -> HealthIssue "and on again, or remove it and add it back with +." ) return HealthIssue( - id="accessibility_missing", + id=ACCESSIBILITY_MISSING, severity="error", title="Accessibility permission missing", detail=( @@ -165,6 +173,238 @@ def _accessibility_missing_issue(app: str, bundle_id: str | None) -> HealthIssue ) +def _automation_missing_issue(app: str, bundle_id: str | None) -> HealthIssue: + """The ``automation_system_events_missing`` health issue (#196). + + Automation entries can't be added with + in Settings: macOS lists an + app only after it has asked once. So when the entry is missing (or on + but stale, the same story as Accessibility), the way back is to reset + the decision and let deckd's next System Events call ask again. The + focus poller makes that call within a second, so the prompt appears + on its own. + """ + if bundle_id is not None: + missing = ( + f"If {app} isn't listed, or System Events is already on, run " + f"`tccutil reset AppleEvents {bundle_id}` in Terminal, then click " + "OK when macOS asks to let it control System Events." + ) + else: + missing = ( + f"If {app} isn't listed, quit and reopen it, then click OK when " + "macOS asks to let it control System Events." + ) + return HealthIssue( + id=AUTOMATION_MISSING, + severity="error", + title="Automation permission missing", + detail=( + f"macOS isn't letting {app} control System Events, so key " + "buttons do nothing and the deck may not follow the app in front." + ), + fix_steps=[ + "On the Mac, open System Settings → Privacy & Security → Automation.", + f"Under {app}, turn on System Events.", + missing, + "This warning clears by itself a few seconds after the grant.", + ], + affects=["key", "focus"], + ) + + +# --------------------------------------------------------------------------- +# Permission failures seen at action time (#196) +# --------------------------------------------------------------------------- + +# AppleScript error numbers that mean "a TCC grant is missing", keyed to +# the health issue that explains the fix. -1743 is errAEEventNotPermitted +# (Automation of System Events denied); 1002 is System Events refusing +# ``keystroke`` / ``key code`` because osascript's responsible app lacks +# Accessibility. +_PERMISSION_ERRORS: dict[int, str] = { + -1743: AUTOMATION_MISSING, + 1002: ACCESSIBILITY_MISSING, +} + +# osascript prints ``: execution error: ()``. The +# message text is localised, so classify by the trailing number only. +_OSA_ERROR_NUMBER = re.compile(r"execution error: .*\((-?\d+)\)\s*$") + + +def classify_osascript_error(stderr: str) -> str | None: + """Map osascript stderr to a health-issue id, or ``None`` if unrelated.""" + for line in stderr.splitlines(): + match = _OSA_ERROR_NUMBER.search(line) + if match is not None: + return _PERMISSION_ERRORS.get(int(match.group(1))) + return None + + +class PermissionLedger: + """What osascript calls have shown about the two System Events grants. + + The proactive checks (``AXIsProcessTrusted``, ``AEDeterminePermission- + ToAutomateTarget``) can be unavailable or disagree with what osascript + actually gets, so every System Events call reports its result here + too. A denial is held until a later call proves the grant: a focus + query that succeeds proves Automation; a keystroke that succeeds + proves both. Shared by the key sink (which records) and the focus + backend (which records and reports), and read from the health + poller's worker thread, hence the lock. + """ + + def __init__(self) -> None: + self._denied: set[str] = set() + self._lock = threading.Lock() + + def observe(self, returncode: int, stderr: str, *, keystroke: bool) -> str | None: + """Record one finished osascript call. Returns the denied issue id, if any.""" + if returncode == 0: + self.record_success(keystroke=keystroke) + return None + return self.record_failure(stderr) + + def record_failure(self, stderr: str) -> str | None: + """Record a failed System Events call; only a permission refusal counts. + + Returns the denied issue id, or ``None`` for an unrelated failure, + which says nothing about the grants either way. + """ + issue = classify_osascript_error(stderr) + if issue is None: + return None + with self._lock: + self._denied.add(issue) + if issue == ACCESSIBILITY_MISSING: + # System Events answered, so the Apple event got through. + self._denied.discard(AUTOMATION_MISSING) + return issue + + def record_success(self, *, keystroke: bool) -> None: + """A System Events call worked: Automation is granted, and if it sent + a keystroke, Accessibility is too.""" + with self._lock: + self._denied.discard(AUTOMATION_MISSING) + if keystroke: + self._denied.discard(ACCESSIBILITY_MISSING) + + def denied(self) -> frozenset[str]: + with self._lock: + return frozenset(self._denied) + + +# The process-wide ledger: the key sink and focus backend are built +# separately (``__main__`` / ``default_backend``) but must share it. +PERMISSIONS = PermissionLedger() + +_KEYSTROKE_PROBE = 'tell application "System Events" to keystroke ""' + + +def _probe_keystroke() -> tuple[int, str]: + """Send an empty keystroke through System Events: ``(returncode, stderr)``. + + Exercises both grants without typing anything. Run once at keysink + startup, then only while a denial is held (see + :meth:`MacFocusBackend.health_issues`), so a healthy host never pays + for it in the poll. + """ + try: + proc = subprocess.run( + ["osascript", "-e", _KEYSTROKE_PROBE], + capture_output=True, text=True, timeout=10, + ) + except (OSError, subprocess.TimeoutExpired) as exc: + return -1, f"osascript keystroke probe: {exc}" + return proc.returncode, proc.stderr or "" + + +def _blocked_message(issue_id: str) -> str: + """The toast for a key press the OS refused (#196).""" + app = _responsible_app_name() + if issue_id == AUTOMATION_MISSING: + return ( + f"Key press blocked: {app} needs Automation permission to " + "control System Events." + ) + return f"Key press blocked: {app} needs Accessibility permission." + + +# --------------------------------------------------------------------------- +# Proactive Automation check (#196) +# --------------------------------------------------------------------------- + +_SYSTEM_EVENTS_BUNDLE_ID = "com.apple.systemevents" +_AE_NO_ERR = 0 +_AE_EVENT_NOT_PERMITTED = -1743 # errAEEventNotPermitted + + +def _fourcc(code: str) -> int: + return int.from_bytes(code.encode("ascii"), "big") + + +class _AEDesc(ctypes.Structure): + _fields_ = [("descriptorType", ctypes.c_uint32), ("dataHandle", ctypes.c_void_p)] + + +@functools.cache +def _core_services() -> ctypes.CDLL: + lib = ctypes.CDLL("/System/Library/Frameworks/CoreServices.framework/CoreServices") + lib.AECreateDesc.argtypes = [ + ctypes.c_uint32, ctypes.c_void_p, ctypes.c_long, ctypes.POINTER(_AEDesc) + ] + lib.AECreateDesc.restype = ctypes.c_int16 + lib.AEDeterminePermissionToAutomateTarget.argtypes = [ + ctypes.POINTER(_AEDesc), ctypes.c_uint32, ctypes.c_uint32, ctypes.c_bool + ] + lib.AEDeterminePermissionToAutomateTarget.restype = ctypes.c_int32 + lib.AEDisposeDesc.argtypes = [ctypes.POINTER(_AEDesc)] + lib.AEDisposeDesc.restype = ctypes.c_int16 + return lib + + +def _automation_status(status: int) -> bool | None: + """Map ``AEDeterminePermissionToAutomateTarget``'s OSStatus to a verdict. + + Only ``noErr`` and ``errAEEventNotPermitted`` are answers. Not asked + yet (-1744) isn't a denial: the first System Events call will prompt. + System Events not running (-600) and anything else mean "can't tell". + """ + if status == _AE_NO_ERR: + return True + if status == _AE_EVENT_NOT_PERMITTED: + return False + return None + + +def _automation_permission() -> bool | None: + """May this process send Apple events to System Events? + + Asks TCC without showing the consent prompt (``askUserIfNeeded`` is + false). Plain ctypes against CoreServices: PyObjC doesn't wrap the + ``AEAddressDesc`` the call needs. ``None`` off macOS or on any error. + The call can block briefly, so the health poller runs it off the + event loop. + """ + if sys.platform != "darwin": + return None + try: + lib = _core_services() + target = _SYSTEM_EVENTS_BUNDLE_ID.encode("ascii") + desc = _AEDesc() + if lib.AECreateDesc(_fourcc("bund"), target, len(target), ctypes.byref(desc)) != 0: + return None + try: + status = lib.AEDeterminePermissionToAutomateTarget( + ctypes.byref(desc), _fourcc("****"), _fourcc("****"), False + ) + finally: + lib.AEDisposeDesc(ctypes.byref(desc)) + except Exception as exc: # a broken probe means "unknown", never a crash + log.debug("Automation probe failed: %s", exc) + return None + return _automation_status(status) + + # --------------------------------------------------------------------------- # Focus # --------------------------------------------------------------------------- @@ -191,8 +431,24 @@ class MacFocusBackend(PlatformBackend): None (the Mac concept doesn't map 1:1). """ + def __init__( + self, + *, + ledger: PermissionLedger | None = None, + keystroke_probe: Callable[[], tuple[int, str]] | None = None, + ) -> None: + self._ledger = ledger if ledger is not None else PERMISSIONS + self._keystroke_probe = keystroke_probe or _probe_keystroke + async def get_active_app(self) -> AppInfo: - out = await _run("osascript", "-e", _FOCUS_SCRIPT) + try: + out = await _run("osascript", "-e", _FOCUS_SCRIPT) + except RuntimeError as exc: + # A -1743 here is the focus half of a missing Automation grant + # (#196): the deck stops following the front app. + self._ledger.record_failure(str(exc)) + raise + self._ledger.record_success(keystroke=False) proc_name, _, title = out.partition("|||") return AppInfo( app_id=proc_name.strip() or None, @@ -208,18 +464,33 @@ def capabilities(self) -> frozenset[str]: return frozenset({"watch_active_app", "watch_windows", "raise_window"}) def health_issues(self) -> list[HealthIssue]: - """Report a missing Accessibility grant (issue #195). - - ``AXIsProcessTrusted`` is re-read on every call, so a grant made - while the daemon runs clears the issue on the next poll. ``None`` - (no PyObjC, so no way to tell) reports nothing. + """Report missing Accessibility (#195) and Automation (#196) grants. + + Each grant is missing when its proactive check says so + (``AXIsProcessTrusted`` / ``AEDeterminePermissionToAutomateTarget``, + re-read on every call so a grant made while the daemon runs clears + the issue on the next poll) *or* when an osascript call was refused + for it. A refusal held in the ledger is re-checked with an empty + keystroke each poll, so it clears on its own too. ``None`` from a + proactive check (no way to tell) reports nothing by itself. """ - if _ax_trusted() is not False: + if self._ledger.denied(): + returncode, stderr = self._keystroke_probe() + self._ledger.observe(returncode, stderr, keystroke=True) + held = self._ledger.denied() + accessibility = ACCESSIBILITY_MISSING in held or _ax_trusted() is False + automation = AUTOMATION_MISSING in held or _automation_permission() is False + if not (accessibility or automation): return [] if self._app_name is None: self._app_name = _responsible_app_name() bundle_id = BUNDLE_ID if getattr(sys, "frozen", False) else None - return [_accessibility_missing_issue(self._app_name, bundle_id)] + issues: list[HealthIssue] = [] + if accessibility: + issues.append(_accessibility_missing_issue(self._app_name, bundle_id)) + if automation: + issues.append(_automation_missing_issue(self._app_name, bundle_id)) + return issues async def watch_windows( self, *, interval_s: float = 0.1 @@ -475,7 +746,8 @@ class MacKeySink(KeySink): those into ``LeftMouseDown`` / ``LeftMouseDragged`` / ``LeftMouseUp``. """ - def __init__(self) -> None: + def __init__(self, *, ledger: PermissionLedger | None = None) -> None: + self._ledger = ledger if ledger is not None else PERMISSIONS self._Q, self._has_quartz = _load_quartz() if not self._has_quartz: log.warning( @@ -489,41 +761,36 @@ def __init__(self) -> None: # ``LeftMouseDragged`` (not ``MouseMoved``) while the user is # mid-drag. The server drives this via pad_drag start/end. self._dragging_left = False - self._check_accessibility() + self._check_system_events() self._check_ax_trust() # -- key ----------------------------------------------------------------- - @staticmethod - def _check_accessibility() -> None: + def _check_system_events(self) -> None: """Check that osascript can send keystrokes via System Events. - macOS 14+ may silently deny keystroke injection even when the - terminal is listed in Accessibility preferences (a re-add often - fixes it). This probe warns the user at startup with actionable - instructions instead of failing silently on the first button - press. + Needs both grants: Automation (System Events) and Accessibility. + macOS 14+ may silently deny keystroke injection even when the app + is listed in Accessibility preferences (a re-add often fixes it). + This probe warns at startup with actionable instructions instead + of failing silently on the first button press, and records the + result in the ledger so the client's banner is up before any + button is pressed (#196). """ - try: - proc = subprocess.run( - ["osascript", "-e", - 'tell application "System Events" to keystroke ""'], - capture_output=True, text=True, timeout=10, - ) - if proc.returncode != 0: - term = _terminal_name() - reason = proc.stderr.strip() or f"exit code {proc.returncode}" - log.warning( - "[mac key] osascript keystroke probe failed: %s\n" - " Grant Accessibility to %s in System Settings > Privacy & Security.\n" - " If already listed, remove it, re-add it, then restart the terminal.", - reason, - term, - ) - except FileNotFoundError: - log.warning("[mac key] osascript not found; key injection unavailable") - except subprocess.TimeoutExpired: - log.warning("[mac key] osascript keystroke probe timed out") + returncode, stderr = _probe_keystroke() + issue = self._ledger.observe(returncode, stderr, keystroke=True) + if returncode == 0: + return + reason = stderr.strip() or f"exit code {returncode}" + grant = "Automation > System Events" if issue == AUTOMATION_MISSING else "Accessibility" + log.warning( + "[mac key] osascript keystroke probe failed: %s\n" + " Grant %s to %s in System Settings > Privacy & Security.\n" + " If already listed, remove it, re-add it, then restart the app.", + reason, + grant, + _responsible_app_name(), + ) @staticmethod def _check_ax_trust() -> None: @@ -559,6 +826,13 @@ def emit_key(self, keycodes: list[int]) -> None: text=True, ) _, err = proc.communicate() + err = err or "" + issue = self._ledger.observe(proc.returncode or 0, err, keystroke=True) + if issue is not None: + # Refused for want of a grant (#196): raise so the server can + # toast the requesting client instead of the press vanishing. + log.warning("[mac key] osascript refused (%s): %s", issue, err.strip()) + raise PermissionDenied(issue, _blocked_message(issue)) if err: log.warning("[mac key] osascript stderr: %s", err.strip()) else: diff --git a/daemon/deckd/protocol.py b/daemon/deckd/protocol.py index 6729b6d..9a7c19f 100644 --- a/daemon/deckd/protocol.py +++ b/daemon/deckd/protocol.py @@ -216,6 +216,28 @@ class MediaErrorMessage(BaseModel): retryable: bool = True +class ActionErrorMessage(BaseModel): + """Daemon -> client push: an action this session triggered was refused + by the OS (issue #196). + + Sent only to the *requesting* session, like ``media_error``: the + failure is a consequence of one session's press. Today the one + ``reason`` is ``permission_denied`` (macOS refused the keystroke for + want of Accessibility or Automation); the client shows ``message`` + as a toast. ``issue_id`` names the :class:`HealthIssue` with the fix + steps, which the daemon raises at the same time. ``id`` is the + pressed widget's id, ``None`` for manual-control keys and typed text. + """ + + model_config = ConfigDict(extra="forbid") + + type: Literal["action_error"] + id: str | None = None + reason: Literal["permission_denied"] + issue_id: str + message: str + + class ChromeMediaMessage(BaseModel): """Daemon -> client push: the chrome media icon's passive playback-state snapshot (issue #47). @@ -384,13 +406,13 @@ class HealthIssue(BaseModel): """One thing the daemon knows is broken on this host (issue #195). Platform-neutral: a backend mints these from whatever it can probe - (macOS Accessibility trust today; Automation, Linux ``uinput`` access - are follow-ups). ``id`` is a stable machine key (``accessibility_missing``) - the client can dedupe and dismiss by. ``fix_steps`` are complete, + (macOS Accessibility trust and Automation of System Events today; + Linux ``uinput`` access is a follow-up). ``id`` is a stable machine + key (``accessibility_missing``) the client can dedupe and dismiss by. ``fix_steps`` are complete, user-facing sentences that name the exact app to grant and the Settings path. ``affects`` lists the input primitives that silently fail while the issue stands (``pointer``, ``scroll``, ``key``, - ``raise_window``, ...). + ``raise_window``, ``focus``, ...). """ model_config = ConfigDict(extra="forbid") @@ -419,7 +441,7 @@ class HealthMessage(BaseModel): ServerMessage = Annotated[ - Union[DeckMessage, StateMessage, BrightnessMessage, WidgetUpdateMessage, MediaStateMessage, MediaErrorMessage, ChromeMediaMessage, EventMessage, MacroResultMessage, ConfirmRequestMessage, RunningWindowsMessage, HealthMessage, ErrorMessage], + Union[DeckMessage, StateMessage, BrightnessMessage, WidgetUpdateMessage, MediaStateMessage, MediaErrorMessage, ActionErrorMessage, ChromeMediaMessage, EventMessage, MacroResultMessage, ConfirmRequestMessage, RunningWindowsMessage, HealthMessage, ErrorMessage], Field(discriminator="type"), ] diff --git a/daemon/deckd/server.py b/daemon/deckd/server.py index 0b53e69..9cf07aa 100644 --- a/daemon/deckd/server.py +++ b/daemon/deckd/server.py @@ -21,7 +21,7 @@ from . import __version__ from . import protocol as p from .actions import ActionContext, MacroOutcome, execute as run_action -from .input import ScrollController, parse_key_combo, text_to_combos +from .input import PermissionDenied, ScrollController, parse_key_combo, text_to_combos from .decks import ( Deck, DeckLoadError, @@ -749,6 +749,9 @@ async def _timed_call(message: DbusMessage) -> DbusMessage: # that make input fail silently. Starts empty ("nothing known to # be wrong"); the poller fills it within one interval. self._health_issues: list[p.HealthIssue] = [] + # One-off re-polls after a permission refusal (#196); held so the + # loop doesn't garbage-collect them mid-flight. + self._health_refreshes: set[asyncio.Task[None]] = set() # Session screen awareness (issue #160). The backend may take a # couple of seconds to answer the first poll, so the daemon # opens on "nothing wrong" — which is also what the client's @@ -1325,6 +1328,47 @@ async def _refuse_locked(self, session: Session, what: str, primitive: str) -> N except (ConnectionResetError, RuntimeError, ConnectionError): pass + async def _report_permission_denied( + self, + session: Session, + exc: PermissionDenied, + *, + primitive: str, + widget_id: str | None, + command_text: str | None = None, + ) -> None: + """An action the OS refused for want of a grant (issue #196). + + Records ``permission_denied`` in the ring buffer and ``/metrics``, + toasts the requesting session (not a broadcast: it was this + session's press), and re-polls health so the banner with the fix + steps comes up with the toast instead of on the next tick. + """ + log.info("[%s] refused by the OS: %s", primitive, exc.issue_id) + self.metrics.record_action(primitive, "permission_denied") + self.recent_actions.add( + ActionRecord( + ts=time.time(), + deck_id=self._current_app_id, + widget_id=(widget_id or primitive)[:64], + primitive=primitive, + outcome="permission_denied", + command_text=command_text, + error=exc.message, + ) + ) + self._refresh_health() + with contextlib.suppress(ConnectionResetError, RuntimeError, ConnectionError): + await session.send( + p.ActionErrorMessage( + type="action_error", + id=widget_id, + reason="permission_denied", + issue_id=exc.issue_id, + message=exc.message, + ) + ) + async def push_session_state_snapshot(self, session: Session) -> None: """Replay the current session state to a just-connected client. @@ -1371,7 +1415,7 @@ async def run_health_watcher(self, *, interval_s: float | None = None) -> None: failing = False while True: try: - issues = list(backend.health_issues()) + issues = await self._probe_health(backend) except Exception as exc: # a broken probe must not end the poller if not failing: log.warning("health probe failed (will keep retrying): %s", exc) @@ -1381,6 +1425,30 @@ async def run_health_watcher(self, *, interval_s: float | None = None) -> None: await self._on_health_issues(issues) await asyncio.sleep(interval) + @staticmethod + async def _probe_health(backend: "PlatformBackend") -> "list[p.HealthIssue]": + # Off the event loop: the macOS probes can shell out to osascript + # or block in TCC (#196). + return list(await asyncio.to_thread(backend.health_issues)) + + def _refresh_health(self) -> None: + """Re-poll health now, outside the watcher's cadence (#196).""" + backend = self.focus_backend + if backend is None: + return + + async def once() -> None: + try: + issues = await self._probe_health(backend) + except Exception as exc: + log.debug("health refresh failed: %s", exc) + return + await self._on_health_issues(issues) + + task = asyncio.create_task(once()) + self._health_refreshes.add(task) + task.add_done_callback(self._health_refreshes.discard) + async def _on_health_issues(self, issues: "list[p.HealthIssue]") -> None: """Record the latest list and broadcast it, only when it changed.""" if issues == self._health_issues: @@ -2723,8 +2791,14 @@ async def _dispatch(self, session: Session, data: dict) -> None: await self._refuse_locked(session, tmsg.text, "type") return if self.key_sink is not None: - for combo in text_to_combos(tmsg.text): - self.key_sink.emit_key(combo) + try: + for combo in text_to_combos(tmsg.text): + self.key_sink.emit_key(combo) + except PermissionDenied as exc: + # No command_text: typed text stays out of the ring. + await self._report_permission_denied( + session, exc, primitive="type", widget_id=None + ) return if msg_type == "key": kmsg = p.KeyMessage.model_validate(data) @@ -2734,7 +2808,13 @@ async def _dispatch(self, session: Session, data: dict) -> None: await self._refuse_locked(session, kmsg.combo, "key") return if self.key_sink is not None: - self.key_sink.emit_key(parse_key_combo(kmsg.combo)) + try: + self.key_sink.emit_key(parse_key_combo(kmsg.combo)) + except PermissionDenied as exc: + await self._report_permission_denied( + session, exc, primitive="key", widget_id=None, + command_text=kmsg.combo, + ) return if msg_type == "media_command": media_command = p.MediaCommandMessage.model_validate(data) @@ -2958,6 +3038,12 @@ async def _dispatch_press(self, session: Session, data: dict) -> None: widget.action = action try: await run_action(widget, ctx) + except PermissionDenied as exc: + primitive, command_text = _action_primitive(action) + await self._report_permission_denied( + session, exc, primitive=primitive, widget_id=press.id, + command_text=command_text, + ) finally: widget.action = original return @@ -3184,7 +3270,14 @@ async def _run_confirmed_action( ) ) ) - outcome = await run_action(widget, ctx) + try: + outcome = await run_action(widget, ctx) + except PermissionDenied as exc: + await self._report_permission_denied( + session, exc, primitive=primitive, widget_id=widget.id, + command_text=command_text, + ) + return if isinstance(outcome, MacroOutcome) and outcome.outcome != "ok": self.metrics.record_action(primitive, outcome.outcome) self.recent_actions.add( diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 41419c0..6d7828b 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -284,7 +284,7 @@ Every non-happy state explains itself in plain language rather than leaving a st - **Reconnecting / disconnected** — when the socket drops, an overlay sits over the last-rendered deck naming the attempt count and the last error (e.g. *Attempt 3 — daemon not reachable*). While the client is retrying it offers **Cancel** to pause the auto-retry loop; once paused (or when the socket is closed) it offers **Retry** to reconnect immediately. The bottom-strip connection dot keeps showing live / reconnecting / disconnected alongside it. - **Screen locked / asleep** — the full-surface lock takeover names the cause (*Screensaver or lock screen active on ‹host›*) and states that input is held until you unlock. The soft "asleep" banner shown for a blank that hasn't locked says *suspend or display blank*, and a press wakes the machine. - **Deck errors** — a deck that fails to load (bad YAML or a schema violation) replaces the grid with the pydantic detail plus a plain-language line naming the deck and the offending widget (`Couldn't load the "firefox" deck. Widget "back" is invalid.`) and a **Return to focused app** button that clears a pinned chrome view. A chrome view that no longer resolves shows *That view isn't available on this daemon.* with the same button. -- **Missing permissions** — when the daemon knows input will fail silently because an OS permission is missing (today: macOS Accessibility not granted), a banner above the grid names the problem, what won't work (*trackpad & clicks, scrolling, key presses, raising windows from the list*), and the exact fix, including the app to grant and the System Settings path. It clears by itself a few seconds after you grant the permission, with no reconnect needed. **Dismiss** hides it for the rest of this page session. `deckctl diag` shows the same list under `health`. +- **Missing permissions** — when the daemon knows input will fail silently because an OS permission is missing (today: macOS Accessibility or Automation → System Events not granted), a banner above the grid names the problem, what won't work (*trackpad & clicks, scrolling, key presses, raising windows from the list, switching decks with the app in front*), and the exact fix, including the app to grant and the System Settings path. Pressing a key button the OS refuses also shows a toast at once (*Key press blocked: deckd.app needs Accessibility permission.*). It clears by itself a few seconds after you grant the permission, with no reconnect needed. **Dismiss** hides it for the rest of this page session. `deckctl diag` shows the same list under `health`. - **Media errors** — a media command the daemon couldn't deliver (player gone, method rejected) surfaces a non-blocking toast naming the player (`VLC media player — player disappeared`) with **Retry** (re-sends the last command for that player) and **Dismiss**. Each of these is announced through the client's `aria-live` region, and every animation is suppressed under `prefers-reduced-motion: reduce` or the in-app *Reduce motion* setting. @@ -707,7 +707,7 @@ To check, look for these lines in `~/Library/Logs/deckd.log` after a restart. A - `osascript is not allowed to send keystrokes (1002)` → Accessibility missing. - `Not authorized to send Apple events to System Events. (-1743)` → Automation missing. -The phone shows a banner while Accessibility is missing ([#195](https://github.com/jonocodes/deckd/issues/195)); detecting a missing Automation grant is a follow-up. +The phone shows a banner while either grant is missing ([#195](https://github.com/jonocodes/deckd/issues/195), [#196](https://github.com/jonocodes/deckd/issues/196)), and a key press refused for either one toasts straight away. Automation can't be added with **+**: macOS lists deckd only after it has asked once. If deckd isn't listed, or System Events is on but keys still fail, run `tccutil reset AppleEvents com.deckd.daemon` and click **OK** when macOS asks again. #### LAN access diff --git a/docs/PLATFORM-PARITY.md b/docs/PLATFORM-PARITY.md index 99e1068..40e98eb 100644 --- a/docs/PLATFORM-PARITY.md +++ b/docs/PLATFORM-PARITY.md @@ -148,7 +148,7 @@ so KDE could honestly re-advertise them. | grant | gates | failure mode without it | |---|---|---| | Accessibility | Quartz `CGEventPost` (pointer, click, drag, scroll) + the `AXRaise` half of `raise_window` | events **silently dropped**, no error; raise activates the app then fails `kAXErrorAPIDisabled` (-25211) | - | System Events | focus detection + `osascript keystroke` | osascript exits non-zero; `MacKeySink._check_accessibility` warns at startup | + | System Events | focus detection + `osascript keystroke` | osascript exits non-zero (`-1743` Automation, `(1002)` Accessibility); the client gets a health banner and, on a refused key press, an `action_error` toast (#196) | | Screen Recording | `kCGWindowName` in `CGWindowList` | every enumerated `title` is `None`; rows label by app name | This is why "it doesn't work on my Mac" is usually a *process-tree* diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index 861f827..7a557d8 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -241,14 +241,21 @@ When the daemon knows input will fail silently because an OS permission is missi - **On change**, every session gets `{"type": "health", "issues": [...]}` with the full list. An empty list clears the banner. - **On connect**, the current list is replayed only when it isn't empty; the client resets to "no issues" on every new connection, so a healthy daemon needs no frame. -- `affects` names the primitives that won't work (`pointer`, `scroll`, `key`, `raise_window`). Unknown values render as-is, so a newer daemon can add one without a client release. +- `affects` names the primitives that won't work (`pointer`, `scroll`, `key`, `raise_window`, `focus`). Unknown values render as-is, so a newer daemon can add one without a client release. - `GET /diag` carries the same list under `health.issues`. Issues reported today: | `id` | Platform | When | Clears | |---|---|---|---| -| `accessibility_missing` | macOS | `AXIsProcessTrusted()` is false for the responsible app (`deckd.app` when packaged, else the launching terminal) | Within one poll of the grant, without a restart. If buttons still do nothing, quit and reopen the app. | +| `accessibility_missing` | macOS | `AXIsProcessTrusted()` is false for the responsible app (`deckd.app` when packaged, else the launching terminal), or an osascript keystroke failed with `(1002)` | Within one poll of the grant, without a restart. If buttons still do nothing, quit and reopen the app. | +| `automation_system_events_missing` | macOS | `AEDeterminePermissionToAutomateTarget` (asked without prompting) says the app may not send Apple events to System Events, or a focus query or keystroke failed with `(-1743)` | Within one poll of the grant. | + +The proactive checks can be unavailable or wrong, so the osascript calls also report what they see (#196). A refusal is held until a later call proves the grant: a focus query that succeeds clears the Automation issue; while either refusal is held, each poll re-checks with an empty keystroke, which clears both once it succeeds. + +### Action errors (`action_error`, #196) + +When the OS refuses an action for want of a permission (today: a macOS key press, `key:` / `text:` / macro key steps / manual-control keys and typing), the daemon sends the *requesting* session `{"type": "action_error", "id": , "reason": "permission_denied", "issue_id": , "message": "Key press blocked: …"}` and re-polls health at once, so the toast and the banner with the fix steps arrive together. A macro stops at the refused step, even with `continue_on_error`. The attempt is recorded with `outcome="permission_denied"` in `/actions/recent` and `deckd_action_outcome_total` on `/metrics`. For a widget press it follows the usual `ok` (dispatched) record, the same pairing a failed macro gets (`ok` then `failed-at-step`). With `--no-focus` there is no platform backend to report health, so the toast still arrives but no banner does. ## Where to read next diff --git a/tests/conftest.py b/tests/conftest.py index 304f056..c12b138 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -189,6 +189,22 @@ def __call__(self, bus_type: Any) -> Any: # Server fixture # --------------------------------------------------------------------------- +@pytest.fixture(autouse=True) +def _no_host_tcc(monkeypatch: pytest.MonkeyPatch) -> None: + """Keep the macOS permission checks off the host's real TCC state (#196). + + ``MacFocusBackend.health_issues`` asks TCC whether this process may + automate System Events, and the process-wide ledger remembers refusals + across calls. On a Mac checkout either would make a test's result + depend on the developer's own grants (or on an earlier test), so every + test starts with "can't tell" and an empty ledger. + """ + import deckd.platform_macos as mac + + monkeypatch.setattr(mac, "_automation_permission", lambda: None) + monkeypatch.setattr(mac, "PERMISSIONS", mac.PermissionLedger()) + + @pytest.fixture def as_linux(monkeypatch: pytest.MonkeyPatch) -> None: """Pin ``sys.platform`` to Linux for tests that assert the Linux branch. diff --git a/tests/test_action_errors.py b/tests/test_action_errors.py new file mode 100644 index 0000000..4955e6a --- /dev/null +++ b/tests/test_action_errors.py @@ -0,0 +1,267 @@ +"""Action-time permission errors: toast + diagnostics (issue #196). + +When a key action fails because an OS permission is missing, the sink +raises :class:`PermissionDenied`. The server must: + +* tell the *requesting* session (``action_error``) so the client toasts, +* count it as ``outcome="permission_denied"`` in the ring buffer and + ``/metrics``, +* re-poll health right away so the banner doesn't wait for the next tick. +""" +from __future__ import annotations + +import asyncio +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest +import websockets +from aiohttp.test_utils import TestServer +from pydantic import TypeAdapter, ValidationError + +from deckd import protocol as p +from deckd.input import PermissionDenied + +from conftest import make_test_server + +_server_adapter = TypeAdapter(p.ServerMessage) + +ISSUE = "accessibility_missing" +MESSAGE = "Key press blocked: deckd.app needs Accessibility permission." + +DECK = """ +match: + - default +widgets: + - id: new-window + kind: button + label: New window + action: + key: "super+n" + - id: hello + kind: button + label: Type hello + action: + text: "hi" + - id: two-keys + kind: button + label: Two keys + macro: + steps: + - type: key + value: "a" + - type: key + value: "b" + - id: launch + kind: button + label: Launch + action: + shell: "true" +""" + + +# --------------------------------------------------------------------------- +# Wire shape +# --------------------------------------------------------------------------- + + +def test_action_error_wire_shape() -> None: + msg = p.ActionErrorMessage( + type="action_error", + id="new-window", + reason="permission_denied", + issue_id=ISSUE, + message=MESSAGE, + ) + assert msg.model_dump() == { + "type": "action_error", + "id": "new-window", + "reason": "permission_denied", + "issue_id": ISSUE, + "message": MESSAGE, + } + parsed = _server_adapter.validate_python(msg.model_dump()) + assert isinstance(parsed, p.ActionErrorMessage) + + +def test_action_error_id_is_optional() -> None: + """Manual-control keys and typed text have no widget id.""" + msg = p.ActionErrorMessage( + type="action_error", reason="permission_denied", issue_id=ISSUE, message=MESSAGE + ) + assert msg.id is None + + +def test_action_error_rejects_unknown_reason() -> None: + with pytest.raises(ValidationError): + p.ActionErrorMessage.model_validate( + {"type": "action_error", "reason": "nope", "issue_id": ISSUE, "message": "x"} + ) + + +# --------------------------------------------------------------------------- +# Server behaviour +# --------------------------------------------------------------------------- + + +class _DenyingSink: + """Key sink whose keystrokes are all refused by the OS.""" + + def __init__(self, on_deny=None) -> None: + self.calls = 0 + self._on_deny = on_deny + + def emit_key(self, keycodes: list[int]) -> None: + self.calls += 1 + if self._on_deny is not None: + self._on_deny() + raise PermissionDenied(ISSUE, MESSAGE) + + def emit_pointer(self, dx: int, dy: int) -> None: + pass + + def emit_click(self, button: str, pressed: bool) -> None: + pass + + def close(self) -> None: + pass + + +async def _boot(monkeypatch, tmp_path: Path, sink, backend=None): + import deckd.actions as actions_mod + + async def fake_shell(_cmd: str) -> None: + pass + + monkeypatch.setattr(actions_mod, "_run_shell", fake_shell) + (tmp_path / "default.yaml").write_text(DECK) + server, _scroll, _key, _dbus = make_test_server(decks_dir=tmp_path) + server.key_sink = sink + server.focus_backend = backend + ts = TestServer(server.app, host="127.0.0.1") + await ts.start_server() + return ts, server + + +async def _read_until(ws, msg_type: str, timeout: float = 2.0) -> dict: + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + while True: + raw = await asyncio.wait_for(ws.recv(), timeout=deadline - loop.time()) + msg = json.loads(raw) + if msg.get("type") == msg_type: + return msg + + +@pytest.mark.parametrize( + ("frame", "widget_id", "primitive"), + [ + ({"type": "press", "id": "new-window"}, "new-window", "key"), + ({"type": "press", "id": "hello"}, "hello", "text"), + ({"type": "press", "id": "two-keys"}, "two-keys", "macro"), + ({"type": "key", "combo": "super+n"}, None, "key"), + ({"type": "type", "text": "hi"}, None, "type"), + ], +) +async def test_permission_denied_toasts_the_requesting_session( + monkeypatch, tmp_path: Path, frame: dict, widget_id: str | None, primitive: str +) -> None: + sink = _DenyingSink() + ts, server = await _boot(monkeypatch, tmp_path, sink) + try: + async with websockets.connect(f"ws://127.0.0.1:{ts.port}/ws") as ws: + await _read_until(ws, "deck") + await ws.send(json.dumps(frame)) + err = await _read_until(ws, "action_error", timeout=1.0) + assert err == { + "type": "action_error", + "id": widget_id, + "reason": "permission_denied", + "issue_id": ISSUE, + "message": MESSAGE, + } + # One refused keystroke is enough: the rest of a macro / text + # would be refused the same way, so it stops at the first. + assert sink.calls == 1 + snap = server.recent_actions.snapshot() + denied = [r for r in snap if r.outcome == "permission_denied"] + assert len(denied) == 1 + assert denied[0].primitive == primitive + assert denied[0].error == MESSAGE + assert server.metrics.action_outcome_total[f"{primitive}/permission_denied"] == 1 + assert 'outcome="permission_denied"' in server.metrics.render() + finally: + await ts.close() + await server.scroll.close() + + +async def test_permission_denied_is_not_broadcast(monkeypatch, tmp_path: Path) -> None: + sink = _DenyingSink() + ts, server = await _boot(monkeypatch, tmp_path, sink) + try: + async with ( + websockets.connect(f"ws://127.0.0.1:{ts.port}/ws") as presser, + websockets.connect(f"ws://127.0.0.1:{ts.port}/ws") as bystander, + ): + await _read_until(presser, "deck") + await _read_until(bystander, "deck") + await presser.send(json.dumps({"type": "press", "id": "new-window"})) + await _read_until(presser, "action_error", timeout=1.0) + with pytest.raises(TimeoutError): + await _read_until(bystander, "action_error", timeout=0.25) + finally: + await ts.close() + await server.scroll.close() + + +async def test_permission_denied_refreshes_health_immediately( + monkeypatch, tmp_path: Path +) -> None: + """The banner comes up with the toast, not on the next poll tick.""" + state: dict[str, list[p.HealthIssue]] = {"issues": []} + issue = p.HealthIssue( + id=ISSUE, + severity="error", + title="Accessibility permission missing", + detail="", + fix_steps=[], + affects=["key"], + ) + + def deny() -> None: + state["issues"] = [issue] # what the ledger now reports + + backend = SimpleNamespace( + capabilities=lambda: frozenset({"watch_active_app"}), + health_issues=lambda: list(state["issues"]), + ) + ts, server = await _boot(monkeypatch, tmp_path, _DenyingSink(on_deny=deny), backend) + try: + # No watcher running: only the refresh can deliver the frame. + async with websockets.connect(f"ws://127.0.0.1:{ts.port}/ws") as ws: + await _read_until(ws, "deck") + await ws.send(json.dumps({"type": "press", "id": "new-window"})) + health = await _read_until(ws, "health", timeout=1.0) + assert [i["id"] for i in health["issues"]] == [ISSUE] + finally: + await ts.close() + await server.scroll.close() + + +async def test_other_primitives_still_run(monkeypatch, tmp_path: Path) -> None: + """A missing keystroke grant doesn't touch shell buttons.""" + sink = _DenyingSink() + ts, server = await _boot(monkeypatch, tmp_path, sink) + try: + async with websockets.connect(f"ws://127.0.0.1:{ts.port}/ws") as ws: + await _read_until(ws, "deck") + await ws.send(json.dumps({"type": "press", "id": "launch"})) + with pytest.raises(TimeoutError): + await _read_until(ws, "action_error", timeout=0.25) + assert not any( + r.outcome == "permission_denied" for r in server.recent_actions.snapshot() + ) + finally: + await ts.close() + await server.scroll.close() diff --git a/tests/test_actions.py b/tests/test_actions.py index e2ae5a3..64a7768 100644 --- a/tests/test_actions.py +++ b/tests/test_actions.py @@ -520,6 +520,61 @@ def fake_which(name: str) -> str | None: assert len(ctrlv) == 1 +async def test_press_text_paste_refused_still_restores_clipboard( + monkeypatch: pytest.MonkeyPatch, as_linux: None, +) -> None: + """Issue #196: when the OS refuses the paste keystroke, the user's + clipboard is put back (without the restore delay, which only exists to + let a paste that happened finish) before the refusal propagates.""" + import deckd.actions as actions_mod + from unittest.mock import AsyncMock + + from deckd.input import PermissionDenied + + written: list[bytes] = [] + + async def fake_exec(*args, stdin=None, stdout=None, stderr=None, + start_new_session=False): + mock = AsyncMock() + mock.stdout = None + mock.stdin = None + if stdout is not None: # the clipboard read + mock.stdout = AsyncMock() + mock.communicate = AsyncMock(return_value=(b"previous clipboard", None)) + if stdin is not None: # a clipboard write + mock.stdin = AsyncMock() + mock.stdin.write = lambda data: written.append(data) + mock.wait = AsyncMock() + return mock + + monkeypatch.setattr(actions_mod.asyncio, "create_subprocess_exec", fake_exec) + monkeypatch.setattr( + actions_mod.shutil, "which", + lambda name: {"wl-copy": "/usr/bin/wl-copy", "wl-paste": "/usr/bin/wl-paste"}.get(name), + ) + slept: list[float] = [] + + async def fake_sleep(seconds: float) -> None: + slept.append(seconds) + + monkeypatch.setattr(actions_mod.asyncio, "sleep", fake_sleep) + + class Refusing(FakePointerSink): + def emit_key(self, keycodes: list[int]) -> None: + raise PermissionDenied("accessibility_missing", "Key press blocked") + + widget = Widget( + id="text-btn", + kind="button", + action=Action(text="secret", text_mode="paste", restore_clipboard=True), + ) + with pytest.raises(PermissionDenied): + await run_action(widget, _ctx_key_sink(Refusing())) + + assert written == [b"secret", b"previous clipboard"] + assert slept == [] + + async def test_press_text_paste_no_clipboard_tool_falls_back_to_simulate( monkeypatch: pytest.MonkeyPatch, as_linux: None, ) -> None: diff --git a/tests/test_macos_permissions.py b/tests/test_macos_permissions.py new file mode 100644 index 0000000..6f2e44e --- /dev/null +++ b/tests/test_macos_permissions.py @@ -0,0 +1,355 @@ +"""macOS Automation + action-time permission failures (issue #196). + +Key buttons on macOS go through ``osascript`` -> System Events, which needs +two grants: Automation (System Events) and Accessibility. Either one +missing used to fail silently. These tests pin: + +* osascript stderr -> health-issue classification (no false positives), +* the ledger that remembers what an action saw, and clears on success, +* the proactive Automation check's status mapping, +* the backend folding both into ``health_issues()``, +* the key sink raising :class:`PermissionDenied` so the server can toast. +""" +from __future__ import annotations + +import sys + +import pytest + +import deckd.platform_macos as mac +from deckd.input import PermissionDenied + +AUTOMATION = "automation_system_events_missing" +ACCESSIBILITY = "accessibility_missing" + +# Real stderr lines, as osascript prints them. +STDERR_1743 = ( + "36:61: execution error: Not authorized to send Apple events to " + "System Events. (-1743)" +) +STDERR_1002 = ( + "36:61: execution error: System Events got an error: osascript is not " + "allowed to send keystrokes. (1002)" +) + + +@pytest.fixture(autouse=True) +def _isolated(monkeypatch): + """Trusted for Accessibility and named like the packaged app. (conftest + already stubs the Automation probe and gives each test a fresh ledger.)""" + monkeypatch.setattr(mac, "_ax_trusted", lambda: True) + monkeypatch.setattr(mac, "_responsible_app_name", lambda: "deckd.app") + + +# --------------------------------------------------------------------------- +# stderr classification +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("stderr", "expected"), + [ + (STDERR_1743, AUTOMATION), + (STDERR_1002, ACCESSIBILITY), + # Trailing whitespace / newline as read from a pipe. + (STDERR_1743 + "\n", AUTOMATION), + # Localised message text: the code is what counts. + ("0:44: execution error: Keine Berechtigung. (-1743)", AUTOMATION), + ], +) +def test_classifies_permission_errors(stderr: str, expected: str) -> None: + assert mac.classify_osascript_error(stderr) == expected + + +@pytest.mark.parametrize( + "stderr", + [ + "", + # Unrelated AppleScript errors. + "0:12: syntax error: Expected end of line but found identifier. (-2741)", + "1:80: execution error: System Events got an error: Can't get " + "window 1 of process \"Finder\". Invalid index. (-1719)", + # The digits appear, but not as the error code. + "1:80: execution error: Can't get window 1002 of process \"X\". (-1728)", + "1:80: execution error: Can't get item (-1743) of list. (-1728)", + "osascript: no such file", + ], +) +def test_unrelated_errors_are_not_permission_errors(stderr: str) -> None: + assert mac.classify_osascript_error(stderr) is None + + +# --------------------------------------------------------------------------- +# Ledger +# --------------------------------------------------------------------------- + + +def test_ledger_records_a_denial() -> None: + ledger = mac.PermissionLedger() + assert ledger.observe(1, STDERR_1743, keystroke=True) == AUTOMATION + assert ledger.denied() == {AUTOMATION} + + +def test_ledger_ignores_unrelated_failures() -> None: + ledger = mac.PermissionLedger() + ledger.observe(1, STDERR_1743, keystroke=False) + assert ledger.observe(1, "0:1: execution error: boom (-1719)", keystroke=True) is None + # An unrelated failure says nothing about the grant either way. + assert ledger.denied() == {AUTOMATION} + + +def test_ledger_accessibility_denial_proves_automation() -> None: + """``(1002)`` comes back *from* System Events, so the Apple event got + through: Automation is granted even if an earlier call said otherwise.""" + ledger = mac.PermissionLedger() + ledger.observe(1, STDERR_1743, keystroke=True) + ledger.observe(1, STDERR_1002, keystroke=True) + assert ledger.denied() == {ACCESSIBILITY} + + +def test_ledger_focus_success_clears_automation_only() -> None: + """A focus query only proves Automation; it sends no keystrokes.""" + ledger = mac.PermissionLedger() + ledger.observe(1, STDERR_1002, keystroke=True) + ledger.observe(1, STDERR_1743, keystroke=False) + ledger.observe(0, "", keystroke=False) + assert ledger.denied() == {ACCESSIBILITY} + + +def test_ledger_keystroke_success_clears_both() -> None: + ledger = mac.PermissionLedger() + ledger.observe(1, STDERR_1002, keystroke=True) + ledger.observe(0, "", keystroke=True) + assert ledger.denied() == frozenset() + + +# --------------------------------------------------------------------------- +# Proactive Automation check +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("status", "expected"), + [ + (0, True), # noErr: granted + (-1743, False), # errAEEventNotPermitted: denied + (-1744, None), # errAEEventWouldRequireUserConsent: not asked yet + (-600, None), # procNotFound: System Events isn't running + (-50, None), # anything else: can't tell + ], +) +def test_automation_status_mapping(status: int, expected: bool | None) -> None: + assert mac._automation_status(status) is expected + + +@pytest.mark.skipif(sys.platform != "darwin", reason="needs CoreServices") +def test_automation_probe_runs_on_macos(monkeypatch) -> None: + """The real ctypes call answers without prompting or raising.""" + monkeypatch.undo() # drop the autouse stub for this one + assert mac._automation_permission() in (True, False, None) + + +def test_automation_probe_is_unknown_off_macos(monkeypatch) -> None: + monkeypatch.undo() + monkeypatch.setattr(sys, "platform", "linux") + assert mac._automation_permission() is None + + +# --------------------------------------------------------------------------- +# Backend -> health issues +# --------------------------------------------------------------------------- + + +def _ids(backend: mac.MacFocusBackend) -> list[str]: + return [i.id for i in backend.health_issues()] + + +def test_proactive_automation_denial_raises_the_issue(monkeypatch) -> None: + monkeypatch.setattr(mac, "_automation_permission", lambda: False) + monkeypatch.setattr(sys, "frozen", True, raising=False) + + issues = mac.MacFocusBackend().health_issues() + + assert [i.id for i in issues] == [AUTOMATION] + issue = issues[0] + assert issue.severity == "error" + text = " ".join([issue.title, issue.detail, *issue.fix_steps]) + assert "deckd.app" in text + assert "Privacy & Security → Automation" in text + assert "System Events" in text + assert any("tccutil reset AppleEvents com.deckd.daemon" in s for s in issue.fix_steps) + assert set(issue.affects) == {"key", "focus"} + + +def test_automation_issue_from_a_checkout_offers_no_tccutil(monkeypatch) -> None: + monkeypatch.setattr(mac, "_automation_permission", lambda: False) + monkeypatch.setattr(mac, "_responsible_app_name", lambda: "iTerm.app") + monkeypatch.delattr(sys, "frozen", raising=False) + + (issue,) = mac.MacFocusBackend().health_issues() + text = " ".join(issue.fix_steps) + assert "iTerm.app" in text + assert "tccutil" not in text + + +@pytest.mark.parametrize("answer", [True, None]) +def test_no_automation_issue_when_granted_or_unknown(monkeypatch, answer) -> None: + monkeypatch.setattr(mac, "_automation_permission", lambda: answer) + assert _ids(mac.MacFocusBackend()) == [] + + +def test_both_grants_missing_lists_both(monkeypatch) -> None: + monkeypatch.setattr(mac, "_ax_trusted", lambda: False) + monkeypatch.setattr(mac, "_automation_permission", lambda: False) + assert _ids(mac.MacFocusBackend()) == [ACCESSIBILITY, AUTOMATION] + + +def test_reactive_denial_raises_the_issue_while_the_probe_still_fails() -> None: + """The proactive check says nothing (or is wrong), but an action saw + -1743: the issue stands as long as a re-probe still fails.""" + ledger = mac.PermissionLedger() + ledger.observe(1, STDERR_1743, keystroke=True) + probes: list[int] = [] + + def probe() -> tuple[int, str]: + probes.append(1) + return 1, STDERR_1743 + + backend = mac.MacFocusBackend(ledger=ledger, keystroke_probe=probe) + assert _ids(backend) == [AUTOMATION] + assert probes, "a held reactive issue is re-checked, not assumed" + + +def test_reactive_issue_clears_once_the_probe_succeeds() -> None: + ledger = mac.PermissionLedger() + ledger.observe(1, STDERR_1002, keystroke=True) + result = {"value": (1, STDERR_1002)} + backend = mac.MacFocusBackend(ledger=ledger, keystroke_probe=lambda: result["value"]) + + assert _ids(backend) == [ACCESSIBILITY] + result["value"] = (0, "") + assert _ids(backend) == [] + + +def test_no_probe_while_nothing_is_held() -> None: + def probe() -> tuple[int, str]: + raise AssertionError("healthy hosts must not run osascript every poll") + + assert _ids(mac.MacFocusBackend(keystroke_probe=probe)) == [] + + +def test_reactive_accessibility_is_not_listed_twice(monkeypatch) -> None: + monkeypatch.setattr(mac, "_ax_trusted", lambda: False) + ledger = mac.PermissionLedger() + ledger.observe(1, STDERR_1002, keystroke=True) + backend = mac.MacFocusBackend(ledger=ledger, keystroke_probe=lambda: (1, STDERR_1002)) + assert _ids(backend) == [ACCESSIBILITY] + + +# --------------------------------------------------------------------------- +# Focus query feeds the ledger +# --------------------------------------------------------------------------- + + +async def test_focus_query_denial_is_recorded(monkeypatch) -> None: + async def denied(*_args: str) -> str: + raise RuntimeError(f"osascript -e ... failed: {STDERR_1743}") + + monkeypatch.setattr(mac, "_run", denied) + ledger = mac.PermissionLedger() + with pytest.raises(RuntimeError): + await mac.MacFocusBackend(ledger=ledger).get_active_app() + assert ledger.denied() == {AUTOMATION} + + +async def test_focus_query_success_clears_automation(monkeypatch) -> None: + async def ok(*_args: str) -> str: + return "Firefox|||New Tab" + + monkeypatch.setattr(mac, "_run", ok) + ledger = mac.PermissionLedger() + ledger.observe(1, STDERR_1743, keystroke=False) + app = await mac.MacFocusBackend(ledger=ledger).get_active_app() + assert app.app_id == "Firefox" + assert ledger.denied() == frozenset() + + +# --------------------------------------------------------------------------- +# Key sink -> PermissionDenied +# --------------------------------------------------------------------------- + + +class _FakePopen: + """Stands in for ``subprocess.Popen`` in ``MacKeySink.emit_key``.""" + + def __init__(self, returncode: int, stderr: str) -> None: + self.returncode = returncode + self._stderr = stderr + + def __call__(self, *_args, **_kwargs) -> "_FakePopen": + return self + + def communicate(self) -> tuple[str, str]: + return "", self._stderr + + +def _sink(ledger: mac.PermissionLedger) -> mac.MacKeySink: + # Skip __init__: it runs real osascript / Quartz probes. + sink = mac.MacKeySink.__new__(mac.MacKeySink) + sink._ledger = ledger + return sink + + +CMD_N = [125, 49] # super+n + + +@pytest.mark.parametrize( + ("stderr", "issue_id", "named"), + [ + (STDERR_1743, AUTOMATION, "System Events"), + (STDERR_1002, ACCESSIBILITY, "Accessibility"), + ], +) +def test_key_sink_raises_permission_denied(monkeypatch, stderr, issue_id, named) -> None: + monkeypatch.setattr(mac.subprocess, "Popen", _FakePopen(1, stderr)) + ledger = mac.PermissionLedger() + + with pytest.raises(PermissionDenied) as info: + _sink(ledger).emit_key(CMD_N) + + assert info.value.issue_id == issue_id + assert info.value.message.startswith("Key press blocked:") + assert "deckd.app" in info.value.message + assert named in info.value.message + assert issue_id in ledger.denied() + + +def test_key_sink_unrelated_error_does_not_raise(monkeypatch) -> None: + monkeypatch.setattr( + mac.subprocess, "Popen", _FakePopen(1, "0:1: execution error: boom (-1719)") + ) + ledger = mac.PermissionLedger() + _sink(ledger).emit_key(CMD_N) # logged, not raised + assert ledger.denied() == frozenset() + + +def test_key_sink_success_clears_the_ledger(monkeypatch) -> None: + monkeypatch.setattr(mac.subprocess, "Popen", _FakePopen(0, "")) + ledger = mac.PermissionLedger() + ledger.observe(1, STDERR_1002, keystroke=True) + _sink(ledger).emit_key(CMD_N) + assert ledger.denied() == frozenset() + + +def test_startup_probe_feeds_the_ledger(monkeypatch) -> None: + """The keysink's startup probe records a denial, so the banner is up + before the first button press even when the proactive check can't tell.""" + + class _Done: + returncode = 1 + stderr = STDERR_1743 + + monkeypatch.setattr(mac.subprocess, "run", lambda *a, **k: _Done()) + ledger = mac.PermissionLedger() + _sink(ledger)._check_system_events() + assert ledger.denied() == {AUTOMATION}