diff --git a/docs/subsystems/plugin-runtime.md b/docs/subsystems/plugin-runtime.md index 11599707c..536befd4c 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 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`. | 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/gui/assets/pluginpages.js b/internal/gui/assets/pluginpages.js index ae8cc7c18..0b943f8b3 100644 --- a/internal/gui/assets/pluginpages.js +++ b/internal/gui/assets/pluginpages.js @@ -19,7 +19,11 @@ if (mode !== "window") return; // how long a page has to say hello before it is taken as broken const HELLO_MS = 10e3; - const pages = new Map(); // key → { entry, frame, hello, timer } + // how long a page the reader left keeps its frame: one left longer is + // let go, and loads again the next time it is opened, unless its + // package keeps it (magpie.page.keepAlive) + const IDLE_MS = 10 * 60e3; + const pages = new Map(); // key → { entry, frame, hello, timer, shown, idle } const panels = new Map(); // frame → { entry, frame, context, hello, timer, body } let panelList = []; // /api/plugin-panels: every panel of a plugin on let ctx = null; @@ -58,12 +62,22 @@ return m[locale] || m[locale.split("-")[0]] || e.title; } + // a page is told when the reader leaves it and comes back + // (magpie.onVisibility): a frame in a hidden view isn't hidden to itself + function seen(p, visible) { + if (p.shown === visible) return; + p.shown = visible; + if (p.hello) post(p.frame?.contentWindow, { event: "visibility", data: { visible } }); + } + // the page's frame, made the first time the page is opened (and again - // after Try again): a plugin's page costs nothing until it is looked at + // after Try again, or once it was let go): a plugin's page costs + // nothing until it is looked at function open(key) { const p = pages.get(key); if (!p) return undefined; - if (p.frame?.isConnected) return p.ready; + clearTimeout(p.idle); + if (p.frame?.isConnected) { seen(p, true); return p.ready; } const main = $("#view-" + key); const f = document.createElement("iframe"); f.className = "plugin-frame"; @@ -76,6 +90,7 @@ f.src = p.entry.url; p.frame = f; p.hello = false; + p.shown = true; p.ready = new Promise((resolve, reject) => { p.said = resolve; clearTimeout(p.timer); @@ -85,6 +100,24 @@ return p.ready; } + // the reader went to another page: this one is told, and its frame is + // let go after IDLE_MS there, with what it holds (its scripts, timers, + // connections); one that is back by then, or keeps itself, stays + function leave(key) { + const p = pages.get(key); + if (!p?.frame) return; + seen(p, false); + clearTimeout(p.idle); + if (p.entry.keepAlive) return; + p.idle = setTimeout(() => { + if (view === key || !p.frame) return; + clearTimeout(p.timer); + p.frame.remove(); + p.frame = null; + p.hello = false; + }, IDLE_MS); + } + async function answer(p, m) { const e = p.entry; switch (m.method) { @@ -95,7 +128,7 @@ // a panel is told where it is: the provider whose editor it is in; // a page served to a browser, where its local service is through // this server (pageservice.go), relative to the page - return { ...theme(), context: p.context || {}, service: (!p.context && e.service) || "" }; + return { ...theme(), context: p.context || {}, service: (!p.context && e.service) || "", visible: p.shown ?? true }; case "theme": return theme(); case "options.get": @@ -211,7 +244,7 @@ if (!p) { p = { entry: e }; pages.set(e.key, p); - ctx.slots.add("page", { key: e.key, title: titled(e), html: "", mount(main) { main.classList.add("plugin-page"); p.frame = null; }, open: () => open(e.key) }); + ctx.slots.add("page", { key: e.key, title: titled(e), html: "", mount(main) { main.classList.add("plugin-page"); p.frame = null; }, open: () => open(e.key), leave: () => leave(e.key) }); } else if (p.entry.url !== e.url || p.gone) { p.frame?.remove(); p.frame = null; diff --git a/internal/gui/pagebridge.js b/internal/gui/pagebridge.js index d4aca0fa3..93c7ffa74 100644 --- a/internal/gui/pagebridge.js +++ b/internal/gui/pagebridge.js @@ -24,6 +24,14 @@ // when one of its magpie.actions is picked // in a row's menu (P6); one picked before // fn was given waits for it +// magpie.visible false while the reader is on another of +// the window's pages +// magpie.onVisibility(fn) fn(visible) as the reader leaves the +// page and comes back, to pause what only +// matters while it is seen; a page left +// 10 minutes is let go, and loads again +// when next opened, unless package.json +// says magpie.page.keepAlive // // A panel (magpie.panels) is as tall as what it draws: the window is told // its height as it changes. @@ -41,6 +49,7 @@ const waiting = new Map(); let next = 0; const themed = []; + const watched = []; let acting = null; const acted = []; function call(method, params) { @@ -68,6 +77,11 @@ for (const fn of themed) { try { fn(m.data); } catch (err) { report(err); } } return; } + if (m.event === "visibility") { + api.visible = !!m.data?.visible; + for (const fn of watched) { try { fn(api.visible); } catch (err) { report(err); } } + return; + } if (m.event === "action") { if (acting) act(m.data); else acted.push(m.data); return; @@ -102,7 +116,9 @@ theme: null, context: {}, service: "", + visible: true, onTheme(fn) { themed.push(fn); }, + onVisibility(fn) { watched.push(fn); }, onAction(fn) { acting = fn; for (const d of acted.splice(0)) act(d); @@ -113,8 +129,9 @@ }, read: (name, params) => call("read", { name, params }), }; - api.ready = call("hello").then(({ context, service, ...theme }) => { + api.ready = call("hello").then(({ context, service, visible, ...theme }) => { api.theme = theme; + if (visible === false) api.visible = false; api.context = context || {}; api.service = ""; try { if (service) api.service = new URL(service, location.href).href; } catch { /* none */ } diff --git a/internal/gui/pluginpage.go b/internal/gui/pluginpage.go index cd50c11bd..e2d1fd67e 100644 --- a/internal/gui/pluginpage.go +++ b/internal/gui/pluginpage.go @@ -86,12 +86,15 @@ type pluginPage struct { // (plugin.ServiceSpec) through this server, relative to the page's own // address: only on a page served to a browser (servePageService) Service string `json:"service,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) - service *plugin.ServiceSpec - options map[string]any // its plugin's, as plugins.json keeps them + // KeepAlive keeps its frame while the reader is on another page + // (plugin.PageSpec); else the window lets it go after a while hidden + KeepAlive bool `json:"keepAlive,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) + service *plugin.ServiceSpec + options map[string]any // its plugin's, as plugins.json keeps them } // pluginAction is an item a plugin's page adds to one of magpie's menus. @@ -156,7 +159,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), file: filepath.ToSlash(rel), hosted: !only, options: e.Options} + URL: pluginPagePrefix + tok + "/" + filepath.ToSlash(rel), file: filepath.ToSlash(rel), hosted: !only, options: e.Options, KeepAlive: spec.KeepAlive} if !only { p.service = spec.Service } diff --git a/internal/gui/tests/plugin-page-idle.test.cjs b/internal/gui/tests/plugin-page-idle.test.cjs new file mode 100644 index 000000000..3345f84ec --- /dev/null +++ b/internal/gui/tests/plugin-page-idle.test.cjs @@ -0,0 +1,120 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A plugin's page the reader left (pluginpages.js): a frame in a hidden view +// isn't hidden to itself, so the page is told as the reader leaves and +// comes back (magpie.onVisibility, magpie.visible), and its frame, with its +// scripts, timers and connections, is let go after 10 minutes away. Back +// sooner, it is the same frame; opened after, it loads again. A page whose +// package says magpie.page.keepAlive keeps its frame however long. A clock +// stands in for time, so nothing waits; the API is faked. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const bridge = path.resolve(__dirname, "../pagebridge.js"); + +const IDLE = "e".repeat(32), KEEP = "f".repeat(32); +const entry = (tok, name, more = {}) => ({ + spec: "/x/" + name, name, key: "plugin-" + name, title: name, reads: [], + url: `/_magpie/plugin/${tok}/index.html`, ...more, +}); +const pages = [entry(IDLE, "idle"), entry(KEEP, "keep", { keepAlive: true })]; +// what the page heard, kept where the test reads it +const PAGE = ` +

page

`; + +async function server(route) { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"en",theme:"light",web:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang: "en", theme: "light" } }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [] }); + if (url.pathname === "/api/groups") return json({ groups: [], pools: [] }); + if (url.pathname === "/api/plugin-pages") return json(pages); + if (url.pathname === "/api/plugin-panels") return json([]); + if (url.pathname.startsWith("/api/")) return json({}); + const m = url.pathname.match(/^\/_magpie\/plugin\/([0-9a-f]{32})\/(.+)$/); + if (m) { + const headers = { "X-Content-Type-Options": "nosniff", "Cache-Control": "no-cache" }; + if (m[2] === "_magpie/bridge.js") return route.fulfill({ headers: { ...headers, "Content-Type": "text/javascript" }, body: await fs.readFile(bridge) }); + if (m[2] === "index.html") return route.fulfill({ headers: { ...headers, "Content-Type": "text/html" }, body: PAGE }); + return route.fulfill({ status: 404, body: "" }); + } + if (url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } +} + +const MIN = 60e3; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: a page the reader left is told, and let go after a while unless it keeps itself`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const context = await browser.newContext({ viewport: { width: 1100, height: 700 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(8000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.clock.install({ time: Date.now() }); + await page.route("**/*", server); + await page.goto("http://magpie.test/"); + await page.locator("#nav button[data-plugin-page]").nth(1).waitFor({ state: "attached" }); + + const frames = (key) => page.locator(`#view-plugin-${key} iframe.plugin-frame`).count(); + // the page's frame once it has said hello, marked so a new one shows + async function opened(key, tok) { + await page.evaluate((k) => show("plugin-" + k), key); + await page.waitForFunction((tok) => [...document.querySelectorAll("iframe.plugin-frame")].some((f) => f.src.includes(tok)), tok); + let f; + for (let i = 0; i < 100 && !(f = page.frames().find((x) => x.url().includes(tok))); i++) await page.waitForTimeout(50); + await f.waitForFunction(() => window.magpie?.theme); + return f; + } + const pass = async (ms) => { await page.clock.runFor(ms); await page.waitForTimeout(100); }; + + const idle = await opened("idle", IDLE); + await idle.evaluate(() => { window.mark = 1; }); + assert.deepEqual(await idle.evaluate(() => [magpie.visible, heard]), [true, []], "open: seen, nothing heard yet"); + + // left: told at once, and its frame still there short of 10 minutes + await page.evaluate(() => show("agents")); + await idle.waitForFunction(() => heard.length === 1); + assert.deepEqual(await idle.evaluate(() => [magpie.visible, heard]), [false, [false]], "left: told it is hidden"); + await pass(9 * MIN); + assert.equal(await frames("idle"), 1, "kept 9 minutes away"); + + // back before then: the same frame, told it is seen, its timer done + await page.evaluate(() => show("plugin-idle")); + await idle.waitForFunction(() => heard.length === 2); + assert.deepEqual(await idle.evaluate(() => [magpie.visible, heard, window.mark]), [true, [false, true], 1], "back: the same frame, seen"); + await pass(11 * MIN); + assert.equal(await frames("idle"), 1, "a page the reader is on is never let go"); + + // a page that keeps itself, left beside it + const keep = await opened("keep", KEEP); + await keep.evaluate(() => { window.mark = 2; }); + await page.evaluate(() => show("agents")); + await keep.waitForFunction(() => heard.length === 1); + await pass(10 * MIN + 1000); + assert.equal(await frames("idle"), 0, "let go 10 minutes after it was left"); + assert.equal(await frames("keep"), 1, "keepAlive: kept"); + assert.deepEqual(await keep.evaluate(() => [magpie.visible, heard, window.mark]), [false, [false], 2], "keepAlive: told, still running"); + await pass(60 * MIN); + assert.equal(await frames("keep"), 1, "keepAlive: kept an hour on"); + + // opened again: it loads again, and is seen + const again = await opened("idle", IDLE); + assert.deepEqual(await again.evaluate(() => [magpie.visible, heard, window.mark]), [true, [], undefined], "opened after: a new frame"); + assert.equal(await frames("idle"), 1); + // and nothing the window held for the one let go says it broke + await pass(11e3); + assert.equal(await page.locator("#view-plugin-idle .slot-error").count(), 0, "no 'stopped working'"); + assert.deepEqual(errors, []); + }); +} diff --git a/internal/plugin/page.go b/internal/plugin/page.go index b7d4d238d..d07d313ec 100644 --- a/internal/plugin/page.go +++ b/internal/plugin/page.go @@ -46,6 +46,11 @@ type PageSpec struct { // its own address to a browser on another computer, where the // service's 127.0.0.1 is that computer's own. Service *ServiceSpec + // KeepAlive keeps the page's frame while the reader is on another + // page, however long (magpie.page.keepAlive true; anything else is + // false, never a package that doesn't parse): a page that works when + // no one looks at it. Others are let go after a while hidden. + KeepAlive bool } // ServiceSpec is a page's local service: an HTTP server on 127.0.0.1 at @@ -147,15 +152,16 @@ func Window(target string) (w *WindowSpec, only bool) { 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"` - ID string `json:"id"` - Menu string `json:"menu"` - Service json.RawMessage `json:"service"` + 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"` + ID string `json:"id"` + Menu string `json:"menu"` + Service json.RawMessage `json:"service"` + KeepAlive json.RawMessage `json:"keepAlive"` } var pkg struct { Main string `json:"main"` @@ -173,7 +179,7 @@ func Window(target string) (w *WindowSpec, only bool) { 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)} + p := &PageSpec{Title: strings.TrimSpace(pg.Title), Titles: titles(pg.Titles), File: file, Dir: filepath.Dir(file), KeepAlive: string(pg.KeepAlive) == "true"} // 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)) { diff --git a/internal/plugin/page_test.go b/internal/plugin/page_test.go index 22ba54725..c23634cf9 100644 --- a/internal/plugin/page_test.go +++ b/internal/plugin/page_test.go @@ -138,6 +138,16 @@ func TestWindowPanels(t *testing.T) { t.Errorf("replaces %q: %+v, want %q", replaces, w, want) } } + + // magpie.page.keepAlive is true or not there: a value of another kind + // is false, and the page is still read + for keep, want := range map[string]bool{`true`: true, `false`: false, `"true"`: false, `1`: false, `{}`: false, `null`: false} { + write(`{"name":"p","magpie":{"page":{"file":"ui/page.html","keepAlive":` + keep + `}}}`) + w, _ := Window(d) + if w == nil || w.Page == nil || w.Page.KeepAlive != want { + t.Errorf("keepAlive %s: %+v, want %v", keep, w, want) + } + } } // A page's and a panel's titles by language (magpie.page.titles) are kept