Files
gabrielvidalandClaude Opus 5.5 83d1827119 feat(plugins): keyboard shortcuts leave the core for the keyboard-shortcuts plugin — app.keymap, optionalRequires, commands() / keyChord bridges
Which keys run which command is now a live plugin's (`keyboard-shortcuts`,
ai-agent-plugins): the defaults, each person's own bindings, the on/off
switch, Settings → Keyboard (a nav "settings" page) and the cheat sheet (an
app.modal slot). The core keeps what a sandboxed frame can't do: the one
keydown listener, the commands and their handlers. No plugin, no shortcuts.

- provides `app.keymap` → GET /api/plugins/keymap (plugins/keymap.py):
  the provider run as the caller, sanitized, cached; dropped on any plugin
  change and after a write of the provider (SSE `keymap` to that user).
- commands: the app's (lib/keyboard/actions.ts, no defaults any more) plus
  `composer.shortcut:<chip id>` (a named guideline chip) and
  `modal:<pluginId>:<slotId>` (a plugin's modal — the cheat sheet).
- `optionalRequires`: optional peers — no install/enable checks, their
  exports and plugin events open while they are on; the info page's
  "Works with" row. prompt-shortcuts is the keyboard plugin's.
- frame bridges `commands()` and `keyChord()`; a frame's unused keys go on
  to the app's key layer while it has the focus (g h on a plugin page).
- carryover.keyboard: each person's state.keyboard → the plugin's
  keymap.json, once.
- the core Keyboard page, CheatSheet and settings.keyboard are gone;
  /settings/keyboard redirects to the plugin's page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:58:38 +01:00

179 lines
6.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""The caller's keyboard shortcuts, from the live plugin that provides them
(``provides: {"app.keymap": "<action>"}`` — the ``keyboard-shortcuts``
plugin since 2026-11-27).
The app keeps the key layer itself (the one keydown listener, the commands and
their handlers: ``frontend/src/lib/keyboard/``); which keys run which command
— the defaults, the person's own bindings, the master switch — is the
plugin's. ``GET /api/plugins/keymap`` runs the first active provider's action
**as the caller** (a guest: the owner's ``managed`` install granted to them)
on ``{"trigger": "app.keymap"}`` and serves its answer, sanitized::
{"enabled": bool, "pluginId": str,
"bindings": [{"command": "palette", "keys": ["mod+k"]}, …]}
A ``command`` is an app command id (``go.home``, ``composer.chip.3``,
``composer.shortcut:<chip id>``…) or ``modal:<pluginId>:<slotId>`` (open a
plugin's ``app.modal`` slot — the cheat sheet, the command palette); the app
skips the ones it doesn't know. ``keys`` are bindings in
``lib/keyboard/keys.ts``'s spelling: one chord or two, space-separated.
No provider: ``{"enabled": false, "bindings": []}`` — no shortcuts at all
(the composers keep their own ⌘↵, ↑, Ctrl+R and Esc).
Cached per caller + plugin fingerprint (stale-while-revalidate, like the
composer's plugin chips); dropped on every plugin change (a peer turning on
changes the answer) and after any non-read action of the provider
(:func:`touched` — the plugin's page saved a binding), which also tells the
caller's tabs to refetch (SSE ``{"type": "keymap"}``).
"""
from __future__ import annotations
import logging
import re
from typing import Any
from plugins.store import OWNER_UID
from plugins.swr import SWRCache
log = logging.getLogger(__name__)
PROVIDES = "app.keymap"
TTL_SECS = 300.0
MAX_STALE_SECS = 86400.0
MAX_BINDINGS = 400
MAX_KEYS = 4
_cache = SWRCache(TTL_SECS, MAX_STALE_SECS, name="keymap")
# An app command id, or ``modal:<pluginId>:<slotId>``.
_COMMAND_RE = re.compile(r"^[a-z][a-zA-Z0-9._:-]{0,119}$")
_MODS = ("mod", "ctrl", "alt", "shift")
# A chord's key: one printable character, a named key or F1–F24.
_NAMED_KEYS = frozenset({
"space", "escape", "enter", "tab", "backspace", "delete", "arrowup", "arrowdown",
"arrowleft", "arrowright", "home", "end", "pageup", "pagedown",
})
_F_KEY_RE = re.compile(r"^f([1-9]|1\d|2[0-4])$")
EMPTY: dict[str, Any] = {"enabled": False, "bindings": [], "pluginId": None}
def invalidate(uid: str | None = None) -> None:
"""Drop cached keymaps (everyone's, or one user's)."""
if uid is None:
_cache.clear()
else:
prefix = f"{uid}:"
_cache.drop(lambda k: k.startswith(prefix))
def _chord_ok(chord: str) -> bool:
rest = chord
seen: list[str] = []
while True:
i = rest.find("+")
if i <= 0:
break
head = rest[:i]
if head not in _MODS:
break
seen.append(head)
rest = rest[i + 1:]
# canonical order, no repeats
if seen != [m for m in _MODS if m in seen]:
return False
if len(rest) == 1:
return rest.isprintable() and not rest.isspace() and not rest.isupper()
return rest in _NAMED_KEYS or bool(_F_KEY_RE.match(rest))
def clean_binding(raw: Any) -> str | None:
"""A binding in canonical spelling, or None when it isn't one."""
if not isinstance(raw, str):
return None
chords = raw.strip().split()
if not 1 <= len(chords) <= 2 or len(raw) > 64:
return None
if not all(_chord_ok(c) for c in chords):
return None
return " ".join(chords)
def clean_keymap(pid: str, raw: Any) -> dict[str, Any]:
if not isinstance(raw, dict):
return {**EMPTY, "pluginId": pid}
out: list[dict[str, Any]] = []
seen: set[str] = set()
items = raw.get("bindings") if isinstance(raw.get("bindings"), list) else []
for b in items[:MAX_BINDINGS]:
if not isinstance(b, dict):
continue
cmd = str(b.get("command") or "").strip()
if not _COMMAND_RE.match(cmd) or cmd in seen:
continue
keys: list[str] = []
for k in (b.get("keys") if isinstance(b.get("keys"), list) else [])[:MAX_KEYS]:
c = clean_binding(k)
if c and c not in keys:
keys.append(c)
if not keys:
continue
seen.add(cmd)
out.append({"command": cmd, "keys": keys})
return {"enabled": bool(raw.get("enabled", True)), "bindings": out, "pluginId": pid}
def _provider(deps, uid: str) -> tuple[dict[str, Any], dict[str, Any] | None] | None:
from plugins.waiting import _providers_for
try:
found = _providers_for(deps, uid, PROVIDES)
except Exception: # noqa: BLE001 — no plugin store (tests, early boot)
return None
return found[0] if found else None
def _run(deps, uid: str, rec: dict[str, Any], grant: dict[str, Any] | None) -> dict[str, Any]:
from plugins.runner import run_script
mf = rec["manifest"]
act = mf["actions"][mf["provides"][PROVIDES]]
try:
raw = run_script(
deps, deps.plugin_store, uid, rec, act["script"],
payload={"trigger": PROVIDES},
timeout_sec=min(15, int(act.get("timeoutSec") or 15)),
grant=grant,
)
except Exception as e: # noqa: BLE001 — a broken plugin means no keys, not a 500
log.warning("app.keymap plugin %s failed: %s", rec.get("id"), e)
return {**EMPTY, "pluginId": rec.get("id")}
return clean_keymap(rec["id"], raw)
def keymap_for(deps, caller) -> dict[str, Any]:
"""The keymap active for ``caller`` (``EMPTY`` without a provider)."""
uid = OWNER_UID if caller.is_owner else caller.id
found = _provider(deps, uid)
if not found:
return dict(EMPTY)
rec, grant = found
key = f"{uid}:{rec['id']}@{rec.get('fingerprint') or ''}"
return _cache.get(key, lambda: _run(deps, uid, rec, grant))
def provides_keymap(rec: dict[str, Any] | None) -> bool:
return bool(rec and PROVIDES in ((rec.get("manifest") or {}).get("provides") or {}))
def touched(deps, rec: dict[str, Any] | None, uid: str) -> None:
"""The plugin ``rec`` just ran a non-read action for ``uid``: when it
provides the keymap, drop that user's and tell their tabs to refetch."""
if not provides_keymap(rec):
return
invalidate(uid)
try:
deps.hub.publish({"type": "keymap", "uid": uid})
except Exception: # noqa: BLE001 — no hub (tests)
pass