gui: a plugin page with a host part starts the host when it opens

guesssssssswhat on X: the Magiczerowxy/magpie-chat page ("对话") sits
on its loading text and never opens. The page says hello and then
navigates its frame to http://127.0.0.1:3477, a server the plugin's
index.mjs starts inside the Bun host. The host was started only by a
call: at launch while providers are first read, and after a Restart
(a plugin installed, updated or set, a Bun update) or a crash only once
something asked a plugin again. With the host down, WebKit (the macOS
window's WKWebView, WebKitGTK) leaves a frame whose navigation is
refused on its old document with no error, and the hello had already
cleared the 10s broken timer, so the page waits forever. Chromium shows
chrome-error instead.

Now serving the entry HTML of a page or panel whose plugin is not
page-only starts the host if none is up (plugin.Warm), waiting at most
7s, then serves the page. Page-only plugins, and the page's other files
and the bridge, don't touch the host.

Reproduced on mote (sandbox HOME, magpie web on a free port, plugin
0.1.16 from GitHub): with its 3477 listener killed, old main's page
stays on "正在连接到本地对话服务…" in Playwright WebKit (chrome-error
in Chromium); the fixed build restarts the host on open and the chat UI
loads in both engines. In the real macOS app (wails://) the frame
reaches 127.0.0.1 (seen by a logging server). TestPluginPageStartsItsHost
is red with the pageHost call removed by hand.

Run at this head (84a6a2c42 + this), on mote: gofmt -l clean; go vet,
GOOS=linux go vet -tags nogui, GOOS=windows go vet; go build,
GOOS=linux go build -tags nogui, GOOS=windows go build; go test ./...
-timeout 45m: every package ok except internal/gui's
TestMainWindowCorners/macOS_26_SDK, red on macOS 27 and filed as #3949
(titlebar, untouched here). plugin-page.test.cjs and
plugin-kinds-discover.test.cjs, Chromium and WebKit, 14/14 each.
Rebased on 29181eb78 (usage, gateway; no file here), then go vet and
go test ./internal/gui/ ./internal/plugin/ again: same, only #3949 red.
Pushed on b586fdf1e, whose two commits (app.css, usage pricing) weren't run with this.
win-run: go test -run 'TestPluginPage|TestWindowPage' ./internal/gui/
./internal/plugin/ ok.

Not tried: the reporter's OS and magpie version; the real Windows and
Linux app windows (wsl-run can't build internal/gui: no gtk4 or
webkitgtk-6.0 dev packages in magpie-desktop, internal/plugin ok); a
real Restart in the background (simulated by killing the host); the
full GUI suite (no asset changed). magpie-chat 0.1.9 to 0.1.13 had no
main or exports, so they are page-only and no host ever starts them;
0.1.14 restored main, and that's for the plugin to tell its users.
This commit is contained in:
yetone
2026-10-28 21:27:47 +08:00
parent b586fdf1eb
commit ca499953e7
4 changed files with 167 additions and 7 deletions
+1 -1
View File
@@ -270,7 +270,7 @@ still means off; a page is its own plugin's to turn on and off.
| Router strategy | A module's `export const strategies = {name: (pool, seats, options) => order}` (or `{order}` objects) are routings `<short name>/<name>`, registered with `routes.Register` while the gateway serves `middleware.Points()` and the plugin is on and loaded; off or reloaded, they are removed. 20ms each, fail open: an error, a timeout or what isn't an order of the seats is the listed order, counted on the Plugins page. The routing pickers offer the served ones (`jsRoutings` in the settings state); a routing saved whose plugin is gone shows as it is and is the listed order. providers.json keeps such a routing as saved (`provider.PluginRouting`), so a plugin turned off and on again routes its groups again. | `plugins/middleware` ("JS gateway plugins", from the same module as its [middleware](gateway-middleware.md)) | [`points.go`](../../internal/middleware/points.go), [`app.js`](../../internal/gui/assets/app.js), [`client.js`](../../internal/gui/assets/plugins/routing/client.js), [`groups_cli.go`](../../internal/cli/groups_cli.go), [`routing.go`](../../internal/provider/routing.go) |
| Usage observer | `export function onUsage(row, options)` gets each usage row of an allow-list (no bodies, prompts or ids), from a bounded queue off the request path: a full queue drops and counts, and a request never waits. 250ms each, fail open. | `plugins/middleware` ("JS gateway plugins", from the same module as its [middleware](gateway-middleware.md)) | [`points.go`](../../internal/middleware/points.go) |
| Tool | Its OpenCode `tool` hook's tools, offered to every agent by magpie's MCP server at `/mcp/magpie/tools`, each named `<plugin>_<tool>`, each call held to the calling key's limit and run in the host within 55s. Off, no tool is listed and a call says the plugin is off. | `plugins/tools` ("Plugin tools", Essential; `InUse` counts the plugins on that give tools, from `plugin-tools.json`), `gwtool.PluginTools` | [Plugin tools](plugin-tools.md) |
| A page in the window | `magpie.page {title, file, icon}` and `magpie.permissions` in package.json, installed from npm, GitHub or a folder like any plugin (`plugin.WindowPage`: `file` an .html inside the plugin, the icon in the page's folder, reads kept to `plugin.PageReads`). An on plugin's page gets a tab in the sidebar's Plugins group, after the built-in pages (`pluginpages.js`, a kernel `page` part). It runs in an iframe sandboxed to `allow-scripts`, its files served from `/_magpie/plugin/<token>/` (an HMAC of the spec with a secret of this run) under a policy of `sandbox allow-scripts`, its own folder only, `connect-src 'none'`. The frame talks to the window by `postMessage`: the window answers only its own frame (`ev.source`), with the theme, its own options (`/api/plugin-pages/options`, at most once a second, saved without restarting the host for a page-only plugin) and the reads it declared (`/api/plugin-pages/read`, checked again by the server): `usage:summary` (totals and the top 20 models) and `providers:list` (ids and names). Nothing secret is readable, since a page can still send its frame to another site. `noFramedAPI` turns away every `/api/` request a sandboxed frame or another site can send (`Origin: null`, `Sec-Fetch-Dest` a frame, a cross-site subresource), since the desktop window's API has no key; `webGuard` lets the prefix through without the cookie the frame never sends, and the token is the key. A page that throws, or doesn't say hello in 10s, is broken through the kernel (`ctx.broke`), with Try again. The Plugins page shows the page and its reads on the row before the plugin is on. A plugin that is only a page is in-magpie-only: no Bun host starts for it. Discover lists a market entry of `kind: "page"` under Pages with the Page chip, and a GitHub repository tagged `magpie-plugin` whose package.json has `magpie.page.file` as a Page (`TaggedRepos`, which then checks that file is committed, as it does a provider's entry; `TestTaggedRepos`, `plugin-kinds-discover.test.cjs`). Tests: `TestWindowPageStaysInside`, `TestPluginPageServedShutIn`, `TestPluginPageReadsWhatItDeclared`, `TestPluginPageNoAPI`, `TestPluginPageWebGuard`, `plugin-page.test.cjs`. Example: `internal/gui/testdata/page-plugin`. | the window, no built-in plugin: the page is the plugin's own on/off | [`page.go`](../../internal/plugin/page.go), [`pluginpage.go`](../../internal/gui/pluginpage.go), [`pagebridge.js`](../../internal/gui/pagebridge.js), [`pluginpages.js`](../../internal/gui/assets/pluginpages.js) |
| A page in the window | `magpie.page {title, file, icon}` and `magpie.permissions` in package.json, installed from npm, GitHub or a folder like any plugin (`plugin.WindowPage`: `file` an .html inside the plugin, the icon in the page's folder, reads kept to `plugin.PageReads`). An on plugin's page gets a tab in the sidebar's Plugins group, after the built-in pages (`pluginpages.js`, a kernel `page` part). It runs in an iframe sandboxed to `allow-scripts`, its files served from `/_magpie/plugin/<token>/` (an HMAC of the spec with a secret of this run) under a policy of `sandbox allow-scripts`, its own folder only, `connect-src 'none'`. The frame talks to the window by `postMessage`: the window answers only its own frame (`ev.source`), with the theme, its own options (`/api/plugin-pages/options`, at most once a second, saved without restarting the host for a page-only plugin) and the reads it declared (`/api/plugin-pages/read`, checked again by the server): `usage:summary` (totals and the top 20 models) and `providers:list` (ids and names). Nothing secret is readable, since a page can still send its frame to another site. `noFramedAPI` turns away every `/api/` request a sandboxed frame or another site can send (`Origin: null`, `Sec-Fetch-Dest` a frame, a cross-site subresource), since the desktop window's API has no key; `webGuard` lets the prefix through without the cookie the frame never sends, and the token is the key. A page that throws, or doesn't say hello in 10s, is broken through the kernel (`ctx.broke`), with Try again. The Plugins page shows the page and its reads on the row before the plugin is on. A plugin that is only a page is in-magpie-only: no Bun host starts for it. A page whose plugin also has a part for the host (a local service its page goes to, as Magiczerowxy/magpie-chat's does) starts the host when its HTML is served, if none is up (`pageHost`, `plugin.Warm`), waiting up to 7s: the host otherwise starts only on a call, so after a Restart (a plugin installed, updated or set, a Bun update) or a crash the page's service was down, and WebKit leaves a frame that navigates to a refused address on its old document with no error. Discover lists a market entry of `kind: "page"` under Pages with the Page chip, and a GitHub repository tagged `magpie-plugin` whose package.json has `magpie.page.file` as a Page (`TaggedRepos`, which then checks that file is committed, as it does a provider's entry; `TestTaggedRepos`, `plugin-kinds-discover.test.cjs`). Tests: `TestWindowPageStaysInside`, `TestPluginPageServedShutIn`, `TestPluginPageReadsWhatItDeclared`, `TestPluginPageNoAPI`, `TestPluginPageWebGuard`, `TestPluginPageStartsItsHost`, `plugin-page.test.cjs`. Example: `internal/gui/testdata/page-plugin`. | the window, no built-in plugin: the page is the plugin's own on/off | [`page.go`](../../internal/plugin/page.go), [`pluginpage.go`](../../internal/gui/pluginpage.go), [`pagebridge.js`](../../internal/gui/pagebridge.js), [`pluginpages.js`](../../internal/gui/assets/pluginpages.js) |
`plugins/middleware` is now "JS gateway plugins". Apply registers the chain and `usage.Observe(middleware.Points())`; off, no JS middleware, strategy or `onUsage` runs, and a pool routed by a JS strategy is its listed order. `InUse` is unchanged. ([`middleware.go`](../../plugins/middleware/middleware.go))
+55 -6
View File
@@ -1,6 +1,7 @@
package gui
import (
"context"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
@@ -9,6 +10,7 @@ import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
@@ -81,6 +83,8 @@ type pluginPage struct {
Actions []pluginAction `json:"actions,omitempty"`
token string
dir string
file string // its HTML, relative to dir, with forward slashes
hosted bool // its plugin has a part for the host too (pageHost)
}
// pluginAction is an item a plugin's page adds to one of magpie's menus.
@@ -104,6 +108,8 @@ type pluginPanel struct {
Reads []string `json:"reads"` // what it may read, of plugin.PageReads
token string
dir string
file string
hosted bool
}
// pageKeyChars are what a window page's key can't have
@@ -119,7 +125,7 @@ func windowParts() (pages []pluginPage, panels []pluginPanel) {
if e.Off {
continue
}
w, _ := plugin.Window(plugin.Target(e.Spec))
w, only := plugin.Window(plugin.Target(e.Spec))
if w == nil {
continue
}
@@ -143,7 +149,7 @@ func windowParts() (pages []pluginPage, panels []pluginPanel) {
tok := pageToken(e.Spec)
rel, _ := filepath.Rel(spec.Dir, spec.File)
p := pluginPage{Spec: e.Spec, Name: name, Key: key, Title: spec.Title, Titles: spec.Titles, Reads: reads, token: tok, dir: spec.Dir,
URL: pluginPagePrefix + tok + "/" + filepath.ToSlash(rel)}
URL: pluginPagePrefix + tok + "/" + filepath.ToSlash(rel), file: filepath.ToSlash(rel), hosted: !only}
if p.Title == "" {
p.Title = plugin.ShortName(name)
}
@@ -168,7 +174,7 @@ func windowParts() (pages []pluginPage, panels []pluginPanel) {
tok := pageToken(e.Spec + "\x00panel\x00" + strconv.Itoa(i))
rel, _ := filepath.Rel(spec.Dir, spec.File)
p := pluginPanel{Spec: e.Spec, Name: name, Key: fmt.Sprintf("%s-%d", key, i), Slot: spec.Slot, Title: spec.Title, Titles: spec.Titles, Reads: reads,
token: tok, dir: spec.Dir, URL: pluginPagePrefix + tok + "/" + filepath.ToSlash(rel)}
token: tok, dir: spec.Dir, URL: pluginPagePrefix + tok + "/" + filepath.ToSlash(rel), file: filepath.ToSlash(rel), hosted: !only}
if p.Title == "" {
p.Title = plugin.ShortName(name)
}
@@ -235,6 +241,44 @@ func pagePolicy(r *http.Request, tok string) string {
}, "; ")
}
// pageHostWait is how long a page's HTML waits for its plugin's host,
// short of the window's 10 seconds for the page to say hello
// (pluginpages.js's HELLO_MS).
var pageHostWait = 7 * time.Second
// warmHost starts the plugin host if it isn't up; tests replace it.
var warmHost = plugin.Warm
// pageHost has the plugin host up for a page whose plugin has a part for
// it too, waiting pageHostWait at most. Such a page can be the way into
// a service that part runs: Magiczerowxy/magpie-chat's page sends its
// frame to the chat server its host part starts. The host starts only on
// a call, and every Restart (a plugin installed, updated or set, a Bun
// update) stops it until the next one, so with no other plugin asking,
// the page went to a server that wasn't there: Chromium shows its
// connection error, and WebKit (the Mac's and Linux's window) leaves the
// frame on the page's own "connecting…" for good. The host starts in the
// background under its own two minutes, as every caller's does, so a
// slow one isn't cut off when the page stops waiting.
func pageHost(ctx context.Context) {
done := make(chan struct{})
go func() {
defer close(done)
c, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
if err := warmHost(c); err != nil {
log.Printf("plugin page: starting the plugin host: %v", err)
}
}()
t := time.NewTimer(pageHostWait)
defer t.Stop()
select {
case <-done:
case <-t.C:
case <-ctx.Done():
}
}
// servePluginPage serves a file of a plugin's page, by its token.
func servePluginPage(rw http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
@@ -248,22 +292,27 @@ func servePluginPage(rw http.ResponseWriter, r *http.Request) {
return
}
// the page's or the panel's folder, by its token
dir := ""
dir, entry, hosted := "", "", false
pages, panels := windowParts()
for _, p := range pages {
if hmac.Equal([]byte(p.token), []byte(tok)) {
dir = p.dir
dir, entry, hosted = p.dir, p.file, p.hosted
}
}
for _, p := range panels {
if hmac.Equal([]byte(p.token), []byte(tok)) {
dir = p.dir
dir, entry, hosted = p.dir, p.file, p.hosted
}
}
if dir == "" {
http.NotFound(rw, r)
return
}
// the page itself, of a plugin with a part for the host: that part is
// up before the page is (pageHost)
if hosted && rel == entry {
pageHost(r.Context())
}
h := rw.Header()
h.Set("Content-Security-Policy", pagePolicy(r, tok))
h.Set("X-Content-Type-Options", "nosniff")
+96
View File
@@ -1,15 +1,18 @@
package gui
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/settings"
)
@@ -188,6 +191,99 @@ func TestPluginPageReadsWhatItDeclared(t *testing.T) {
}
}
// A page whose plugin has a part for the host too has the host up before
// its HTML is served: Magiczerowxy/magpie-chat's page sends its frame to
// the chat server that part starts, and with the host stopped (after a
// Restart, nothing else asking) WebKit left the frame on "connecting…"
// for good (guesssssssswhat on X). A page-only plugin starts no host,
// nor does any other file of the page, and a host slower than
// pageHostWait doesn't hold the page past it.
func TestPluginPageStartsItsHost(t *testing.T) {
on, _ := pagePlugins(t)
hosted := filepath.Join(filepath.Dir(on), "chat")
if err := os.CopyFS(hosted, os.DirFS("testdata/page-plugin")); err != nil {
t.Fatal(err)
}
pkg := `{"name": "page-chat", "main": "./index.mjs", "magpie": {"page": {"title": "Chat", "file": "page/index.html"}}}`
if err := os.WriteFile(filepath.Join(hosted, "package.json"), []byte(pkg), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(hosted, "index.mjs"), []byte("export default {}\n"), 0o644); err != nil {
t.Fatal(err)
}
b, _ := json.Marshal(map[string]any{"plugins": []map[string]any{{"spec": on}, {"spec": hosted}}})
if err := os.WriteFile(filepath.Join(settings.Dir(), "plugins.json"), b, 0o644); err != nil {
t.Fatal(err)
}
var mu sync.Mutex
warmed := 0
hold := make(chan struct{})
warmHost = func(ctx context.Context) error {
mu.Lock()
warmed++
mu.Unlock()
<-hold
return nil
}
t.Cleanup(func() { warmHost = plugin.Warm })
count := func() int {
mu.Lock()
defer mu.Unlock()
return warmed
}
pages := pluginPages()
if len(pages) != 2 {
t.Fatalf("pages: %+v", pages)
}
glance, chat := pages[0], pages[1]
h := pageMux()
// the page-only plugin's page: no host
if w := do(h, httptest.NewRequest("GET", glance.URL, nil)); w.Code != 200 || count() != 0 {
t.Fatalf("a page-only plugin's page: %d, host started %d times", w.Code, count())
}
// the hosted plugin's page waits for its host
served := make(chan *httptest.ResponseRecorder, 1)
go func() { served <- do(h, httptest.NewRequest("GET", chat.URL, nil)) }()
for deadline := time.Now().Add(5 * time.Second); count() == 0; {
if time.Now().After(deadline) {
t.Fatal("opening the hosted plugin's page didn't start its host")
}
time.Sleep(time.Millisecond)
}
select {
case w := <-served:
t.Fatalf("the page was served (%d) before its host was up", w.Code)
case <-time.After(50 * time.Millisecond):
}
close(hold)
if w := <-served; w.Code != 200 || !strings.Contains(w.Body.String(), "Usage glance") {
t.Fatalf("the hosted page: %d %s", w.Code, w.Body)
}
// its other files ask nothing of the host
n := count()
tok := strings.Split(strings.TrimPrefix(chat.URL, pluginPagePrefix), "/")[0]
for _, f := range []string{"style.css", "app.js", pluginBridgePath} {
if w := do(h, httptest.NewRequest("GET", pluginPagePrefix+tok+"/"+f, nil)); w.Code != 200 || count() != n {
t.Errorf("%s: %d, host started %d times", f, w.Code, count()-n)
}
}
// a host that never comes up holds the page pageHostWait, no longer
stuck := make(chan struct{})
defer close(stuck)
warmHost = func(ctx context.Context) error { <-stuck; return nil }
old := pageHostWait
pageHostWait = 100 * time.Millisecond
t.Cleanup(func() { pageHostWait = old })
start := time.Now()
if w := do(h, httptest.NewRequest("GET", chat.URL, nil)); w.Code != 200 {
t.Fatalf("the page with its host stuck: %d", w.Code)
}
if d := time.Since(start); d < 100*time.Millisecond || d > 3*time.Second {
t.Errorf("the page with its host stuck waited %v; want pageHostWait (100ms)", d)
}
}
// 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
+15
View File
@@ -747,6 +747,21 @@ func Running() bool {
return current != nil && current.alive()
}
// Warm starts the host if none is up and Bun is here. A plugin's page in
// the window whose plugin has a part for the host too (a local service
// its page goes to, as Magiczerowxy/magpie-chat's does) is served by the
// host, which is otherwise started only by a call: at launch, while the
// providers are first read, and after every Restart (a plugin installed,
// updated or set, a Bun update) only once something asks a plugin again.
// Opening such a page is that ask.
func Warm(ctx context.Context) error {
if Running() || !HasBun() {
return nil
}
_, err := get(ctx)
return err
}
func (h *host) alive() bool {
select {
case <-h.dead: