ui.pages[].fileTypes (a viewer page picked by extension; host-file links,
file chips, /file/* and open() follow it; init.fileOpeners), the
aiAgentPlugin.fetchFile bridge (any hub file path, any type, <= 100 MB) and
ui.filePreviews (a card under an agent's message naming a previewable host
file, mounted once visible). navigate(path, {replace}). Docs: plugins.md →
File viewers.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
204 lines
9.7 KiB
Python
204 lines
9.7 KiB
Python
"""File viewers (docs/plugins.md → "File viewers: pages by type, fetchFile,
|
|
previews"): ``ui.pages[].fileTypes`` (a viewer page picked by extension) and
|
|
``ui.filePreviews[]`` (an inline card under an agent's message naming a host
|
|
file). The manifest keys and their refusals, the approval fingerprint of a
|
|
plugin without them, the descriptors ``GET /api/plugins`` hands the app and
|
|
the document ``/ui/preview/<id>`` serves."""
|
|
|
|
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.manifest import ManifestError, capability_fingerprint, validate_manifest # noqa: E402
|
|
from plugins.store import OWNER_UID, PluginStore # noqa: E402
|
|
|
|
OWNER_H = {"X-Internal-Auth": os.environ.get("INTERNAL_API_TOKEN", "")}
|
|
DOC = "<p>viewer frame</p>"
|
|
|
|
|
|
def _write(root: pathlib.Path, mf: dict) -> pathlib.Path:
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
(root / "plugin.json").write_text(json.dumps(mf, indent=2), encoding="utf-8")
|
|
(root / "ui").mkdir(exist_ok=True)
|
|
(root / "ui" / "v.html").write_text(DOC, encoding="utf-8")
|
|
return root
|
|
|
|
|
|
def _page(**kw) -> dict:
|
|
return {"id": "view", "label": "View", "nav": "files", "html": "ui/v.html",
|
|
"opens": ["host-file"], **kw}
|
|
|
|
|
|
def _mf(pid: str, pages=None, previews=None) -> dict:
|
|
ui: dict = {}
|
|
if pages is not None:
|
|
ui["pages"] = pages
|
|
if previews is not None:
|
|
ui["filePreviews"] = previews
|
|
return {"schema": 1, "id": pid, "name": pid.title(), "ui": ui}
|
|
|
|
|
|
class FileTypesManifestTest(unittest.TestCase):
|
|
def test_page_file_types(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
mf = validate_manifest(_write(pathlib.Path(td) / "pdf", _mf("pdf", [
|
|
_page(fileTypes=["pdf", "PDF".lower(), "epub"])])))
|
|
pg = mf["ui"]["pages"][0]
|
|
self.assertEqual(pg["fileTypes"], ["pdf", "epub"])
|
|
self.assertEqual(pg["opens"], ["host-file"])
|
|
# a page without the key doesn't get one
|
|
mf = validate_manifest(_write(pathlib.Path(td) / "x", _mf("x", [_page()])))
|
|
self.assertNotIn("fileTypes", mf["ui"]["pages"][0])
|
|
|
|
def test_page_file_types_refused(self):
|
|
bad = [
|
|
(_page(fileTypes=["pdf"], opens=["commit"]), "needs \"opens\""),
|
|
({**_page(fileTypes=["pdf"]), "opens": None}, "needs \"opens\""),
|
|
(_page(fileTypes=[]), "fileTypes must be"),
|
|
(_page(fileTypes=".pdf"), "fileTypes must be"),
|
|
(_page(fileTypes=[".pdf"]), "fileTypes must be"),
|
|
(_page(fileTypes=["PDF"]), "fileTypes must be"),
|
|
(_page(fileTypes=["abcdefghijk"]), "fileTypes must be"),
|
|
(_page(fileTypes=[f"e{i}" for i in range(33)]), "fileTypes must be"),
|
|
(_page(fileTypes=[1]), "fileTypes must be"),
|
|
]
|
|
with tempfile.TemporaryDirectory() as td:
|
|
for i, (pg, why) in enumerate(bad):
|
|
if pg.get("opens") is None:
|
|
pg = {k: v for k, v in pg.items() if k != "opens"}
|
|
with self.subTest(i=i, why=why), self.assertRaises(ManifestError) as cm:
|
|
validate_manifest(_write(pathlib.Path(td) / f"p{i}", _mf(f"p{i}", [pg])))
|
|
self.assertIn(why, str(cm.exception))
|
|
|
|
def test_previews_normalized(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
mf = validate_manifest(_write(pathlib.Path(td) / "pdf", _mf("pdf", previews=[
|
|
{"id": "card", "label": "PDF", "html": "ui/v.html", "fileTypes": ["pdf"], "height": 200,
|
|
"vis": {"key": "pdf", "label": "PDF previews", "hint": "pdf cards"}},
|
|
{"id": "other", "html": "ui/v.html", "fileTypes": ["epub", "epub"]},
|
|
])))
|
|
card, other = mf["ui"]["filePreviews"]
|
|
self.assertEqual(card, {"id": "card", "label": "PDF", "html": "ui/v.html", "fileTypes": ["pdf"],
|
|
"height": 200, "vis": {"key": "pdf", "label": "PDF previews",
|
|
"hint": "pdf cards"}})
|
|
self.assertEqual(other["fileTypes"], ["epub"])
|
|
self.assertEqual(other["height"], 240)
|
|
self.assertEqual(other["label"], "other")
|
|
self.assertNotIn("vis", other)
|
|
|
|
def test_previews_refused(self):
|
|
ok = {"id": "a", "html": "ui/v.html", "fileTypes": ["pdf"]}
|
|
bad = [
|
|
([{**ok, "fileTypes": []}], "fileTypes must be"),
|
|
([{**ok, "fileTypes": ["Pdf"]}], "fileTypes must be"),
|
|
([{k: v for k, v in ok.items() if k != "fileTypes"}], "fileTypes must be"),
|
|
([{**ok, "html": "../x.html"}], "html"),
|
|
([{**ok, "height": 10}], "height"),
|
|
([{**ok, "id": "a b"}], "id invalid"),
|
|
([ok, ok], "declared twice"),
|
|
([{**ok, "id": f"p{i}"} for i in range(5)], "at most 4"),
|
|
("nope", "must be a list"),
|
|
([{**ok, "vis": {"key": "Bad Key"}}], "vis"),
|
|
]
|
|
with tempfile.TemporaryDirectory() as td:
|
|
for i, (previews, why) in enumerate(bad):
|
|
with self.subTest(why=why), self.assertRaises(ManifestError) as cm:
|
|
validate_manifest(_write(pathlib.Path(td) / f"p{i}", _mf(f"p{i}", previews=previews)))
|
|
self.assertIn(why, str(cm.exception))
|
|
|
|
def test_fingerprint_unchanged_without_them(self):
|
|
"""Neither key in a normalized ``ui`` that declares none: the approval
|
|
fingerprint of every installed plugin stays put."""
|
|
with tempfile.TemporaryDirectory() as td:
|
|
root = _write(pathlib.Path(td) / "e", _mf("e", [_page()]))
|
|
mf = validate_manifest(root)
|
|
self.assertNotIn("filePreviews", mf["ui"])
|
|
self.assertNotIn("fileTypes", mf["ui"]["pages"][0])
|
|
fp = capability_fingerprint(mf)
|
|
raw = json.loads((root / "plugin.json").read_text())
|
|
raw["ui"]["filePreviews"] = []
|
|
(root / "plugin.json").write_text(json.dumps(raw))
|
|
self.assertEqual(capability_fingerprint(validate_manifest(root)), fp)
|
|
raw["ui"]["pages"][0]["fileTypes"] = ["pdf"]
|
|
(root / "plugin.json").write_text(json.dumps(raw))
|
|
self.assertNotEqual(capability_fingerprint(validate_manifest(root)), fp)
|
|
|
|
|
|
class FileViewerRoutesTest(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)
|
|
|
|
def tearDown(self):
|
|
self.deps.plugin_store = self.orig
|
|
self.td.cleanup()
|
|
|
|
def test_descriptors_and_document(self):
|
|
a = _write(self.root / "pdf", _mf("pdf", [_page(fileTypes=["pdf"])], previews=[
|
|
{"id": "card", "html": "ui/v.html", "fileTypes": ["pdf"], "height": 180}]))
|
|
b = _write(self.root / "viewers", _mf("viewers", [_page(id="media", fileTypes=["mp4", "pdf"])], previews=[
|
|
{"id": "clip", "html": "ui/v.html", "fileTypes": ["mp4", "pdf"]}]))
|
|
self.store.install(OWNER_UID, str(a), is_owner=True)
|
|
self.store.install(OWNER_UID, str(b), is_owner=True)
|
|
for route in ("/api/plugins", "/api/plugins/ui"):
|
|
r = self.client.get(route, headers=OWNER_H)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
ui = r.json()["ui"]
|
|
pages = {p["pluginId"]: p for p in ui["pages"]}
|
|
self.assertEqual(pages["pdf"]["fileTypes"], ["pdf"])
|
|
self.assertEqual(pages["viewers"]["fileTypes"], ["mp4", "pdf"])
|
|
prev = ui["filePreviews"]
|
|
# every active plugin's, in plugin order (by id) — the app takes the first per ext
|
|
self.assertEqual([(p["pluginId"], p["id"]) for p in prev], [("pdf", "card"), ("viewers", "clip")])
|
|
self.assertEqual(prev[0]["height"], 180)
|
|
self.assertNotIn("html", prev[0])
|
|
doc = self.client.get("/api/plugins/pdf/ui/preview/card", headers=OWNER_H)
|
|
self.assertEqual(doc.status_code, 200, doc.text)
|
|
self.assertEqual(doc.text, DOC)
|
|
self.assertEqual(self.client.get("/api/plugins/pdf/ui/preview/nope", headers=OWNER_H).status_code, 404)
|
|
|
|
def test_no_previews_is_an_empty_list(self):
|
|
r = self.client.get("/api/plugins", headers=OWNER_H)
|
|
self.assertEqual(r.json()["ui"]["filePreviews"], [])
|
|
|
|
def test_capability_line(self):
|
|
a = _write(self.root / "pdf", _mf("pdf", previews=[
|
|
{"id": "card", "html": "ui/v.html", "fileTypes": ["pdf", "epub"]}]))
|
|
from plugins.manifest import capability_summary
|
|
lines = [i["label"] for i in capability_summary(validate_manifest(a))]
|
|
self.assertIn("Previews .pdf, .epub files agents' messages name (sandboxed)", lines)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|