Files
ai-agent/backend/test_plugin_keymap.py
gabrielvidalandClaude Opus 5.5 8bb8ac20f7 feat(plugins): the command palette leaves the core for the command-palette plugin — preload modals, runCommand / places / conversations bridges
⌘K's palette is now a live plugin's (`command-palette`, ai-agent-plugins),
the keyboard-shortcuts plugin's second optional peer (⌘K is bound only while
it is on). The core keeps the data it lists and the commands it runs:

- `ui.slots[].preload` (app.modal only): the frame loads hidden once the app
  is idle and stays loaded, so it opens at once (PluginWarmModals — its own
  fixed layer, as an iframe can't move without reloading); each opening is
  an update {open, seq, init}.
- frame bridges: commands() rows gain `available`, `keys`, `current`;
  runCommand(id) runs an available command (closing the modal first);
  places() — sections, Settings pages and rows, plugin pages, Add machine;
  conversations() — the loaded list in the profile on screen.
- over a plugin modal, its own command still acts (⌘K closes the palette).
- the core CommandPalette, KeyCaps, lazy chunk, `palette` command and the
  data-kb-layer logic are gone.

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

314 lines
16 KiB
Python

"""The keyboard shortcuts' platform points (2026-11-27, the keyboard-shortcuts
plugin):
* ``optionalRequires`` — optional peers: validated, never checked at install /
enable / disable / uninstall, in the fingerprint only when set, and they open
the peer's exports and plugin events like ``requires``;
* ``provides: {"app.keymap": …}`` — ``GET /api/plugins/keymap``, sanitized,
cached, dropped after a write of the provider;
* ``carryover.keyboard`` — each person's ``state.keyboard`` → the plugin's
per-user ``keymap.json``.
"""
from __future__ import annotations
import json
import os
import pathlib
import sys
import tempfile
import unittest
BACKEND = pathlib.Path(__file__).resolve().parent
if str(BACKEND) not in sys.path:
sys.path.insert(0, str(BACKEND))
_TMP = tempfile.TemporaryDirectory()
_DATA = pathlib.Path(_TMP.name)
os.environ.setdefault("DB_PATH", str(_DATA / "ai-agent.db"))
os.environ.setdefault("TRANSCRIPTS_DIR", str(_DATA / "transcripts"))
os.environ.setdefault("WORKSPACE", str(_DATA / "workspace"))
os.environ.setdefault("REPO_DIR", str(_DATA / "workspace"))
os.environ.setdefault("PLUGINS_DIR", str(_DATA / "plugins"))
os.environ.setdefault("UI_STATE_PATH", str(_DATA / "ui-state.json"))
os.environ.setdefault("USERS_PATH", str(_DATA / "users.json"))
os.environ.setdefault("AUTH_PATH", str(_DATA / "auth.json"))
os.environ.setdefault("TOOLS_TOKEN_KEY", str(_DATA / "tools.key"))
os.environ.setdefault("INTERNAL_API_TOKEN", "tok")
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
from plugins import carryover # noqa: E402
from plugins import keymap as plugin_keymap # noqa: E402
from plugins.manifest import ManifestError, capability_fingerprint, validate_manifest # noqa: E402
from plugins.store import OWNER_UID, PluginStore # noqa: E402
from toolproxy import access # noqa: E402
OWNER_H = {"X-Internal-Auth": os.environ.get("INTERNAL_API_TOKEN", "")}
def _write_plugin(root: pathlib.Path, mf: dict, files: dict[str, str] | None = None) -> pathlib.Path:
root.mkdir(parents=True, exist_ok=True)
(root / "plugin.json").write_text(json.dumps(mf, indent=2), encoding="utf-8")
for rel, content in (files or {}).items():
p = root / rel
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(content, encoding="utf-8")
return root
# A provider whose keymap is in its data dir (keymap.json, else a default),
# and a save that writes it — enough to see the cache and its drop.
KEYMAP_PY = """import json, os, pathlib, sys
d = pathlib.Path(os.environ['AIA_PLUGIN_DATA_DIR'])
f = d / 'keymap.json'
km = json.loads(f.read_text()) if f.exists() else {'enabled': True, 'bindings': [{'command': 'go.home', 'keys': ['g h']}]}
active = json.loads(os.environ.get('AIA_ACTIVE_PLUGINS') or '[]')
if 'peer' in active:
km['bindings'].append({'command': 'composer.shortcut:changes', 'keys': ['alt+c']})
print(json.dumps(km))
"""
SAVE_PY = """import json, os, pathlib, sys
p = json.load(sys.stdin)
(pathlib.Path(os.environ['AIA_PLUGIN_DATA_DIR']) / 'keymap.json').write_text(json.dumps(p['keymap']))
print('{"ok": true}')
"""
class OptionalRequiresManifestTest(unittest.TestCase):
def test_validates_and_fingerprints_only_when_set(self):
with tempfile.TemporaryDirectory() as td:
d = pathlib.Path(td)
_write_plugin(d / "plain", {"schema": 1, "id": "plain", "name": "Plain"})
plain = validate_manifest(d / "plain")
self.assertNotIn("optionalRequires", plain)
_write_plugin(d / "kb", {
"schema": 1, "id": "kb", "name": "Kb",
"optionalRequires": ["prompt-shortcuts", "prompt-shortcuts"],
"actions": {"on": {"script": "h.py"}},
# an optional peer's plugin events may be heard
"events": [{"id": "e", "on": ["plugin:prompt-shortcuts:changed"], "action": "on"}],
}, {"h.py": "print('{}')\n"})
mf = validate_manifest(d / "kb")
self.assertEqual(mf["optionalRequires"], ["prompt-shortcuts"])
self.assertNotEqual(capability_fingerprint(mf),
capability_fingerprint({k: v for k, v in mf.items() if k != "optionalRequires"}))
for bad in (["kb2"], ["Bad Id"], "prompt-shortcuts"):
_write_plugin(d / "kb2", {"schema": 1, "id": "kb2", "name": "Kb2", "optionalRequires": bad})
with self.assertRaises(ManifestError, msg=repr(bad)):
validate_manifest(d / "kb2")
_write_plugin(d / "kb3", {"schema": 1, "id": "kb3", "name": "Kb3",
"requires": ["ask-form"], "optionalRequires": ["ask-form"]})
with self.assertRaises(ManifestError):
validate_manifest(d / "kb3")
def test_app_keymap_is_a_known_provides_key(self):
with tempfile.TemporaryDirectory() as td:
d = pathlib.Path(td)
_write_plugin(d / "kb", {
"schema": 1, "id": "kb", "name": "Kb",
"provides": {"app.keymap": "keymap"},
"actions": {"keymap": {"script": "k.py", "readOnly": True}},
}, {"k.py": KEYMAP_PY})
self.assertEqual(validate_manifest(d / "kb")["provides"], {"app.keymap": "keymap"})
class PreloadSlotTest(unittest.TestCase):
def test_only_app_modal_slots_preload(self):
with tempfile.TemporaryDirectory() as td:
d = pathlib.Path(td)
_write_plugin(d / "pal", {
"schema": 1, "id": "pal", "name": "Pal",
"ui": {"slots": [{"id": "palette", "where": "app.modal", "html": "ui/p.html", "preload": True},
{"id": "other", "where": "app.modal", "html": "ui/p.html", "preload": False}]},
}, {"ui/p.html": "<p>x</p>"})
slots = validate_manifest(d / "pal")["ui"]["slots"]
self.assertTrue(slots[0]["preload"])
self.assertNotIn("preload", slots[1]) # only written when set
for bad in ({"where": "home.section", "preload": True}, {"where": "app.modal", "preload": "yes"}):
_write_plugin(d / "bad", {"schema": 1, "id": "bad", "name": "Bad",
"ui": {"slots": [{"id": "s", "html": "ui/p.html", **bad}]}},
{"ui/p.html": "<p>x</p>"})
with self.assertRaises(ManifestError, msg=repr(bad)):
validate_manifest(d / "bad")
class CleanKeymapTest(unittest.TestCase):
def test_bindings(self):
ok = ["mod+k", "?", "g h", "alt+]", "mod+shift+o", "alt+1", "f5", "ctrl+alt+arrowup", "/"]
for b in ok:
self.assertEqual(plugin_keymap.clean_binding(b), b, b)
self.assertEqual(plugin_keymap.clean_binding(" g h "), "g h")
for b in ["", "shift+mod+k", "mod+mod+k", "a b c", "K", "hyper+k", "f25", "enterr", 3, None]:
self.assertIsNone(plugin_keymap.clean_binding(b), repr(b))
def test_keymap(self):
raw = {"enabled": True, "bindings": [
{"command": "go.home", "keys": ["g h", "g h", "bad key here"]},
{"command": "go.home", "keys": ["x"]}, # a second go.home: dropped
{"command": "modal:keyboard-shortcuts:cheatsheet", "keys": ["?"]},
{"command": "composer.shortcut:changes", "keys": ["alt+c"]},
{"command": "Not A Command", "keys": ["y"]},
{"command": "list.next", "keys": []}, # no keys: dropped
"junk",
]}
out = plugin_keymap.clean_keymap("kb", raw)
self.assertEqual(out, {"enabled": True, "pluginId": "kb", "bindings": [
{"command": "go.home", "keys": ["g h"]},
{"command": "modal:keyboard-shortcuts:cheatsheet", "keys": ["?"]},
{"command": "composer.shortcut:changes", "keys": ["alt+c"]},
]})
self.assertEqual(plugin_keymap.clean_keymap("kb", "nope")["bindings"], [])
self.assertFalse(plugin_keymap.clean_keymap("kb", {"enabled": False, "bindings": []})["enabled"])
class KeymapRouteTest(unittest.TestCase):
def setUp(self):
self.td = tempfile.TemporaryDirectory()
self.root = pathlib.Path(self.td.name)
self.deps = main.app.state.ai
self.orig_store = self.deps.plugin_store
self.store = PluginStore(self.root / "plugins-data")
self.deps.plugin_store = self.store
plugin_keymap.invalidate()
self.client = TestClient(main.app)
def tearDown(self):
self.deps.plugin_store = self.orig_store
plugin_keymap.invalidate()
self.td.cleanup()
def _kb(self):
return _write_plugin(self.root / "kb", {
"schema": 1, "id": "kb", "name": "Kb",
"optionalRequires": ["peer"],
"provides": {"app.keymap": "keymap"},
"actions": {"keymap": {"script": "keymap.py", "readOnly": True},
"save": {"script": "save.py"},
"call_peer": {"script": "call.py"}},
}, {"keymap.py": KEYMAP_PY, "save.py": SAVE_PY, "call.py": "print('{}')\n"})
def _peer(self):
return _write_plugin(self.root / "peer", {
"schema": 1, "id": "peer", "name": "Peer",
"actions": {"shortcuts": {"script": "s.py", "readOnly": True}, "hidden": {"script": "s.py"}},
"exports": ["shortcuts"],
}, {"s.py": "import json; print(json.dumps({'shortcuts': [{'id': 'changes', 'label': 'Changes'}]}))\n"})
def test_no_provider_no_keys(self):
r = self.client.get("/api/plugins/keymap", headers=OWNER_H)
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(r.json(), {"enabled": False, "bindings": [], "pluginId": None})
def test_serves_caches_and_drops_after_a_write(self):
self.store.install(OWNER_UID, str(self._kb()), is_owner=True, approve=True)
r = self.client.get("/api/plugins/keymap", headers=OWNER_H)
self.assertEqual(r.json()["bindings"], [{"command": "go.home", "keys": ["g h"]}])
self.assertEqual(r.json()["pluginId"], "kb")
# A write behind the hub's back: the cached answer stays …
data = self.store.user_data_dir(OWNER_UID, "kb") / "keymap.json"
data.write_text(json.dumps({"enabled": True, "bindings": [{"command": "go.files", "keys": ["g f"]}]}))
self.assertEqual(self.client.get("/api/plugins/keymap", headers=OWNER_H).json()["bindings"][0]["command"],
"go.home")
# … the plugin's own (non-read) action drops it.
km = {"enabled": True, "bindings": [{"command": "sidebar", "keys": ["mod+b"]}]}
r = self.client.post("/api/plugins/kb/actions/save", json={"keymap": km}, headers=OWNER_H)
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(self.client.get("/api/plugins/keymap", headers=OWNER_H).json()["bindings"],
[{"command": "sidebar", "keys": ["mod+b"]}])
def test_optional_peer_never_blocks_and_opens_its_exports(self):
kb = self._kb()
# installs without the peer (requires would refuse)
self.store.install(OWNER_UID, str(kb), is_owner=True, approve=True)
tok = access.mint_handler(OWNER_UID, "kb", ttl=300)
auth = {"Authorization": f"Bearer {tok}"}
# the peer missing: the call fails, nothing else does
r = self.client.post("/proxy/tools/plugins/peer/actions/shortcuts", json={}, headers=auth)
self.assertGreaterEqual(r.status_code, 400)
self.store.install(OWNER_UID, str(self._peer()), is_owner=True, approve=True)
plugin_keymap.invalidate()
r = self.client.post("/proxy/tools/plugins/peer/actions/shortcuts", json={}, headers=auth)
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(r.json()["shortcuts"][0]["id"], "changes")
# an action the peer doesn't export stays closed
r = self.client.post("/proxy/tools/plugins/peer/actions/hidden", json={}, headers=auth)
self.assertEqual(r.status_code, 403)
# the provider sees the peer in AIA_ACTIVE_PLUGINS
cmds = [b["command"] for b in self.client.get("/api/plugins/keymap", headers=OWNER_H).json()["bindings"]]
self.assertIn("composer.shortcut:changes", cmds)
# the peer can be disabled and uninstalled while kb is on
self.store.update(OWNER_UID, "peer", enabled=False)
self.assertTrue(self.store.uninstall(OWNER_UID, "peer"))
# a plugin change through the API drops the cache: the peer's part is gone
r = self.client.put("/api/plugins/kb", json={"enabled": True}, headers=OWNER_H)
self.assertEqual(r.status_code, 200, r.text)
cmds = [b["command"] for b in self.client.get("/api/plugins/keymap", headers=OWNER_H).json()["bindings"]]
self.assertNotIn("composer.shortcut:changes", cmds)
def test_info_lists_peers_and_which_are_on(self):
self.store.install(OWNER_UID, str(self._kb()), is_owner=True, approve=True)
info = self.client.get("/api/plugins/kb/info", headers=OWNER_H).json()
self.assertEqual(info["optionalRequires"], ["peer"])
self.assertEqual(info["peersActive"], [])
self.store.install(OWNER_UID, str(self._peer()), is_owner=True, approve=True)
self.assertEqual(self.client.get("/api/plugins/kb/info", headers=OWNER_H).json()["peersActive"], ["peer"])
class FakeUiState:
def __init__(self, blobs: dict[str, dict]):
self.d = {k: json.dumps(v) for k, v in blobs.items()}
def get(self, key):
return self.d.get(key)
def set(self, key, value):
self.d[key] = value
class FakeUsers:
def __init__(self, ids):
self.ids = ids
def all(self):
return [{"id": i} for i in self.ids]
class KeyboardCarryOverTest(unittest.TestCase):
def test_each_persons_keyboard_settings_once(self):
with tempfile.TemporaryDirectory() as td:
store = PluginStore(pathlib.Path(td) / "plugins-data")
ui = FakeUiState({
"ai-agent-settings": {"state": {"keyboard": {"enabled": True, "bindings": {"palette": ["mod+p"], "go.home": []}}}},
"u.g1.ai-agent-settings": {"state": {"keyboard": {"enabled": False, "bindings": {}}}},
# the defaults: nothing to carry
"u.g2.ai-agent-settings": {"state": {"keyboard": {"enabled": True, "bindings": {}}}},
"u.g3.ai-agent-settings": {"state": {}},
})
# g4 already has the plugin's own: kept
own = store.user_data_dir("g4", "keyboard-shortcuts") / "keymap.json"
own.write_text('{"enabled": true, "bindings": {"sidebar": ["mod+\\\\"]}}')
ui.d["u.g4.ai-agent-settings"] = json.dumps({"state": {"keyboard": {"enabled": False, "bindings": {}}}})
n = carryover.keyboard(store, ui, FakeUsers(["g1", "g2", "g3", "g4"]))
self.assertEqual(n, 2)
owner = json.loads((store.user_data_dir(OWNER_UID, "keyboard-shortcuts") / "keymap.json").read_text())
self.assertEqual(owner, {"enabled": True, "bindings": {"palette": ["mod+p"], "go.home": []}})
g1 = json.loads((store.user_data_dir("g1", "keyboard-shortcuts") / "keymap.json").read_text())
self.assertEqual(g1, {"enabled": False, "bindings": {}})
self.assertFalse((store.user_data_dir("g2", "keyboard-shortcuts") / "keymap.json").exists())
self.assertIn("sidebar", own.read_text())
# once
(store.user_data_dir(OWNER_UID, "keyboard-shortcuts") / "keymap.json").unlink()
self.assertEqual(carryover.keyboard(store, ui, FakeUsers(["g1"])), 0)
self.assertFalse((store.user_data_dir(OWNER_UID, "keyboard-shortcuts") / "keymap.json").exists())
if __name__ == "__main__":
unittest.main()