Generic platform points for the `diff-viewer` and `commits` plugins (ai-agent-plugins): a `conversation.tab` slot (Thread | Changes N) with setTab/openTab/closeTab/reply bridges; stackable + pullOut tool cards and match.hasReport; `pathShims` (a git PATH shim for every harness) with out-of-band reports (lab: /api/plugin-reports, worker: outbox `report`); `conversations.reports` and `diff.read` hub bridges; ui.pages[].opens for Project/Service "Recent commits". The core commit card, Changes view, diff page and review store are gone; bash_diff.py keeps bashDiff only. Legacy gitCommits / commit-line parsing stays for past transcripts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
281 lines
14 KiB
Python
281 lines
14 KiB
Python
"""Prompt shortcuts leave the core for the prompt-shortcuts plugin (2026-11-27):
|
|
|
|
* the carry-over of the owner's library and each guest's own shortcuts and
|
|
preferences into the plugin's files (``carryover.prompt_shortcuts``);
|
|
* seeding an app plugin that declares ``"seed": true``;
|
|
* ``ui.pages[].nav: "settings"`` (``group`` / ``after``) and its route;
|
|
* the ``composer.shortcuts`` provider: ``position: first``, an empty
|
|
``runners`` kept, ``hidden``, and the refresh after a POSTed action.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import sys
|
|
import tempfile
|
|
import types
|
|
import unittest
|
|
from unittest import mock
|
|
|
|
BACKEND = pathlib.Path(__file__).resolve().parent
|
|
if str(BACKEND) not in sys.path:
|
|
sys.path.insert(0, str(BACKEND))
|
|
|
|
from plugins import carryover # noqa: E402
|
|
from plugins import shortcuts as plugin_shortcuts # noqa: E402
|
|
from plugins.manifest import ManifestError, validate_manifest # noqa: E402
|
|
from plugins.store import OWNER_UID, PluginStore # noqa: E402
|
|
from users.store import DEFAULT_GUEST_SHORTCUTS # noqa: E402
|
|
|
|
|
|
class FakeUiState:
|
|
def __init__(self, blobs: dict[str, dict]):
|
|
self.blobs = {k: json.dumps(v) for k, v in blobs.items()}
|
|
|
|
def get(self, key):
|
|
return self.blobs.get(key)
|
|
|
|
|
|
class FakeUsers:
|
|
def __init__(self, ids, legacy=None):
|
|
self.ids = ids
|
|
self.legacy = [dict(s) for s in (legacy if legacy is not None else DEFAULT_GUEST_SHORTCUTS)]
|
|
|
|
def all(self):
|
|
return [{"id": i} for i in self.ids]
|
|
|
|
def legacy_guest_shortcuts(self):
|
|
return [dict(s) for s in self.legacy]
|
|
|
|
|
|
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), encoding="utf-8")
|
|
for rel, content in (files or {}).items():
|
|
(root / rel).parent.mkdir(parents=True, exist_ok=True)
|
|
(root / rel).write_text(content, encoding="utf-8")
|
|
return root
|
|
|
|
|
|
APP = {
|
|
"schema": 1, "id": "prompt-shortcuts", "name": "Prompt shortcuts", "version": "1.0.0",
|
|
"description": "chips", "seed": True, "managed": {"defaultForGuests": True},
|
|
"provides": {"composer.shortcuts": "shortcuts"},
|
|
"actions": {"shortcuts": {"script": "actions/shortcuts.py", "readOnly": True}},
|
|
"ui": {"pages": [{"id": "library", "label": "Prompt shortcuts", "nav": "settings",
|
|
"group": "you", "after": "keyboard", "html": "ui/library.html"}]},
|
|
}
|
|
APP_FILES = {"actions/shortcuts.py": "print('{}')\n", "ui/library.html": "<p>x</p>"}
|
|
|
|
|
|
class CarryOverTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.td = tempfile.TemporaryDirectory()
|
|
self.store = PluginStore(pathlib.Path(self.td.name) / "plugins")
|
|
|
|
def tearDown(self):
|
|
self.td.cleanup()
|
|
|
|
def _library(self):
|
|
p = self.store.shared_data_dir("prompt-shortcuts") / "library.json"
|
|
return json.loads(p.read_text()) if p.exists() else None
|
|
|
|
def _personal(self, uid):
|
|
p = self.store.user_data_dir(uid, "prompt-shortcuts") / "personal.json"
|
|
return json.loads(p.read_text()) if p.exists() else None
|
|
|
|
def test_v4_library_and_guests_move_once(self):
|
|
ui = FakeUiState({
|
|
"ai-agent-settings": {"version": 4, "state": {"theme": "dark", "promptShortcuts": [
|
|
{"id": "changes", "label": "Changes", "icon": "GitCommitHorizontal",
|
|
"guideline": "ship", "defaultOn": True, "labelOff": "No changes",
|
|
"guidelineOff": "no", "shared": True, "guests": True},
|
|
{"id": "deploy", "label": "Deploy", "guideline": "deploy", "shared": False,
|
|
"runners": ["local", "orus"], "children": ["pr"]},
|
|
{"id": "pr", "label": "PR", "guideline": "pr", "shared": False,
|
|
"runners": [], "guests": True, "triggers": ["open a pr"]},
|
|
{"id": "junk"}, # no label: dropped
|
|
]}},
|
|
"u.dom.ai-agent-settings": {"version": 4, "state": {
|
|
"promptShortcuts": [{"id": "mine", "label": "Mine", "guideline": "m"}],
|
|
"shortcutPrefs": {"changes": {"hidden": True}, "pr": {"defaultOn": True, "x": 1},
|
|
"bad": "no"}}},
|
|
"u.claire.ai-agent-settings": {"version": 4, "state": {"promptShortcuts": [],
|
|
"shortcutPrefs": {}}},
|
|
})
|
|
users = FakeUsers(["dom", "claire", "ghost"])
|
|
self.assertTrue(carryover.prompt_shortcuts(self.store, ui, users))
|
|
lib = self._library()
|
|
self.assertEqual(lib["version"], 1)
|
|
by_id = {s["id"]: s for s in lib["shortcuts"]}
|
|
self.assertEqual(list(by_id), ["changes", "deploy", "pr"])
|
|
self.assertEqual((by_id["changes"]["shared"], by_id["changes"]["guests"]), (True, True))
|
|
self.assertEqual(by_id["changes"]["guidelineOff"], "no")
|
|
self.assertEqual((by_id["deploy"]["runners"], by_id["deploy"]["guests"]), (["local", "orus"], False))
|
|
self.assertEqual(by_id["deploy"]["children"], ["pr"])
|
|
self.assertEqual((by_id["pr"]["runners"], by_id["pr"]["triggers"]), ([], ["open a pr"]))
|
|
dom = self._personal("dom")
|
|
self.assertEqual([s["id"] for s in dom["shortcuts"]], ["mine"])
|
|
self.assertTrue(dom["shortcuts"][0]["shared"])
|
|
self.assertEqual(dom["prefs"], {"changes": {"hidden": True}, "pr": {"defaultOn": True}})
|
|
self.assertIsNone(self._personal("claire")) # nothing of their own
|
|
# once: a later start changes nothing, even with new ui-state
|
|
ui.blobs["ai-agent-settings"] = json.dumps({"version": 4, "state": {"promptShortcuts": []}})
|
|
self.assertFalse(carryover.prompt_shortcuts(self.store, ui, users))
|
|
self.assertEqual(len(self._library()["shortcuts"]), 3)
|
|
|
|
def test_pre_v4_library_folds_the_old_guest_list(self):
|
|
ask = next(s for s in DEFAULT_GUEST_SHORTCUTS if s["id"] == "ask")
|
|
ui = FakeUiState({
|
|
"ai-agent-settings": {"version": 3, "state": {"promptShortcuts": [
|
|
{"id": "commit", "label": "Commit & push", "guideline": "commit+push", "shared": True},
|
|
{**ask, "shared": True},
|
|
{"id": "deploy", "label": "Deploy", "guideline": "deploy", "shared": False,
|
|
"runner": "orus"},
|
|
{"id": "worktree", "label": "Worktree", "guideline": "wt"}, # v2: no `shared`
|
|
{"id": "lab", "label": "Lab", "guideline": "lab"},
|
|
]}},
|
|
"u.dom.ai-agent-settings": {"version": 3, "state": {"promptShortcuts": [
|
|
{"id": "commit", "label": "Commit"}, {"id": "mine", "label": "Mine"}]}},
|
|
})
|
|
carryover.prompt_shortcuts(self.store, ui, FakeUsers(["dom"]))
|
|
by_id = {s["id"]: s for s in self._library()["shortcuts"]}
|
|
self.assertFalse(by_id["commit"]["guests"])
|
|
self.assertEqual((by_id["guest-commit"]["label"], by_id["guest-commit"]["guests"],
|
|
by_id["guest-commit"]["shared"], by_id["guest-commit"]["runners"]),
|
|
("Commit", True, False, []))
|
|
self.assertTrue(by_id["ask"]["guests"])
|
|
self.assertNotIn("guest-ask", by_id)
|
|
self.assertEqual((by_id["deploy"]["shared"], by_id["deploy"]["runners"]), (False, ["orus"]))
|
|
self.assertNotIn("runner", by_id["deploy"])
|
|
self.assertTrue(by_id["worktree"]["shared"]) # the old shared-by-default ids
|
|
self.assertEqual((by_id["lab"]["shared"], by_id["lab"]["runners"]), (False, ["local"]))
|
|
# the guest's frozen copy of the old list goes, what they added stays
|
|
self.assertEqual([s["id"] for s in self._personal("dom")["shortcuts"]], ["mine"])
|
|
|
|
def test_keeps_what_the_plugin_has_and_skips_a_missing_store(self):
|
|
dst = self.store.shared_data_dir("prompt-shortcuts") / "library.json"
|
|
dst.write_text(json.dumps({"version": 1, "shortcuts": [{"id": "x"}]}))
|
|
ui = FakeUiState({"ai-agent-settings": {"version": 4, "state": {"promptShortcuts": [
|
|
{"id": "a", "label": "A", "guideline": "a", "shared": True}]}}})
|
|
carryover.prompt_shortcuts(self.store, ui, FakeUsers([]))
|
|
self.assertEqual(self._library()["shortcuts"], [{"id": "x"}])
|
|
self.assertFalse(carryover.prompt_shortcuts(self.store, None, None))
|
|
|
|
def test_no_owner_blob_leaves_the_builtins(self):
|
|
carryover.prompt_shortcuts(self.store, FakeUiState({}), FakeUsers([]))
|
|
self.assertIsNone(self._library())
|
|
self.assertTrue((self.store.shared_data_dir("prompt-shortcuts") / ".carried-over").exists())
|
|
|
|
|
|
class SeedAndManifestTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.td = tempfile.TemporaryDirectory()
|
|
self.root = pathlib.Path(self.td.name)
|
|
|
|
def tearDown(self):
|
|
self.td.cleanup()
|
|
|
|
def test_settings_page_and_seed_validate(self):
|
|
mf = validate_manifest(_write_plugin(self.root / "ps", APP, APP_FILES))
|
|
self.assertTrue(mf["seed"])
|
|
pg = mf["ui"]["pages"][0]
|
|
self.assertEqual((pg["nav"], pg["group"], pg["after"]), ("settings", "you", "keyboard"))
|
|
# a dashboards page carries neither
|
|
dash = {**APP, "seed": False, "ui": {"pages": [{"id": "p", "html": "ui/library.html"}]}}
|
|
mf = validate_manifest(_write_plugin(self.root / "dash", dash, APP_FILES))
|
|
self.assertNotIn("seed", mf)
|
|
self.assertNotIn("group", mf["ui"]["pages"][0])
|
|
|
|
def test_settings_page_errors(self):
|
|
for i, page in enumerate([
|
|
{"id": "p", "nav": "settings", "group": "nowhere", "html": "ui/library.html"},
|
|
{"id": "p", "nav": "settings", "after": "Not An Id", "html": "ui/library.html"},
|
|
{"id": "p", "nav": "dashboards", "group": "you", "html": "ui/library.html"},
|
|
]):
|
|
with self.assertRaises(ManifestError):
|
|
validate_manifest(_write_plugin(self.root / f"bad{i}", {**APP, "ui": {"pages": [page]}},
|
|
APP_FILES))
|
|
with self.assertRaises(ManifestError):
|
|
validate_manifest(_write_plugin(self.root / "badseed", {**APP, "seed": "yes"}, APP_FILES))
|
|
|
|
def test_seed_installs_an_app_that_asks_once(self):
|
|
seed = self.root / "seed"
|
|
_write_plugin(seed / "prompt-shortcuts", APP, APP_FILES)
|
|
_write_plugin(seed / "other", {**APP, "id": "other", "seed": False}, APP_FILES)
|
|
_write_plugin(seed / "broken", {"seed": True}, {})
|
|
store = PluginStore(self.root / "plugins")
|
|
self.assertEqual(carryover.seed_typed_plugins(store, seed), ["prompt-shortcuts"])
|
|
rec = next(r for r in store.list_for(OWNER_UID) if r["id"] == "prompt-shortcuts")
|
|
self.assertTrue(rec["enabled"])
|
|
self.assertFalse(rec.get("needsApproval"))
|
|
self.assertNotIn("other", {r["id"] for r in store.list_for(OWNER_UID)})
|
|
# every guest gets it through its managed grant
|
|
self.assertTrue(store.effective_grant("dom", "prompt-shortcuts")["enabled"])
|
|
self.assertEqual(carryover.seed_typed_plugins(store, seed), [])
|
|
store.uninstall(OWNER_UID, "prompt-shortcuts")
|
|
self.assertEqual(carryover.seed_typed_plugins(PluginStore(self.root / "plugins"), seed), [])
|
|
|
|
def test_seed_installs_a_required_plugin_first(self):
|
|
# `commits` requires `diff-viewer`: alphabetical order would install it first and fail.
|
|
seed = self.root / "seed2"
|
|
base = {k: v for k, v in APP.items() if k != "provides"}
|
|
_write_plugin(seed / "a-needs-z", {**base, "id": "a-needs-z", "requires": ["z-base"],
|
|
"ui": {"pages": []}}, APP_FILES)
|
|
_write_plugin(seed / "z-base", {**base, "id": "z-base", "ui": {"pages": []}}, APP_FILES)
|
|
store = PluginStore(self.root / "plugins2")
|
|
self.assertEqual(carryover.seed_typed_plugins(store, seed), ["z-base", "a-needs-z"])
|
|
self.assertEqual({r["id"] for r in store.list_for(OWNER_UID) if r["enabled"]},
|
|
{"z-base", "a-needs-z"})
|
|
|
|
|
|
class ProviderTest(unittest.TestCase):
|
|
def setUp(self):
|
|
plugin_shortcuts.invalidate()
|
|
self.addCleanup(plugin_shortcuts.invalidate)
|
|
|
|
def test_cleaning_keeps_empty_runners_and_hidden(self):
|
|
got = plugin_shortcuts._clean_shortcuts("p", {"shortcuts": [
|
|
{"id": "g", "label": "G", "guideline": "g", "shared": False, "runners": [], "guests": True},
|
|
{"id": "h", "label": "H", "guideline": "h", "hidden": True},
|
|
{"id": "n", "label": "N", "guideline": "n", "hidden": "yes"},
|
|
] + [{"id": f"x{i}", "label": "X", "guideline": "x"} for i in range(70)]})
|
|
self.assertEqual(len(got), plugin_shortcuts.MAX_SHORTCUTS)
|
|
self.assertEqual((got[0]["shared"], got[0]["runners"]), (False, []))
|
|
self.assertTrue(got[1]["hidden"])
|
|
self.assertNotIn("hidden", got[2])
|
|
|
|
def test_position_first_goes_before_the_others(self):
|
|
recs = [({"id": "ask-form", "fingerprint": "a"}, None),
|
|
({"id": "prompt-shortcuts", "fingerprint": "b"}, None)]
|
|
answers = {
|
|
"ask-form": (False, [{"id": "form", "label": "Form"}, {"id": "changes", "label": "Dup"}]),
|
|
"prompt-shortcuts": (True, [{"id": "changes", "label": "Changes"}]),
|
|
}
|
|
caller = types.SimpleNamespace(is_owner=True, id="owner")
|
|
with mock.patch.object(plugin_shortcuts, "_providers_for", return_value=recs), \
|
|
mock.patch.object(plugin_shortcuts, "_run_one",
|
|
side_effect=lambda deps, uid, rec, grant: answers[rec["id"]]):
|
|
got = plugin_shortcuts.shortcuts_for(types.SimpleNamespace(), caller)
|
|
self.assertEqual([(s["id"], s["label"]) for s in got], [("changes", "Changes"), ("form", "Form")])
|
|
self.assertTrue(plugin_shortcuts._first({"position": "first"}))
|
|
self.assertFalse(plugin_shortcuts._first({"shortcuts": []}))
|
|
|
|
def test_a_posted_action_refreshes_every_composer(self):
|
|
published = []
|
|
deps = types.SimpleNamespace(hub=types.SimpleNamespace(publish=published.append))
|
|
rec = {"id": "prompt-shortcuts", "manifest": APP}
|
|
with mock.patch.object(plugin_shortcuts, "invalidate") as inv:
|
|
plugin_shortcuts.touched(deps, rec)
|
|
inv.assert_called_once_with("prompt-shortcuts")
|
|
self.assertEqual(published, [{"type": "composer-shortcuts"}])
|
|
# a plugin without chips: silent
|
|
plugin_shortcuts.touched(deps, {"id": "x", "manifest": {"actions": {}}})
|
|
self.assertEqual(len(published), 1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|