Files
magpie/internal/gui/pluginpage_test.go
T
yetone d783df46cb plugin: a plugin's page adds items to a provider's and an agent's row menu (P6)
package.json's magpie.actions: [{id, menu, title, titles}] puts items in
the row menus magpie draws, after its own: a provider row's (right-click)
and an agent row's (its handle, or right-click). Picking one opens the
plugin's page and posts it {event: "action", data: {id, provider|agent:
{id, name}}}, nothing else of the row; the bridge's magpie.onAction(fn)
gets it, and an action picked before fn was given waits for it.

- plugin.Window reads them (page.go): menu one of ActionMenus (provider,
  agent; a session's menu is left out, its title is user content), id
  ^[a-z0-9][a-z0-9-]{0,39}$, an id given twice is the first's, 8 at most,
  none for a plugin with no page.
- /api/plugin-pages carries them on the page; a missing title is the
  page's, in each language (pluginpage.go).
- pluginpages.js: magpie.actions(menu, context) gives the row menu's
  items; openRowMenu draws a plugin's name as written (literal), not
  through t().
- The Plugins page says which menus a plugin adds to (actionsLine),
  translated in zh, zh-TW, ja and de.
- Docs: plugin-runtime.md's P6 section and verification; the site's
  plugin docs (en, zh, ja) gain "Items in magpie's menus".
- The core's budget (TestCoreScriptBudget) is not raised (#2710): with
  P6 the core came to 1,447,648 bytes, 648 over. pluginpages.js's header
  now says P5's and P6's part in one paragraph and points to
  plugin-runtime.md, which says it in full, and plugins.js's panels and
  actions lines share whereLine: 1,446,845, 155 under.

Run:
- Full: this series (P5, the Plugins dot, the probe test, P6, and a
  built-ins-on commit since dropped for main's own 5a2414acd) was run
  together, at load 200-660.
  At the pushed tree, 88dfab2d3 on origin/main 5380114da (rebased
  from 210bc2b77, no conflicts; its GUI assets and tests are the same
  bytes as the tree the GUI runs below used, diff -rq): gofmt clean,
  vet darwin/linux nogui/windows ok, TestCoreScriptBudget ok
  (1,446,845 of 1,447,000). go test -timeout 45m ./... at load
  193-278: 62 packages ok, red in TestMainWindowCorners (#1936) and
  TestPluginStreamLargeReplies JSON_fast (client timeout; alone 1 of
  3 red here, 0 of 3 on 5380114da side by side at load ~280; the
  series doesn't touch the stream path; #2551 reopened with the
  output, taken). Two earlier runs at this tree are discarded: one
  stopped when the disk filled, one when another session's go clean
  -cache emptied the build cache mid-run. The whole GUI suite at
  this tree was not finished (the disk filled); the files the series
  reaches ran (1318 tests, 124 red), and the 39 red files ran again
  at concurrency 1 on both trees: here 148 ok 120 red, origin/main
  135 ok 127 red. Both sides' reds are page.goto/launch timeouts
  under load (66 here, 71 there) and the same assertions:
  title-bar-tools' and settings-proxy-auth's "access control checks"
  on a cut-off /api/providers read (#2740, taken next), sidebar's
  "the list unrolls" and WebKit "#prefs pressed darkens" (#2684;
  alone, 1 red here, 3 on main), side-toggle (#2732); plugin-move
  red on main only. Six files again one by one on both trees:
  plugin-actions red 1 of 6 here, a 5s goto of ?view=plugins at load
  260; plugin-clash red on both; plugin-own-icon, plugin-gateway,
  plugin-checkin ok on both; settings-proxy-auth ok here, 3 red on
  main.
  At 976c9893a (on origin/main 6f950653f): go test -timeout 45m ./...
  red only in TestMainWindowCorners (#1936, the window's process
  killed at its deadline) and TestSetAnswersWhileDevinAndProvidersHang
  (#1375, 3 of 3 alone). The whole GUI suite, both engines: 10834
  tests, 237 red in 73 files, 184 of them a 180s browser launch. Those
  73 files run again at concurrency 2: 52 green, among them every
  plugin-* and agent-* file and plugin-actions; the 21 still red were
  run at origin/main f191d6423 and are red there too: codex-predictions
  (#2624), lightweight (#2638), segs-glide (#2683), usage-agents-hide
  (#2276), provider-advanced-fold (#2552), routing-bodies (#2559),
  routing-model-rest and rest-try-now (#2115, #2564), routing-keys-fold
  (#1612), routing-wb-restricted (#1905), routing-request-metrics
  (#2571), quota-count-wrap and quota-name-translated (#2228), s3-sync
  (#2448), usage-checkin (#2549), usage-ledger-abort (#2700),
  tencent-access-key (#2733), usage-range (#2734); side-toggle's WebKit
  motion red 1 of 3 on main, 0 of 3 here (#2732); usage-fold green alone.
  Rebased onto origin/main 717b69f78 (60725faa1, no conflicts): gofmt
  clean, vet darwin/linux nogui/windows ok; go test -timeout 45m ./...
  red in TestSetAnswersWhileDevinAndProvidersHang (#1375) and agent and
  gateway at the 45m alarm with tests still moving at load 400+, both ok
  alone (1173s, 1167s); 105 GUI files the series reaches (plugin*,
  sidebar*, side-*, settings*, title*, header*, agent-*): 1322 tests,
  23 red, run alone 214 of 218 ok, the 4 left in sidebar and
  sidebar-overlay-scrollbar (WebKit), red on 717b69f78 too (#2684,
  #1863). The whole GUI suite was not run again after the rebase.
- gofmt -l clean; go vet darwin, linux (-tags nogui) and windows ok;
  TestCoreScriptBudget ok.
- go test -run 'TestWindowActions|TestPluginPageActions' ok: duplicate,
  malformed and session-menu ids dropped, 12 actions kept to 8, none
  without a page, an off plugin's not served.
- plugin-actions.test.cjs: chromium and webkit, en zh zh-TW ja de, at
  1100 and 420: no page adds nothing; the agent menu ends with Hide then
  the plugin's item; the provider menu's item is in the window's
  language; a pick opens the page, which gets exactly {id, provider|
  agent: {id, name}} once, in one frame, though it calls onAction 400ms
  late. The Plugins row says which menus.
- Broken by hand, each red then restored: the bridge not holding an
  action picked before onAction (the late-registering fixture), the
  provider's whole row posted in place of {id, name} (the exact-data
  check), any id and any menu accepted (TestWindowActions).
- Neighbours in both engines: plugin-page, agent-cli-missing,
  agent-disconnect, group-bulk-remove, model-test-why and provider-find
  ok; plugin-panels red before P5's fixture fix (padding, in that
  commit), ok after.
- Real use: a dev build (-tags dev) in a sandbox HOME with a
  local plugin of two actions; WebKit on its dev UI picked "Inspect
  agent" on Claude Code and "Inspect provider" on a local provider, and
  the page logged {"id":"about-agent","agent":{"id":"claude","name":
  "Claude Code"}} then {"id":"about-provider","provider":{"id":
  "local-try","name":"Local Try"}}, one frame. Not clicked in the
  WKWebView window itself; the frame's loading there is
  TestPluginPageLoadsItsFilesInTheWindow's.
2026-10-18 07:13:12 +08:00

280 lines
11 KiB
Go

package gui
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/settings"
)
// pagePlugins writes plugins.json with the example page plugin
// (testdata/page-plugin), on, and a copy of it switched off; it answers
// their specs.
func pagePlugins(t *testing.T) (on, off string) {
t.Helper()
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
t.Setenv("XDG_DATA_HOME", filepath.Join(h, ".local", "share"))
t.Setenv("MAGPIE_BUN", "")
t.Setenv("PATH", "")
copyDir := func(to string) {
t.Helper()
err := filepath.WalkDir("testdata/page-plugin", func(p string, d os.DirEntry, err error) error {
if err != nil {
return err
}
rel, _ := filepath.Rel("testdata/page-plugin", p)
if d.IsDir() {
return os.MkdirAll(filepath.Join(to, rel), 0o755)
}
b, err := os.ReadFile(p)
if err != nil {
return err
}
return os.WriteFile(filepath.Join(to, rel), b, 0o644)
})
if err != nil {
t.Fatal(err)
}
}
on, off = filepath.Join(h, "src", "glance"), filepath.Join(h, "src", "glance-off")
copyDir(on)
copyDir(off)
// a file of the plugin's own, but out of its page's folder, and one out
// of the plugin, which a link in the page's folder points to
if err := os.WriteFile(filepath.Join(h, "secret.txt"), []byte("SECRET"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join(h, "secret.txt"), filepath.Join(on, "page", "link.txt")); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(settings.Dir(), 0o755); err != nil {
t.Fatal(err)
}
b, _ := json.Marshal(map[string]any{"plugins": []map[string]any{{"spec": on}, {"spec": off, "off": true}}})
if err := os.WriteFile(filepath.Join(settings.Dir(), "plugins.json"), b, 0o644); err != nil {
t.Fatal(err)
}
return on, off
}
func pageMux() http.Handler {
mux := http.NewServeMux()
pluginPageRoutes(mux)
mux.HandleFunc("GET /api/state", func(rw http.ResponseWriter, r *http.Request) {
writeJSON(rw, map[string]string{"secret": "the window's"})
})
return noFramedAPI(mux)
}
func do(h http.Handler, r *http.Request) *httptest.ResponseRecorder {
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
// A plugin's page's files are served by a token of this run, with a policy
// that keeps it to its own folder and off the network; nothing outside its
// page's folder is served, nor anything of a plugin switched off, nor
// anything by a token made up.
func TestPluginPageServedShutIn(t *testing.T) {
on, off := pagePlugins(t)
h := pageMux()
var pages []pluginPage
w := do(h, httptest.NewRequest("GET", "/api/plugin-pages", nil))
if err := json.Unmarshal(w.Body.Bytes(), &pages); err != nil || len(pages) != 1 {
t.Fatalf("pages: %s %v", w.Body, err)
}
p := pages[0]
if p.Spec != on || p.Key != "plugin-magpie-usage-glance" || p.Title != "Usage glance" || len(p.Reads) != 1 || p.Reads[0] != "usage:summary" {
t.Fatalf("page %+v", p)
}
tok := strings.Split(strings.TrimPrefix(p.URL, pluginPagePrefix), "/")[0]
r := httptest.NewRequest("GET", p.URL, nil)
r.Host = "127.0.0.1:3437"
w = do(h, r)
if w.Code != 200 || !strings.Contains(w.Body.String(), "Usage glance") {
t.Fatalf("the page: %d %s", w.Code, w.Body)
}
csp := w.Header().Get("Content-Security-Policy")
for _, want := range []string{"sandbox allow-scripts", "default-src 'none'", "connect-src 'none'", "script-src 127.0.0.1:3437" + pluginPagePrefix + tok + "/;", "form-action 'none'", "frame-src 'none'"} {
if !strings.Contains(csp, want) {
t.Errorf("policy %q has no %q", csp, want)
}
}
if strings.Contains(csp, "allow-same-origin") || strings.Contains(csp, "'unsafe-eval'") {
t.Errorf("policy %q lets the page out", csp)
}
// the sandboxed frame is an origin of its own: a resource policy of
// same-origin or same-site blocks the page's own scripts and styles
if c := w.Header().Get("Cross-Origin-Resource-Policy"); c != "" && c != "cross-origin" {
t.Errorf("Cross-Origin-Resource-Policy %q keeps the page from its own files", c)
}
if w.Header().Get("X-Content-Type-Options") != "nosniff" {
t.Error("no nosniff")
}
if w := do(h, httptest.NewRequest("GET", pluginPagePrefix+tok+"/"+pluginBridgePath, nil)); w.Code != 200 || !strings.Contains(w.Body.String(), "postMessage") {
t.Errorf("the bridge: %d", w.Code)
}
// out of the page's folder, through a link, by another token
for _, path := range []string{
pluginPagePrefix + tok + "/../package.json",
pluginPagePrefix + tok + "/link.txt",
pluginPagePrefix + pageToken(off) + "/index.html",
pluginPagePrefix + strings.Repeat("0", 32) + "/index.html",
pluginPagePrefix + tok,
} {
r := httptest.NewRequest("GET", "/", nil)
r.URL.Path = path
w := httptest.NewRecorder()
servePluginPage(w, r)
if w.Code == 200 || strings.Contains(w.Body.String(), "SECRET") || strings.Contains(w.Body.String(), `"name"`) {
t.Errorf("%s: %d %s", path, w.Code, w.Body)
}
}
}
// What a page didn't declare it reads is refused by the server too, not
// only by the window; a page sets its own options and no other plugin's.
func TestPluginPageReadsWhatItDeclared(t *testing.T) {
on, off := pagePlugins(t)
h := pageMux()
post := func(path, body string) *httptest.ResponseRecorder {
r := httptest.NewRequest("POST", path, strings.NewReader(body))
r.Header.Set("Content-Type", "application/json")
return do(h, r)
}
spec, _ := json.Marshal(on)
if w := post("/api/plugin-pages/read", `{"spec":`+string(spec)+`,"read":"providers:list"}`); w.Code != http.StatusForbidden {
t.Errorf("an undeclared read: %d %s", w.Code, w.Body)
}
w := post("/api/plugin-pages/read", `{"spec":`+string(spec)+`,"read":"usage:summary","params":{"period":"today"}}`)
var sum map[string]any
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &sum) != nil || sum["period"] != "today" {
t.Errorf("a declared read: %d %s", w.Code, w.Body)
}
for _, k := range []string{"callerKeys", "accounts", "sessions", "providerKeys"} {
if _, ok := sum[k]; ok {
t.Errorf("usage:summary gave the page %s", k)
}
}
offSpec, _ := json.Marshal(off)
if w := post("/api/plugin-pages/read", `{"spec":`+string(offSpec)+`,"read":"usage:summary"}`); w.Code == 200 {
t.Errorf("a plugin switched off read: %d", w.Code)
}
if w := post("/api/plugin-pages/options", `{"spec":`+string(spec)+`,"options":{"hideCost":true}}`); w.Code != 200 || !strings.Contains(w.Body.String(), `"hideCost":true`) {
t.Fatalf("options set: %d %s", w.Code, w.Body)
}
if w := post("/api/plugin-pages/options", `{"spec":`+string(spec)+`,"options":{"hideCost":false}}`); w.Code != http.StatusTooManyRequests {
t.Errorf("a second set within the second: %d", w.Code)
}
if w := post("/api/plugin-pages/options", `{"spec":`+string(spec)+`}`); !strings.Contains(w.Body.String(), `"hideCost":true`) {
t.Errorf("options get: %s", w.Body)
}
if w := post("/api/plugin-pages/options", `{"spec":`+string(offSpec)+`,"options":{"x":1}}`); w.Code == 200 {
t.Errorf("another plugin's options set: %d", w.Code)
}
if !pageSetAllowed("x", time.Now()) || pageSetAllowed("x", time.Now()) || !pageSetAllowed("x", time.Now().Add(2*time.Second)) {
t.Error("pageSetAllowed")
}
}
// The desktop window's /api has no key: what keeps a plugin's page off it
// is that every way a sandboxed frame can ask is turned away, a fetch
// (Origin: null), a frame of /api, another site's page; the window's own
// requests, and a link opened from elsewhere, go on.
func TestPluginPageNoAPI(t *testing.T) {
pagePlugins(t)
h := pageMux()
ask := func(set map[string]string) int {
r := httptest.NewRequest("GET", "/api/state", nil)
for k, v := range set {
r.Header.Set(k, v)
}
return do(h, r).Code
}
for _, c := range []map[string]string{
{"Origin": "null"},
{"Origin": "null", "Sec-Fetch-Site": "cross-site", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Dest": "empty"},
{"Sec-Fetch-Dest": "iframe", "Sec-Fetch-Site": "same-origin"},
{"Sec-Fetch-Dest": "image", "Sec-Fetch-Site": "cross-site"},
{"Sec-Fetch-Dest": "script", "Sec-Fetch-Site": "cross-site"},
} {
if code := ask(c); code != http.StatusForbidden {
t.Errorf("%v: %d", c, code)
}
}
// the window's own handler, not only this test's
r := httptest.NewRequest("GET", "/api/plugin-pages", nil)
r.Header.Set("Origin", "null")
if w := do(Handler(nil, nil), r); w.Code != http.StatusForbidden {
t.Errorf("the window's /api to a sandboxed frame: %d", w.Code)
}
for _, c := range []map[string]string{
{},
{"Sec-Fetch-Site": "same-origin", "Sec-Fetch-Dest": "empty", "Origin": "http://127.0.0.1:3437"},
{"Sec-Fetch-Site": "cross-site", "Sec-Fetch-Dest": "document"},
} {
if code := ask(c); code != 200 {
t.Errorf("%v: %d", c, code)
}
}
}
// magpie web's guard lets a page's files through without the cookie a
// sandboxed frame never sends, and only those: a made-up token is served
// nothing, and the rest of the page still wants the key.
func TestPluginPageWebGuard(t *testing.T) {
pagePlugins(t)
g := webGuard("magpie_web_1", "key", 0, pageMux())
var pages []pluginPage
_ = json.Unmarshal(do(pageMux(), httptest.NewRequest("GET", "/api/plugin-pages", nil)).Body.Bytes(), &pages)
if len(pages) != 1 {
t.Fatal("no page")
}
if w := do(g, httptest.NewRequest("GET", pages[0].URL, nil)); w.Code != 200 {
t.Errorf("the page's file without the cookie: %d", w.Code)
}
if w := do(g, httptest.NewRequest("GET", pluginPagePrefix+strings.Repeat("a", 32)+"/index.html", nil)); w.Code != 404 {
t.Errorf("a made-up token: %d", w.Code)
}
if w := do(g, httptest.NewRequest("GET", "/api/plugin-pages", nil)); w.Code != http.StatusUnauthorized {
t.Errorf("/api without the cookie: %d", w.Code)
}
}
// A page's actions (magpie.actions) come with it to the window, one that
// names no title by the page's own in each language; a plugin switched
// off adds no item to any menu.
func TestPluginPageActions(t *testing.T) {
on, off := pagePlugins(t)
for _, dir := range []string{on, off} {
pkg := `{"name":"magpie-usage-glance","magpie":{"page":{"title":"Usage glance","titles":{"zh":"用量速览"},"file":"page/index.html"},
"actions":[{"id":"check","menu":"provider","title":"Check balance","titles":{"ja":"残高を確認"}},{"id":"logs","menu":"agent"}]}}`
if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte(pkg), 0o644); err != nil {
t.Fatal(err)
}
}
var pages []pluginPage
w := do(pageMux(), httptest.NewRequest("GET", "/api/plugin-pages", nil))
if err := json.Unmarshal(w.Body.Bytes(), &pages); err != nil || len(pages) != 1 {
t.Fatalf("pages: %s %v", w.Body, err)
}
a := pages[0].Actions
if len(a) != 2 || a[0].ID != "check" || a[0].Menu != "provider" || a[0].Title != "Check balance" || a[0].Titles["ja"] != "残高を確認" {
t.Fatalf("actions %+v", a)
}
if a[1].ID != "logs" || a[1].Menu != "agent" || a[1].Title != "Usage glance" || a[1].Titles["zh"] != "用量速览" {
t.Errorf("an action with no title: %+v, want the page's", a[1])
}
}