diff --git a/docs/subsystems/plugin-runtime.md b/docs/subsystems/plugin-runtime.md index b190f1438..afb724e0a 100644 --- a/docs/subsystems/plugin-runtime.md +++ b/docs/subsystems/plugin-runtime.md @@ -271,7 +271,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 `/`, 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 `_`, 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//` (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 frame is made the first time the page is opened. When the reader goes to another page it is told (`{event: "visibility", data: {visible: false}}`, the bridge's `magpie.visible` and `magpie.onVisibility(fn)`), since a frame in a hidden view isn't hidden to itself, and told again on coming back. A page left 10 minutes (`IDLE_MS`) has its frame let go, with its scripts, timers and connections, and loads again when it is next opened; `magpie.page.keepAlive: true` (`plugin.PageSpec.KeepAlive`, anything but `true` is false) keeps it however long, for a page that works while no one looks at it. Tests: `TestWindowPanels` (keepAlive), `plugin-page-idle.test.cjs`. 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. A page reaches its service through magpie too, when the plugin declares it (`magpie.page.service {port, option}`, `plugin.ServiceSpec`: the port, or the plugin option named, from its plugins.json `options`): in `magpie web`, where 127.0.0.1 is the viewer's own computer, not the server (aigcfree on Discord: a server behind nginx, a Windows PC's browser, "127.0.0.1 refused to connect"), `/api/plugin-pages` gives the page a `service` under its token, `_magpie/service/`, and the bridge hands it to the frame as `magpie.service`, an absolute address (the desktop window gets none, and the page goes to 127.0.0.1 as before; a slot page gets none). `servePageService` reverse-proxies it to 127.0.0.1:: Host set to the service's own (its rebinding check), the window's cookie taken off, Origin only absent or `null` (403 otherwise), Set-Cookie dropped, everything it sends sandboxed (`sandbox allow-scripts; frame-ancestors 'self'`, `Referrer-Policy: no-referrer`), streamed as it comes (`FlushInterval -1`, `X-Accel-Buffering: no` on an event stream, which `webCompressed` never gzips), a redirect to its own address made relative, and the gateway's port never served (a request from this server is loopback, which the gateway takes without a key). The way in is the page's: the token, which only a signed-in `/api` hands out, behind `AllowGuard`; the service stays on loopback. Its entry starts the host as the page's HTML does, and a service not up yet answers its frame with a 502 page that tries again in 2s. The chat page (`@magpie-community/page-chat` 0.1.1) goes to `magpie.service` when given one, else 127.0.0.1, and asks its `api/…` by relative address. Tests: `TestPluginPageServiceListedToBrowserOnly`, `TestPluginPageServiceSpec`, `TestPluginPageServiceProxied`, `TestPluginPageServiceDown`, `TestServiceLocation`, `plugin-page.test.cjs` (`magpie.service`). 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) | +| 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//` (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 frame is made the first time the page is opened. When the reader goes to another page it is told (`{event: "visibility", data: {visible: false}}`, the bridge's `magpie.visible` and `magpie.onVisibility(fn)`), since a frame in a hidden view isn't hidden to itself, and told again on coming back. A page left 10 minutes (`IDLE_MS`) has its frame let go, with its scripts, timers and connections, and loads again when it is next opened; `magpie.page.keepAlive: true` (`plugin.PageSpec.KeepAlive`, anything but `true` is false) keeps it however long, for a page that works while no one looks at it. Tests: `TestWindowPanels` (keepAlive), `plugin-page-idle.test.cjs`. 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. A page reaches its service through magpie too, when the plugin declares it (`magpie.page.service {port, option}`, `plugin.ServiceSpec`: the port, or the plugin option named, from its plugins.json `options`): in `magpie web`, where 127.0.0.1 is the viewer's own computer, not the server (aigcfree on Discord: a server behind nginx, a Windows PC's browser, "127.0.0.1 refused to connect"), `/api/plugin-pages` gives the page a `service` under its token, `_magpie/service/`, and the bridge hands it to the frame as `magpie.service`, an absolute address (the desktop window gets none, and the page goes to 127.0.0.1 as before; a slot page gets none). `servePageService` reverse-proxies it to 127.0.0.1:: Host set to the service's own (its rebinding check), the window's cookie taken off, Origin only absent or `null` (403 otherwise), Set-Cookie dropped, everything it sends sandboxed (`sandbox allow-scripts; frame-ancestors 'self'`, `Referrer-Policy: no-referrer`), streamed as it comes (`FlushInterval -1`, `X-Accel-Buffering: no` on an event stream, which `webCompressed` never gzips), a redirect to its own address made relative, and the gateway's port never served (a request from this server is loopback, which the gateway takes without a key). The way in is the page's: the token, which only a signed-in `/api` hands out, behind `AllowGuard`; the service stays on loopback. Its entry starts the host as the page's HTML does, and a service not up yet answers its frame with a 502 page that tries again in 2s. The chat page (`@magpie-community/page-chat` 0.1.1) goes to `magpie.service` when given one, else 127.0.0.1, and asks its `api/…` by relative address. Tests: `TestPluginPageServiceListedToBrowserOnly`, `TestPluginPageServiceSpec`, `TestPluginPageServiceProxied`, `TestPluginPageServiceDown`, `TestServiceLocation`, `plugin-page.test.cjs` (`magpie.service`). 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`. A magpie that serves no pages (a command such as `magpie plugin update`, `servesPages` in `internal/cli`) starts its host with each service its plugin's option moves on a free port of its own (`plugin.ServePages`, `hostOptions`): a plugin that waits on its port, as page-chat does, loads at once beside the app's host holding it, and doesn't go on trying for it to take it when the app's host restarts (#5187). A service no option moves is started as before. Tests: `TestHostServingNoPagesLeavesHeldPort`, `TestHostOptionsMoveOnlyTheService`, `TestServesPages`. | 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)) diff --git a/internal/cli/main.go b/internal/cli/main.go index 56bc67b19..0211a590f 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -27,6 +27,7 @@ import ( "github.com/yetone/magpie/internal/imagemcp" "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/notices" + "github.com/yetone/magpie/internal/plugin" "github.com/yetone/magpie/internal/pluginrt" "github.com/yetone/magpie/internal/proc" "github.com/yetone/magpie/internal/profile" @@ -282,6 +283,24 @@ var startUp = func() { release() } +// servesPages is whether magpie run with args serves plugins' pages, +// and so runs the services they talk to (plugin.ServePages): the app, +// tray, web, serve and the TUI do; a command that does its work and +// ends doesn't. +func servesPages(args []string) bool { + if len(args) == 0 { + return true + } + if strings.HasPrefix(strings.ToLower(args[0]), "magpie:") { + return hasGUI + } + switch args[0] { + case "tui", "web", "serve", "tray", "app", "gui", "panel", "-Embedding": + return true + } + return false +} + func run(args []string) error { // a command that saved a provider or a group ends with the agents' // files written, which its save no longer waits for; and a test's run @@ -379,6 +398,9 @@ func run(args []string) error { if len(args) > 0 && args[0] == "serve" && plainServe(args[1:]) { awaitGatewayFree(gatewayFreeEvery) } + // a command that serves no pages starts a plugin host beside the + // app's, whose page services it leaves to the app (#5187) + plugin.ServePages(servesPages(args)) startUp() // a provider added, edited or removed, or a list fetched anew, reaches // the model lists agents keep in files of their own, behind the save diff --git a/internal/cli/serves_pages_test.go b/internal/cli/serves_pages_test.go new file mode 100644 index 000000000..f905a90da --- /dev/null +++ b/internal/cli/serves_pages_test.go @@ -0,0 +1,21 @@ +package cli + +import "testing" + +// Only a magpie that serves pages runs plugins' page services; a command +// that does its work and ends leaves them to the app (#5187). +func TestServesPages(t *testing.T) { + for _, args := range [][]string{nil, {"tui"}, {"web"}, {"serve"}, {"tray"}, {"app"}, {"gui", "settings"}, {"panel"}, {"-Embedding"}} { + if !servesPages(args) { + t.Errorf("%q serves no pages, want it to", args) + } + } + for _, args := range [][]string{{"plugin", "update"}, {"plugin", "list"}, {"plugin", "add", "x"}, {"claude"}, {"daemon", "install"}, {"autostart"}, {"providers"}} { + if servesPages(args) { + t.Errorf("%q serves pages, want it not to", args) + } + } + if servesPages([]string{"magpie://import?x"}) != hasGUI { + t.Errorf("a magpie: link serves pages %v, want it to as the app opens it (%v)", !hasGUI, hasGUI) + } +} diff --git a/internal/plugin/host.go b/internal/plugin/host.go index f8a9ff0a4..8221682a8 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -13,6 +13,7 @@ import ( "fmt" "io" "log" + "maps" "net" "net/http" "os" @@ -1140,7 +1141,7 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) { // a plugin that is only gateway middleware or an agent runs in // magpie (internal/middleware, internal/agentplug), not here if !e.Off && !InMagpieOnly(Target(e.Spec)) { - items = append(items, item{e.Spec, Target(e.Spec), e.Options, Gateway(Target(e.Spec))}) + items = append(items, item{e.Spec, Target(e.Spec), hostOptions(Target(e.Spec), e.Options), Gateway(Target(e.Spec))}) } } var res struct { @@ -1180,6 +1181,50 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) { return h, false, nil } +// ServePages sets whether this magpie's host runs the services plugins' +// pages talk to (magpie.page.service), true until it is set. The app, +// magpie web, serve, tray and tui do; a command such as magpie plugin +// update doesn't, and its host may start while the app's host holds the +// service's port: a plugin that waits for its port then holds the +// command up, and goes on trying it in the background, to take it from +// the app's host when that restarts (#5187). +func ServePages(on bool) { noPageServices.Store(!on) } + +var noPageServices atomic.Bool + +// hostOptions are the options the host hands the plugin at target. In a +// magpie that runs no page services, a service the plugin's option +// moves is moved to a free port of its own, so the plugin's other parts +// load at once beside the app's host holding the real one. One no +// option moves is handed the plugin's options as they are. +func hostOptions(target string, options map[string]any) map[string]any { + if !noPageServices.Load() { + return options + } + w, _ := Window(target) + if w == nil || w.Page == nil || w.Page.Service == nil || w.Page.Service.Option == "" { + return options + } + port, err := freePort() + if err != nil { + return options + } + out := make(map[string]any, len(options)+1) + maps.Copy(out, options) + out[w.Page.Service.Option] = float64(port) + return out +} + +// freePort is a TCP port on 127.0.0.1 nothing listens on just now. +func freePort() (int, error) { + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + return 0, err + } + defer l.Close() + return l.Addr().(*net.TCPAddr).Port, nil +} + // pluginLoadWait bounds one plugin's load in the host, and // pluginListWait one provider's model list in a listing: a plugin stuck on // its vendor (a sign-in refused and tried again) is given up on by itself, diff --git a/internal/plugin/plugin_pageservice_test.go b/internal/plugin/plugin_pageservice_test.go new file mode 100644 index 000000000..8b0ded3f6 --- /dev/null +++ b/internal/plugin/plugin_pageservice_test.go @@ -0,0 +1,84 @@ +package plugin + +import ( + "context" + "net" + "path/filepath" + "strconv" + "testing" + "time" +) + +// holdPort listens on a free port on 127.0.0.1 for the test, as the app's +// host holds its page service's port, and gives the port. +func holdPort(t *testing.T) int { + t.Helper() + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { l.Close() }) + return l.Addr().(*net.TCPAddr).Port +} + +// #5187 (MYCF711): magpie plugin update, run while the app runs, started +// a host whose page-chat waited on the port the app's host holds. A host +// in a magpie that serves no pages loads such a plugin at once, its +// service on a port of its own, and leaves the held port alone. +func TestHostServingNoPagesLeavesHeldPort(t *testing.T) { + sandbox(t) + load := pluginLoadWait + pluginLoadWait = 10 * time.Second + ServePages(false) + t.Cleanup(func() { pluginLoadWait = load; ServePages(true) }) + port := holdPort(t) + t.Setenv("PAGESVC_PORT", strconv.Itoa(port)) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + abs, _ := filepath.Abs("testdata/pageservice") + if _, err := Add(ctx, abs); err != nil { + t.Fatal(err) + } + start := time.Now() + ls, err := Plugins(ctx) + took := time.Since(start) + if err != nil || len(ls) != 1 || ls[0].Error != "" { + t.Fatalf("Plugins = %+v, %v", ls, err) + } + // the load is a bun start and a listen; waiting on the held port, it + // takes the whole of pluginLoadWait + if took > 5*time.Second { + t.Errorf("the plugins were listed after %v: the host waited on the held port", took) + } +} + +// hostOptions moves the service only in a magpie that serves no pages, +// only through the option the page names, and keeps the plugin's other +// options; one that serves pages hands the options on as they are. +func TestHostOptionsMoveOnlyTheService(t *testing.T) { + t.Cleanup(func() { ServePages(true) }) + dir, _ := filepath.Abs("testdata/pageservice") + opts := map[string]any{"port": float64(3477), "other": "kept"} + + ServePages(true) + if got := hostOptions(dir, opts); got["port"] != float64(3477) || got["other"] != "kept" { + t.Errorf("serving pages, options = %v, want them as they are", got) + } + ServePages(false) + got := hostOptions(dir, opts) + p, ok := portOf(got["port"]) + if !ok || p == 3477 || got["other"] != "kept" { + t.Errorf("serving no pages, options = %v, want port moved and other kept", got) + } + if opts["port"] != float64(3477) { + t.Errorf("the plugin's own options were changed: %v", opts) + } + // a plugin with no page service, and one given by a file, as they are + fake, _ := filepath.Abs("testdata/fake/index.js") + plain, _ := filepath.Abs("testdata/options") + for _, target := range []string{fake, plain} { + if got := hostOptions(target, opts); got["port"] != float64(3477) { + t.Errorf("%s: options = %v, want them as they are", target, got) + } + } +} diff --git a/internal/plugin/testdata/pageservice/index.js b/internal/plugin/testdata/pageservice/index.js new file mode 100644 index 000000000..a51cae033 --- /dev/null +++ b/internal/plugin/testdata/pageservice/index.js @@ -0,0 +1,21 @@ +// A plugin whose page talks to a service its host part runs, as +// page-chat's (#5187): the service listens on options.port, else on +// $PAGESVC_PORT, and the plugin's load waits until it does, trying again +// while another program holds the port. It has no other part. +import { createServer } from "node:http" + +const listen = (port) => + new Promise((resolve) => { + const srv = createServer((_, res) => res.end("ok")) + srv.once("error", () => resolve(null)) + srv.listen(port, "127.0.0.1", () => resolve(srv)) + }) + +export const PageService = async (_input, options) => { + const port = Number(options?.port) > 0 ? Number(options.port) : Number(process.env.PAGESVC_PORT) + for (;;) { + if (await listen(port)) break + await new Promise((r) => setTimeout(r, 200)) + } + return {} +} diff --git a/internal/plugin/testdata/pageservice/package.json b/internal/plugin/testdata/pageservice/package.json new file mode 100644 index 000000000..649e65eeb --- /dev/null +++ b/internal/plugin/testdata/pageservice/package.json @@ -0,0 +1,9 @@ +{ + "name": "magpie-pageservice-test", + "version": "1.0.0", + "type": "module", + "main": "index.js", + "magpie": { + "page": { "title": "Page service", "file": "page.html", "service": { "port": 3477, "option": "port" } } + } +} diff --git a/internal/plugin/testdata/pageservice/page.html b/internal/plugin/testdata/pageservice/page.html new file mode 100644 index 000000000..56c0c72ba --- /dev/null +++ b/internal/plugin/testdata/pageservice/page.html @@ -0,0 +1 @@ +Page service

page service