Files
magpie/internal/plugin/page.go
T
yetone b9f790d37b plugins: panels in magpie's pages, a page that replaces a built-in one, titles in the window's language, and a look that matches
P5 of the plugin runtime (docs/subsystems/plugin-runtime.md):

- Panels (magpie.panels): a plugin draws a frame into a slot of a
  built-in page (a provider's editor, Settings, Usage); magpie.context
  says where it is, and the frame is as tall as what it draws.
- A page can replace a built-in one (magpie.page.replaces); show() opens
  it in that page's place, and the sidebar row goes to it.
- page.titles and a panel's titles name it in the window's language
  ({"zh": …}); a malformed map is dropped, the title kept
  (TestWindowTitles).
- main's #2501 already names wails:// in the policy of a page in the
  desktop window (through ownWindow), which is why the usage page drew as
  bare HTML from v0.1.1259. TestPluginPageLoadsItsFilesInTheWindow loads
  a page through ownWindow in a real WKWebView, which Playwright on http
  can't; the subsystem page says how.
- The bridge adds magpie's look for what a page leaves unstyled, every
  rule in :where() so any rule of the page's wins, and the theme's
  colours as --magpie-* variables.

One commit: the panels, the replacing pages and the titles share hunks
in page.go, pluginpage.go, pluginpages.js and the docs, and couldn't be
split cleanly.

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.
- plugin-panels' tall panel (body{margin:0}) measured 220, not 180,
  after the look above gave an unstyled body 20px of padding; the
  fixture now sets padding:0 too, as a page that wants none would.
  plugin-panels ok in chromium and webkit after.
- gofmt -l clean; go vet darwin, linux (-tags nogui) and windows ok.
- GUI: plugin-page and plugin-panels in chromium and webkit, en zh zh-TW
  ja de, wide and narrow, ok.
- Broken by hand, each red then green: titled() in pluginpages.js
  (the "draws in its frame" test), the wails:// scheme in pagePolicy
  (the WKWebView test, before the rebase onto #2501), titles' parsing
  (TestWindowTitles).
- Real use: the published @magpie-community/page-usage 0.1.1 in a
  sandbox magpie window, its tiles styled.
2026-10-18 07:13:09 +08:00

242 lines
7.8 KiB
Go

package plugin
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
)
// WindowSpec is what a plugin adds to magpie's window: its page
// (package.json's magpie.page), its panels in magpie's own pages
// (magpie.panels), and the reads magpie.permissions asks for, which its
// page and its panels share.
type WindowSpec struct {
Page *PageSpec // nil when it adds no page of its own
Panels []PanelSpec
// Reads are the reads it asked for that magpie has (PageReads), in
// the order asked.
Reads []string
}
// PageSpec is a plugin's own page in magpie's window.
type PageSpec struct {
Title string // "" when it names none
// Titles are its title in other languages, by the window's language
// ("zh", "zh-TW", "ja", "de"): magpie.page.titles
Titles map[string]string
Icon string // a file in the page's folder, relative to it, or ""
File string // the page's HTML, inside the plugin's folder
Dir string // the folder the page's files are served from: File's
// Replaces is the built-in page (one of Replaceable) whose place in
// the sidebar the page takes while its plugin is on, or "".
Replaces string
}
// PanelSpec is a panel a plugin adds to one of magpie's own pages: a
// part of that page, drawn by the plugin's HTML in a frame of its own.
type PanelSpec struct {
Slot string // one of PanelSlots
Title string // "" when it names none
Titles map[string]string
File string // the panel's HTML, inside the plugin's folder
Dir string // the folder the panel's files are served from: File's
}
// PageReads are the reads a plugin's page can be granted, each in
// magpie.permissions. None of them carries a secret.
var PageReads = []string{"usage:summary", "providers:list"}
// PanelSlots are the places in magpie's own pages a plugin's panel can
// go: under the Agents page's list, at the end of the Usage page, on
// Settings' Plugins tab, and in a provider's editor (which tells the
// panel the provider's id and name).
var PanelSlots = []string{"agents", "usage", "settings", "provider"}
// Replaceable are the built-in pages a plugin's page can take the place
// of: the pages that are built-in plugins of their own.
var Replaceable = []string{"sessions", "library", "routing", "usage"}
// titles are a page's or a panel's titles by language, without the empty
// ones, or nil: magpie.page.titles {"zh": "…"}. title stays a string
// beside them, so a magpie that knows no titles still reads the package,
// and titles that aren't an object of strings leave the page as it was.
func titles(raw json.RawMessage) map[string]string {
var m map[string]any
if json.Unmarshal(raw, &m) != nil {
return nil
}
var out map[string]string
for k, x := range m {
v, _ := x.(string)
k, v = strings.TrimSpace(k), strings.TrimSpace(v)
if k == "" || v == "" || len(k) > 16 || len(out) == 16 {
continue
}
if out == nil {
out = map[string]string{}
}
out[k] = v
}
return out
}
// maxPanels is how many panels one plugin adds, at most.
const maxPanels = 8
// Window is what a plugin at target adds to magpie's window, or nil when
// it adds nothing: package.json's magpie.page {title, file, icon,
// replaces} and magpie.panels [{slot, file, title}]. A file outside the
// plugin's folder, or not .html, is no page or panel; a panel in a slot
// magpie doesn't have is left out, and so is a replaces of a page that
// can't be replaced. only is whether it is nothing else: no OpenCode
// plugin for the host to load (no main, no exports).
func Window(target string) (w *WindowSpec, only bool) {
st, err := os.Stat(target)
if err != nil || !st.IsDir() {
return nil, false
}
b, err := os.ReadFile(filepath.Join(target, "package.json"))
if err != nil {
return nil, false
}
type part struct {
Title string `json:"title"`
Titles json.RawMessage `json:"titles"`
File string `json:"file"`
Icon string `json:"icon"`
Slot string `json:"slot"`
Replaces string `json:"replaces"`
}
var pkg struct {
Main string `json:"main"`
Exports json.RawMessage `json:"exports"`
Magpie struct {
Page *part `json:"page"`
Panels []part `json:"panels"`
Permissions []string `json:"permissions"`
} `json:"magpie"`
}
if json.Unmarshal(b, &pkg) != nil {
return nil, false
}
w = &WindowSpec{}
if pg := pkg.Magpie.Page; pg != nil {
if file, ok := htmlInside(target, pg.File); ok {
p := &PageSpec{Title: strings.TrimSpace(pg.Title), Titles: titles(pg.Titles), File: file, Dir: filepath.Dir(file)}
// the icon is served with the page, so it sits in the page's folder
if icon, ok := inside(target, pg.Icon); ok {
if rel, err := filepath.Rel(p.Dir, icon); err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
p.Icon = filepath.ToSlash(rel)
}
}
if r := strings.TrimSpace(pg.Replaces); slices.Contains(Replaceable, r) {
p.Replaces = r
}
w.Page = p
}
}
for _, pn := range pkg.Magpie.Panels {
if len(w.Panels) == maxPanels {
break
}
slot := strings.TrimSpace(pn.Slot)
file, ok := htmlInside(target, pn.File)
if !ok || !slices.Contains(PanelSlots, slot) {
continue
}
w.Panels = append(w.Panels, PanelSpec{Slot: slot, Title: strings.TrimSpace(pn.Title), Titles: titles(pn.Titles), File: file, Dir: filepath.Dir(file)})
}
if w.Page == nil && len(w.Panels) == 0 {
return nil, false
}
for _, r := range pkg.Magpie.Permissions {
if slices.Contains(PageReads, r) && !slices.Contains(w.Reads, r) {
w.Reads = append(w.Reads, r)
}
}
return w, pkg.Main == "" && len(pkg.Exports) == 0
}
// htmlInside is rel joined to dir, if that stays inside dir and is an
// .html file.
func htmlInside(dir, rel string) (string, bool) {
file, ok := inside(dir, rel)
if !ok || !strings.HasSuffix(strings.ToLower(file), ".html") {
return "", false
}
if st, err := os.Stat(file); err != nil || st.IsDir() {
return "", false
}
return file, true
}
// inside is rel joined to dir, if that stays inside dir: no "..", no
// absolute path, and no symbolic link out of it.
func inside(dir, rel string) (string, bool) {
rel = strings.TrimSpace(rel)
if rel == "" || filepath.IsAbs(rel) || strings.HasPrefix(rel, "/") || strings.Contains(rel, `\`) {
return "", false
}
clean := filepath.Clean(filepath.FromSlash(rel))
if clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) {
return "", false
}
full := filepath.Join(dir, clean)
realDir, err := filepath.EvalSymlinks(dir)
if err != nil {
return "", false
}
real, err := filepath.EvalSymlinks(full)
if err != nil {
return "", false
}
if r, err := filepath.Rel(realDir, real); err != nil || r == ".." || strings.HasPrefix(r, ".."+string(filepath.Separator)) {
return "", false
}
return full, true
}
// FileIn is the file at rel among the files served from dir (a page's
// or a panel's folder), if it is one: inside dir, and a file.
func FileIn(dir, rel string) (string, bool) {
f, ok := inside(dir, rel)
if !ok {
return "", false
}
if st, err := os.Stat(f); err != nil || st.IsDir() {
return "", false
}
return f, true
}
// SetPageOptions sets the options of a plugin from its page or a panel.
// One whose page and panels are all it has is never loaded by the host, so the host goes on as
// it was; any other is SetOptions, which starts the host again for it.
func SetPageOptions(spec string, opts map[string]any) error {
t := Target(spec)
if mw, _ := Middleware(t); mw != "" {
return SetOptions(spec, opts)
}
if ag, _ := Agent(t); ag != "" {
return SetOptions(spec, opts)
}
if w, only := Window(t); w == nil || !only {
return SetOptions(spec, opts)
}
listMu.Lock()
defer listMu.Unlock()
l := Load()
i := indexOf(l, spec)
if i < 0 {
return fmt.Errorf("no plugin %q", spec)
}
if len(opts) == 0 {
opts = nil
}
l.Plugins[i].Options = opts
return save(l)
}