254 lines
14 KiB
Python
254 lines
14 KiB
Python
#!/usr/bin/env python3
|
||
"""Unit tests for the Command palette live plugin: the manifest (and the hub's
|
||
validator when a backend checkout that knows ``preload`` and ``seed`` is
|
||
around), the document (self-contained, current with ``ui-src``, its scripts
|
||
parse), and ``common.js`` under node — the fuzzy scorer (close to the core's
|
||
old Fuse.js setup) and the list (what the core's CommandPalette listed).
|
||
|
||
python3 -m pytest plugins/command-palette/tests/
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import pathlib
|
||
import re
|
||
import shutil
|
||
import subprocess
|
||
import sys
|
||
import tempfile
|
||
import unittest
|
||
|
||
sys.dont_write_bytecode = True
|
||
PLUGIN = pathlib.Path(__file__).resolve().parent.parent
|
||
COMMON = PLUGIN / "ui-src" / "common.js"
|
||
|
||
# What the app's bridges answer (business/keyboard/commands.ts, appIndex.ts).
|
||
CMDS = {"commands": [
|
||
{"id": "sidebar", "group": "general", "label": "Show or hide the sidebar", "available": True, "keys": ["mod+b"]},
|
||
{"id": "search", "group": "general", "label": "Search conversations", "available": True, "keys": ["/"]},
|
||
{"id": "settings.search", "group": "general", "label": "Search settings", "context": "settings",
|
||
"available": False, "keys": ["/"]},
|
||
{"id": "conv.new", "group": "conversations", "label": "New conversation", "available": True,
|
||
"keys": ["c", "mod+shift+o"]},
|
||
{"id": "conv.reply", "group": "conversations", "label": "Reply in this conversation", "available": False, "keys": ["r"]},
|
||
{"id": "composer.guidelines", "group": "composer", "label": "Guidelines on / off", "available": True, "keys": []},
|
||
{"id": "composer.chip.1", "group": "composer", "label": "Guideline chip 1 on / off", "context": "composer",
|
||
"available": True, "keys": ["alt+1"]},
|
||
{"id": "go.home", "group": "go", "label": "Home", "available": True, "keys": ["g h"]},
|
||
{"id": "profile.cycle", "group": "profiles", "label": "Next profile", "owner": True, "available": True, "keys": ["p"]},
|
||
{"id": "profile.1", "group": "profiles", "label": "Switch to Personal", "owner": True, "current": True,
|
||
"available": True, "keys": ["alt+1"]},
|
||
{"id": "profile.2", "group": "profiles", "label": "Switch to Work", "owner": True, "available": True, "keys": ["alt+2"]},
|
||
# the plugin modals the keymap binds: the cheat sheet is listed, the palette itself isn't
|
||
{"id": "modal:keyboard-shortcuts:cheatsheet", "group": "general", "label": "Keyboard shortcuts",
|
||
"available": True, "keys": ["?"]},
|
||
{"id": "modal:command-palette:palette", "group": "general", "label": "Command palette",
|
||
"available": True, "keys": ["mod+k"]},
|
||
], "groups": [], "fixed": [], "mac": True}
|
||
PLACES = [
|
||
{"to": "/", "label": "Home"},
|
||
{"to": "/settings/display", "label": "Display", "hint": "Settings › You", "keywords": ["theme", "dark mode"]},
|
||
{"to": "/settings/display#tz", "label": "Timezone", "hint": "Settings › Display"},
|
||
{"to": "/settings/roles", "label": "Roles", "hint": "Settings › People & security"},
|
||
{"to": "/settings/display", "label": "Display", "hint": "dup"},
|
||
]
|
||
CONVS = [{"id": f"c{i}", "title": f"Conversation {i}", "hint": "running · ai-agent" if i == 0 else ""}
|
||
for i in range(10)]
|
||
|
||
|
||
class TestManifest(unittest.TestCase):
|
||
def test_shape(self):
|
||
mf = json.loads((PLUGIN / "plugin.json").read_text())
|
||
self.assertEqual(mf["id"], "command-palette")
|
||
self.assertIs(mf["seed"], True)
|
||
self.assertIs(mf["managed"]["defaultForGuests"], True)
|
||
self.assertNotIn("actions", mf)
|
||
(slot,) = mf["ui"]["slots"]
|
||
self.assertEqual((slot["id"], slot["where"], slot["preload"]), ("palette", "app.modal", True))
|
||
self.assertTrue((PLUGIN / slot["html"]).is_file())
|
||
for f in ("icon.svg", "README.md"):
|
||
self.assertTrue((PLUGIN / f).is_file(), f)
|
||
# the keyboard plugin opens it through this command
|
||
kb = json.loads((PLUGIN.parent / "keyboard-shortcuts" / "plugin.json").read_text())
|
||
self.assertIn("command-palette", kb["optionalRequires"])
|
||
|
||
def test_the_hub_accepts_it(self):
|
||
core = pathlib.Path(os.environ.get("AI_AGENT_BACKEND",
|
||
pathlib.Path.home() / "projects/ai-agent/backend"))
|
||
if not (core / "plugins" / "manifest.py").is_file():
|
||
self.skipTest("no backend checkout")
|
||
try:
|
||
import fastapi # noqa: F401
|
||
except ImportError:
|
||
self.skipTest("the backend's deps aren't installed here")
|
||
sys.path.insert(0, str(core))
|
||
try:
|
||
from plugins import manifest
|
||
src = (core / "plugins" / "manifest.py").read_text()
|
||
if "seed" not in manifest._TOP_KEYS or '"preload"' not in src:
|
||
self.skipTest("that backend predates seed / preload")
|
||
mf = manifest.validate_manifest(PLUGIN)
|
||
finally:
|
||
sys.path.remove(str(core))
|
||
self.assertTrue(mf["ui"]["slots"][0]["preload"])
|
||
|
||
|
||
class TestUi(unittest.TestCase):
|
||
def node(self):
|
||
node = shutil.which("node")
|
||
if not node:
|
||
self.skipTest("no node")
|
||
return node
|
||
|
||
def run_js(self, body: str):
|
||
script = ("var window={aiAgentPlugin:null};var navigator={platform:'MacIntel',userAgent:''};\n"
|
||
+ COMMON.read_text() + "\n" + body)
|
||
p = subprocess.run([self.node(), "-e", script], capture_output=True, text=True, timeout=30)
|
||
self.assertEqual(p.returncode, 0, p.stderr)
|
||
return json.loads(p.stdout)
|
||
|
||
def test_scripts_parse(self):
|
||
node = self.node()
|
||
for f in sorted((PLUGIN / "ui").glob("*.html")):
|
||
html = f.read_text()
|
||
self.assertNotRegex(html, r"<script[^>]+src=", f.name)
|
||
self.assertNotRegex(html, r"<link[^>]+href=\"?https?:", f.name)
|
||
self.assertNotIn("/*@COMMON_", html, f.name)
|
||
for i, js in enumerate(re.findall(r"<script[^>]*>(.*?)</script>", html, re.S)):
|
||
with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as tf:
|
||
tf.write(js)
|
||
try:
|
||
p = subprocess.run([node, "--check", tf.name], capture_output=True)
|
||
finally:
|
||
os.unlink(tf.name)
|
||
self.assertEqual(p.returncode, 0, f"{f.name} script {i}: {p.stderr.decode()[:400]}")
|
||
|
||
def test_built_documents_are_current(self):
|
||
with tempfile.TemporaryDirectory() as td:
|
||
subprocess.run([sys.executable, str(PLUGIN / "ui-src" / "build.py"), str(PLUGIN / "ui-src"), td], check=True)
|
||
for f in pathlib.Path(td).glob("*.html"):
|
||
self.assertEqual(f.read_text(), (PLUGIN / "ui" / f.name).read_text(),
|
||
f"ui/{f.name} is stale: python3 ui-src/build.py ui-src ui")
|
||
|
||
def test_field_score(self):
|
||
out = self.run_js(
|
||
"console.log(JSON.stringify(["
|
||
"fieldScore('time','timezone'),fieldScore('tmezone','timezone'),fieldScore('qqqq','timezone'),"
|
||
"fieldScore('',''),fieldScore('a',''),fold('Paramètres Écran')]))")
|
||
self.assertEqual(out[0], 0) # in there as is
|
||
self.assertAlmostEqual(out[1], 1 / 7) # one edit in 7
|
||
self.assertEqual(out[2], 1)
|
||
self.assertEqual((out[3], out[4]), (0, 1))
|
||
self.assertEqual(out[5], "parametres ecran")
|
||
|
||
def test_search(self):
|
||
items = [
|
||
{"label": "Show or hide the sidebar"},
|
||
{"label": "Timezone", "hint": "Settings › Display"},
|
||
{"label": "Display", "hint": "Settings › You", "keywords": ["theme", "dark mode"]},
|
||
{"label": "Paramètres", "hint": ""},
|
||
{"label": "Something", "hint": "about the timezone of a very long hint line"},
|
||
{"label": "Roles", "hint": "Settings › People & security"},
|
||
]
|
||
out = self.run_js(
|
||
f"var I={json.dumps(items)};var L=function(q){{return search(I,q).map(function(i){{return i.label}})}};"
|
||
"console.log(JSON.stringify({time:L('time'),typo:L('sidbar'),accent:L('parametres'),"
|
||
"kw:L('dark'),none:L('qqqqq'),blank:L(' ').length,"
|
||
"cap:search(Array.from({length:60},function(_,i){return {label:'Item '+i}}),'item').length}))")
|
||
# the label match beats a hint match in a long line
|
||
self.assertEqual(out["time"], ["Timezone", "Something"])
|
||
self.assertEqual(out["typo"], ["Show or hide the sidebar"])
|
||
self.assertEqual(out["accent"], ["Paramètres"])
|
||
self.assertEqual(out["kw"], ["Display"]) # through its keywords
|
||
self.assertEqual(out["none"], [])
|
||
self.assertEqual(out["blank"], len(items))
|
||
self.assertEqual(out["cap"], 40)
|
||
|
||
def test_the_list(self):
|
||
out = self.run_js(
|
||
f"var items=buildItems({json.dumps(CMDS)},{json.dumps(PLACES)},{json.dumps(CONVS)});"
|
||
"console.log(JSON.stringify({items:items.map(function(i){return [i.kind,i.label,i.binding||'',i.run]}),"
|
||
"empty:shown(items,'').map(function(i){return i.key}),"
|
||
"q:shown(items,'work').map(function(i){return i.key}),"
|
||
"caps:capsHtml('g h')}));")
|
||
actions = [[k, label, b] for k, label, b, _ in out["items"] if k == "action"]
|
||
self.assertEqual(actions, [
|
||
["action", "Show or hide the sidebar", "mod+b"],
|
||
["action", "Search conversations", "/"],
|
||
["action", "New conversation", "c"],
|
||
["action", "Guidelines on / off", ""],
|
||
["action", "Home", "g h"],
|
||
["action", "Switch to Work", "alt+2"], # not the profile on screen, not Next profile
|
||
["action", "Keyboard shortcuts", "?"], # the cheat sheet, not the palette itself
|
||
])
|
||
runs = {label: run for k, label, _, run in out["items"]}
|
||
self.assertEqual(runs["Keyboard shortcuts"], {"command": "modal:keyboard-shortcuts:cheatsheet"})
|
||
self.assertEqual(runs["New conversation"], {"command": "conv.new"})
|
||
self.assertEqual(runs["Conversation 3"], {"to": "/conversation/c3"})
|
||
self.assertEqual(runs["Roles"], {"to": "/settings/roles"})
|
||
pages = [label for k, label, _, _ in out["items"] if k == "page"]
|
||
self.assertEqual(pages.count("Display"), 1) # same address and label: once
|
||
self.assertIn("Timezone", pages)
|
||
# no query: the 8 newest conversations, then the actions
|
||
self.assertEqual(out["empty"][:8], [f"c:c{i}" for i in range(8)])
|
||
self.assertTrue(all(k.startswith("a:") for k in out["empty"][8:]))
|
||
self.assertEqual(len(out["empty"]), 8 + 7)
|
||
self.assertEqual(out["q"][0], "a:profile.2")
|
||
self.assertIn("<kbd>G</kbd>", out["caps"])
|
||
|
||
def test_plugins(self):
|
||
# each active plugin's page (places with `plugin`, its glyph) and the
|
||
# plugins this person may turn off / on (pluginSwitches)
|
||
glyph = "data:image/svg+xml;base64,PHN2Zy8+"
|
||
places = PLACES + [
|
||
{"to": "/settings/plugin/nanobanana", "label": "Nano Banana", "hint": "Settings › Plugins",
|
||
"keywords": ["nanobanana"], "plugin": "nanobanana", "icon": glyph},
|
||
{"to": "/settings/plugin/pets", "label": "Pets", "hint": "Settings › Plugins",
|
||
"plugin": "pets", "icon": "javascript:alert(1)"},
|
||
]
|
||
switches = [{"id": "nanobanana", "name": "Nano Banana", "on": True},
|
||
{"id": "sleepy", "name": "Sleepy", "on": False}, {"id": "bad"}]
|
||
out = self.run_js(
|
||
f"var items=buildItems({json.dumps(CMDS)},{json.dumps(places)},{json.dumps(CONVS)},{json.dumps(switches)});"
|
||
"console.log(JSON.stringify({items:items.filter(function(i){return i.kind==='plugin'||i.kind==='switch'}),"
|
||
"empty:shown(items,'').map(function(i){return i.kind}),"
|
||
"nano:shown(items,'nano').map(function(i){return i.key}),"
|
||
"old:buildItems({},[],[]).length}));")
|
||
by = {i["key"]: i for i in out["items"]}
|
||
nano = by["p:/settings/plugin/nanobanana\u0000Nano Banana"]
|
||
self.assertEqual((nano["kind"], nano["icon"], nano["run"]), ("plugin", glyph, {"to": "/settings/plugin/nanobanana"}))
|
||
self.assertNotIn("icon", by["p:/settings/plugin/pets\u0000Pets"]) # only a base64 SVG URI
|
||
self.assertEqual((by["s:nanobanana"]["label"], by["s:nanobanana"]["run"]),
|
||
("Turn Nano Banana off", {"plugin": "nanobanana", "on": False}))
|
||
self.assertEqual((by["s:sleepy"]["label"], by["s:sleepy"]["run"]),
|
||
("Turn Sleepy on", {"plugin": "sleepy", "on": True}))
|
||
self.assertNotIn("s:bad", by)
|
||
# never in the empty list; typed, the plugin's page comes first
|
||
self.assertEqual(set(out["empty"]), {"conversation", "action"})
|
||
self.assertEqual(out["nano"][:2], ["p:/settings/plugin/nanobanana\u0000Nano Banana", "s:nanobanana"])
|
||
self.assertEqual(out["old"], 0)
|
||
|
||
def test_switch_labels_in_french(self):
|
||
script = ("var window={aiAgentPlugin:{init:{lang:'fr'}}};var navigator={platform:'Linux',userAgent:''};\n"
|
||
+ COMMON.read_text() + "\nconsole.log(JSON.stringify(buildItems({},[],[],"
|
||
"[{id:'pets',name:'Pets',on:true},{id:'x',name:'X',on:false}]).map(function(i){return i.label})))")
|
||
p = subprocess.run([self.node(), "-e", script], capture_output=True, text=True, timeout=30)
|
||
self.assertEqual(p.returncode, 0, p.stderr)
|
||
self.assertEqual(json.loads(p.stdout), ["Désactiver Pets", "Activer X"])
|
||
|
||
def test_french(self):
|
||
script = ("var window={aiAgentPlugin:{init:{lang:'fr'}}};var navigator={platform:'Linux',userAgent:''};\n"
|
||
+ COMMON.read_text()
|
||
+ "\nconsole.log(JSON.stringify([tr('No matches.'),tr('Run an action, open a page or a conversation…'),"
|
||
"chordCaps('mod+k'),tr('then')]));")
|
||
p = subprocess.run([self.node(), "-e", script], capture_output=True, text=True, timeout=30)
|
||
self.assertEqual(p.returncode, 0, p.stderr)
|
||
self.assertEqual(json.loads(p.stdout),
|
||
["Aucun résultat.", "Lance une action, ouvre une page ou une conversation…", ["Ctrl", "K"], "puis"])
|
||
|
||
|
||
if __name__ == "__main__":
|
||
unittest.main()
|