Files
ai-agent/backend/test_plugin_launch.py
gabrielvidalandClaude Opus 5.5 d9cd099143 feat(plugins): What's new leaves the core for the whats-new plugin — provides app.launch opens a plugin's app.modal on opening the app
- app.launch: GET /api/plugins/app-launch (plugins/launch.py) asked once per
  opening (load / foreground) by PluginLaunchHost; answers open a plugin's
  app.modal slot in the host modal (iPhone-safe), closeAction runs on close
- impersonatedBy in an action's AIA_USER_CONTEXT; users.read createdAt;
  init.lang in every frame; plugin page labels through t()
- whatsnew.index bridge for App usage; Settings entries may point at plugin pages
- carryover.whats_new: the core tables -> the plugin's shared files, whatsNew:false -> autoOpen:false
- gone: backend/whatsnew, /api/whats-new*, business/whatsNew, cli/whats_new.py,
  ai-agent whats-new, users.json whatsNew in the API, the User page panel

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

281 lines
13 KiB
Python

"""What opens on its own as the app opens — ``provides: app.launch`` and
``GET /api/plugins/app-launch`` (plugins/launch.py) — plus what the What's new
move to the ``whats-new`` plugin left in the core: ``impersonatedBy`` in an
action's context, ``createdAt`` on ``users.read``, the ``whatsnew.index``
bridge (App usage) and the carry-over of the core's tables.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
from __future__ import annotations
import asyncio
import json
import os
import pathlib
import sqlite3
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)
for k, v in {"DB_PATH": _DATA / "ai-agent.db", "TRANSCRIPTS_DIR": _DATA / "transcripts",
"WORKSPACE": _DATA / "workspace", "REPO_DIR": _DATA / "workspace",
"PLUGINS_DIR": _DATA / "plugins", "UI_STATE_PATH": _DATA / "ui-state.json",
"USERS_PATH": _DATA / "users.json", "AUTH_PATH": _DATA / "auth.json",
"TOOLS_TOKEN_KEY": _DATA / "tools.key"}.items():
os.environ.setdefault(k, str(v))
os.environ.setdefault("INTERNAL_API_TOKEN", "tok")
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
from plugins import carryover, launch, whatsnew_bridge # noqa: E402
from plugins.manifest import validate_manifest # noqa: E402
from plugins.store import OWNER_UID, PluginStore # noqa: E402
from users.caller import OWNER, guest_from_record # noqa: E402
OWNER_H = {"X-Internal-Auth": "tok"}
# The provider echoes what it was handed, so the tests see the payload, the
# context and the grant.
ECHO = ("import json, os, sys\n"
"p = json.load(sys.stdin)\n"
"ctx = json.loads(os.environ['AIA_USER_CONTEXT'])\n"
"mode = open('mode.txt').read().strip() if os.path.exists('mode.txt') else 'ok'\n"
"if mode == 'nothing':\n"
" print('{}')\n"
"elif mode == 'bad-slot':\n"
" print(json.dumps({'modal': {'slot': 'card', 'init': {}}}))\n"
"elif mode == 'boom':\n"
" sys.exit(3)\n"
"else:\n"
" print(json.dumps({'modal': {'slot': 'hello', 'closeAction': 'closed',\n"
" 'init': {'payload': p, 'uid': ctx.get('uid'), 'grant': ctx.get('grant'),\n"
" 'impersonatedBy': ctx.get('impersonatedBy')}}}))\n")
def _plugin(root: pathlib.Path, pid: str, *, managed: bool = False) -> pathlib.Path:
d = root / pid
(d / "ui").mkdir(parents=True, exist_ok=True)
(d / "ui" / "m.html").write_text("<p>hi</p>")
(d / "launch.py").write_text(ECHO)
(d / "closed.py").write_text("import sys, json; json.load(sys.stdin); print('{}')\n")
mf = {"schema": 1, "id": pid, "name": pid.title(),
"ui": {"slots": [{"id": "hello", "where": "app.modal", "html": "ui/m.html"},
{"id": "card", "where": "home.section", "html": "ui/m.html"}]},
"actions": {"launch": {"script": "launch.py", "readOnly": True},
"closed": {"script": "closed.py"}},
"provides": {"app.launch": "launch"}}
if managed:
mf["managed"] = {"defaultForGuests": True, "grantFields": [
{"key": "autoOpen", "label": "Auto", "type": "checkbox", "default": True}]}
(d / "plugin.json").write_text(json.dumps(mf))
return d
class LaunchTest(unittest.TestCase):
def setUp(self):
self.td = tempfile.TemporaryDirectory()
self.root = pathlib.Path(self.td.name)
self.deps = main.app.state.ai
self.orig = self.deps.plugin_store
self.store = PluginStore(self.root / "plugins-data")
self.deps.plugin_store = self.store
self.client = TestClient(main.app)
for u in self.deps.users.all():
self.deps.users.delete(u["id"])
self.dom = self.deps.users.create("dom@example.com", "Dom")
def tearDown(self):
self.deps.plugin_store = self.orig
self.td.cleanup()
def install(self, pid: str = "hello", **kw) -> dict:
rec = self.store.install(OWNER_UID, str(_plugin(self.root, pid, **kw)), is_owner=True)
return rec
def test_manifest_takes_app_launch(self):
mf = validate_manifest(_plugin(self.root, "hello"))
self.assertEqual(mf["provides"], {"app.launch": "launch"})
def test_route_answers_the_owners_provider(self):
self.install()
r = self.client.get("/api/plugins/app-launch?reason=foreground&path=/conversation/x", headers=OWNER_H)
self.assertEqual(r.status_code, 200, r.text)
[item] = r.json()["open"]
self.assertEqual((item["pluginId"], item["slotId"], item["closeAction"]), ("hello", "hello", "closed"))
self.assertEqual(item["init"]["payload"],
{"trigger": "app.launch", "reason": "foreground", "path": "/conversation/x"})
self.assertEqual(item["init"]["uid"], OWNER_UID)
self.assertIsNone(item["init"]["impersonatedBy"])
def test_route_is_empty_without_a_provider(self):
self.assertEqual(self.client.get("/api/plugins/app-launch", headers=OWNER_H).json(), {"open": []})
def test_odd_reasons_and_paths_are_cleaned(self):
self.install()
out = launch.launch_for(self.deps, OWNER, "midnight", "//evil.example")
self.assertEqual(out[0]["init"]["payload"]["reason"], "load")
self.assertEqual(out[0]["init"]["payload"]["path"], "/")
def test_answers_that_arent_its_own_app_modal_are_dropped(self):
self.install()
rec = self.store.get_raw(OWNER_UID, "hello")
for mode in ("nothing", "bad-slot", "boom"):
(pathlib.Path(self.store.get_raw(OWNER_UID, "hello")["dir"]) / "mode.txt").write_text(mode)
self.assertEqual(launch.launch_for(self.deps, OWNER), [], mode)
self.assertIsNone(launch.clean_answer(rec, {"modal": {"slot": "hello", "init": {"x": "y" * 17_000}}}))
self.assertIsNone(launch.clean_answer(rec, {"modal": {"slot": "hello", "init": []}}))
got = launch.clean_answer(rec, {"modal": {"slot": "hello", "closeAction": "nope"}})
self.assertEqual(got, {"pluginId": "hello", "slotId": "hello", "init": {}})
def test_a_guest_gets_a_managed_plugins_answer_with_their_grant(self):
self.install(managed=True)
guest = guest_from_record(self.dom)
[item] = launch.launch_for(self.deps, guest)
self.assertEqual(item["init"]["uid"], self.dom["id"])
self.assertEqual(item["init"]["grant"]["autoOpen"], True)
self.store.set_grant(self.dom["id"], "hello", enabled=False)
self.assertEqual(launch.launch_for(self.deps, guest), [])
def test_the_owner_through_a_guests_eyes_is_named(self):
self.install(managed=True)
import dataclasses
peek = dataclasses.replace(guest_from_record(self.dom), impersonator=OWNER_UID)
[item] = launch.launch_for(self.deps, peek)
self.assertEqual(item["init"]["impersonatedBy"], OWNER_UID)
def test_an_action_called_while_impersonating_says_so(self):
d = _plugin(self.root, "echo", managed=True)
(d / "who.py").write_text("import json, os, sys\njson.load(sys.stdin)\n"
"print(os.environ['AIA_USER_CONTEXT'])\n")
mf = json.loads((d / "plugin.json").read_text())
mf["actions"]["who"] = {"script": "who.py", "readOnly": True}
(d / "plugin.json").write_text(json.dumps(mf))
self.store.install(OWNER_UID, str(d), is_owner=True)
from plugins import routes as plugin_routes
import dataclasses
g = guest_from_record(self.dom)
ctx = asyncio.run(plugin_routes._invoke_action(self.deps, g, "echo", "who", {}, read=True))
self.assertNotIn("impersonatedBy", ctx)
peek = dataclasses.replace(g, impersonator=OWNER_UID)
ctx = asyncio.run(plugin_routes._invoke_action(self.deps, peek, "echo", "who", {}, read=False))
self.assertEqual(ctx["impersonatedBy"], OWNER_UID)
class UsersReadTest(unittest.TestCase):
def test_safe_user_carries_created_at(self):
deps = main.app.state.ai
u = deps.users.create("eve@example.com", "Eve")
from plugins.hubbridge import _safe_user
self.assertEqual(_safe_user(deps, u["id"])["createdAt"], u["createdAt"])
class WhatsNewBridgeTest(unittest.TestCase):
def setUp(self):
self.td = tempfile.TemporaryDirectory()
self.root = pathlib.Path(self.td.name)
self.deps = main.app.state.ai
self.orig = self.deps.plugin_store
self.store = PluginStore(self.root / "plugins-data")
self.deps.plugin_store = self.store
whatsnew_bridge.invalidate()
def tearDown(self):
self.deps.plugin_store = self.orig
whatsnew_bridge.invalidate()
self.td.cleanup()
def test_no_plugin_no_entries(self):
self.assertEqual(whatsnew_bridge.entries(self.deps), [])
def test_the_providers_entries(self):
d = self.root / "wn"
d.mkdir()
(d / "i.py").write_text("import json, sys\njson.load(sys.stdin)\nprint(json.dumps({'entries': ["
"{'id': 'a', 'title': 'A', 'publishedAt': '2026-11-01T00:00:00Z', 'seen': 2},"
"{'title': 'no id'}]}))\n")
(d / "plugin.json").write_text(json.dumps({
"schema": 1, "id": "wn", "name": "WN", "actions": {"index": {"script": "i.py", "readOnly": True}},
"provides": {"whatsnew.index": "index"}}))
self.store.install(OWNER_UID, str(d), is_owner=True)
self.assertEqual(whatsnew_bridge.entries(self.deps),
[{"id": "a", "title": "A", "publishedAt": "2026-11-01T00:00:00Z", "seen": 2}])
class CarryOverTest(unittest.TestCase):
def setUp(self):
self.td = tempfile.TemporaryDirectory()
self.root = pathlib.Path(self.td.name)
self.store = PluginStore(self.root / "plugins-data")
self.db = self.root / "ai-agent.db"
con = sqlite3.connect(self.db)
con.executescript("""
CREATE TABLE whats_new (id TEXT PRIMARY KEY, title TEXT NOT NULL, body TEXT NOT NULL,
mockup TEXT, status TEXT NOT NULL DEFAULT 'published', published_at REAL,
created_at REAL NOT NULL, updated_at REAL NOT NULL, session_id TEXT);
CREATE TABLE whats_new_seen (user_id TEXT NOT NULL, entry_id TEXT NOT NULL,
seen_at REAL NOT NULL, PRIMARY KEY (user_id, entry_id));
INSERT INTO whats_new VALUES ('tes-couleurs', 'Tes couleurs', '- une', '<div>m</div>',
'published', 1762000000.5, 1761990000, 1762000000.5, 'sess-1');
INSERT INTO whats_new VALUES ('brouillon', 'Brouillon', '- deux', NULL, 'draft', NULL,
1762100000, 1762100000, NULL);
INSERT INTO whats_new_seen VALUES ('dom', 'tes-couleurs', 1762050000);
""")
con.commit()
con.close()
class Users:
def all(self_inner):
return [{"id": "dom", "whatsNew": False}, {"id": "eve", "whatsNew": True}, {"id": "zed"}]
self.users = Users()
def tearDown(self):
self.td.cleanup()
def test_tables_become_the_plugins_files_then_switches_once_installed(self):
self.assertTrue(carryover.whats_new(self.store, self.users, str(self.db)))
shared = self.store.shared_data_dir("whats-new")
entries = json.loads((shared / "entries.json").read_text())["entries"]
self.assertEqual([e["id"] for e in entries], ["tes-couleurs", "brouillon"])
e = entries[0]
self.assertEqual((e["status"], e["mockup"], e["sessionId"]), ("published", "<div>m</div>", "sess-1"))
self.assertTrue(e["publishedAt"].startswith("2025-11-01T"))
self.assertIsNone(entries[1]["publishedAt"])
seen = json.loads((shared / "seen.json").read_text())["seen"]
self.assertEqual(list(seen["dom"]), ["tes-couleurs"])
self.assertFalse((shared / ".carried-over").exists()) # the switches wait for the plugin
d = self.root / "whats-new"
d.mkdir()
(d / "l.py").write_text("print('{}')\n")
(d / "plugin.json").write_text(json.dumps({
"schema": 1, "id": "whats-new", "name": "What's new",
"managed": {"defaultForGuests": True, "grantFields": [
{"key": "autoOpen", "label": "Auto", "type": "checkbox", "default": True}]},
"actions": {"launch": {"script": "l.py"}}}))
self.store.install(OWNER_UID, str(d), is_owner=True)
(shared / "entries.json").write_text('{"entries": []}') # the plugin's own copy now
self.assertTrue(carryover.whats_new(self.store, self.users, str(self.db)))
self.assertEqual(json.loads((shared / "entries.json").read_text()), {"entries": []}) # never overwritten
mf = self.store.get_raw(OWNER_UID, "whats-new")["manifest"]
self.assertFalse(self.store.effective_grant("dom", "whats-new", mf)["config"]["autoOpen"])
self.assertTrue(self.store.effective_grant("eve", "whats-new", mf)["config"]["autoOpen"])
self.assertTrue((shared / ".carried-over").exists())
self.assertFalse(carryover.whats_new(self.store, self.users, str(self.db)))
def test_no_tables_nothing_to_carry(self):
empty = self.root / "empty.db"
sqlite3.connect(empty).close()
self.assertFalse(carryover.whats_new(self.store, None, str(empty)))
self.assertFalse(carryover.whats_new(self.store, None, str(self.root / "missing.db")))
if __name__ == "__main__":
unittest.main()