plugin pages: a page the reader left is told, and let go after 10 minutes unless it keeps itself

A plugin's page kept its frame, with its scripts, timers and
connections, for as long as the window was open once it had been
looked at: show() only hid its view, and a frame in a hidden view isn't
hidden to itself (its visibilityState doesn't change), so a page
couldn't even pause on its own. Asked by the owner: is that by design?
Only the lazy first load was.

- The kernel's leave hook now reaches the page part: the page is told
  {event: "visibility", data: {visible}} as the reader leaves and comes
  back. The bridge has magpie.visible and magpie.onVisibility(fn); hello
  carries visible, for a page left before it said hello.
- A page left 10 minutes (IDLE_MS) has its frame removed and loads again
  when next opened. Back sooner, it is the same frame. Its hello timer is
  cleared, so nothing says it broke.
- magpie.page.keepAlive: true (plugin.PageSpec.KeepAlive, keepAlive in
  /api/plugin-pages) keeps a page however long, for one that works while
  no one looks at it. Anything but true is false, read as raw JSON so a
  wrong type never drops the package's page.
- plugin-runtime.md's page row says so.

Run on mote. The Go suite and most GUI files ran at this change on
557f51dbf. After rebasing onto 30cd39f19 (none of these files changed
upstream), the budgets, TestWindow* and the page GUI files ran again
at this tree:
- plugin-page-idle (new), plugin-page and plugin-panels, chromium and
  webkit: 14/14 at 557f51dbf. At the rebased tree, the first run was
  13/14: plugin-page's chromium "draws in its frame, shut in" was red
  once, and its assertion wasn't kept (#4589). After that: 42/42 over
  3 runs, then 16/16 chromium over 4.
- i18n-keys, plugin-actions, plugin-kinds-discover, plugin-kernel,
  plugin-replaced, plugin-proxy-page: 51/52. The red is i18n-keys'
  "Unmarked", the same on origin/main e0eb74987 (#4524).
- go test -timeout 45m ./...: every package ok except three reds, none in
  code touched here:
  - TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
    TestMainWindowCorners (#3949) fail the same on origin/main e0eb74987.
  - TestUnroutedHeldReportSaved (#4300) failed in the full run only.
    Alone, -count=5, it passes.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./..., go build ./..., gofmt -l: clean.

Broken by hand: with the leave hook taken out of the page part, the new
test is red in both engines.

Not tried: a real plugin page in the desktop app or WebKitGTK. The
IDLE_MS length (10 minutes) is a judgement, not measured.
This commit is contained in:
yetone
2026-10-31 22:39:37 +08:00
parent b75fa328ce
commit c30d3b7b63
7 changed files with 213 additions and 24 deletions
File diff suppressed because one or more lines are too long
+38 -5
View File
@@ -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;
+18 -1
View File
@@ -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 */ }
+10 -7
View File
@@ -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
}
@@ -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 = `<!doctype html><meta charset="utf-8"><script src="_magpie/bridge.js"></script>
<script>window.heard = []; magpie.onVisibility((v) => heard.push(v));</script><p>page</p>`;
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, []);
});
}
+16 -10
View File
@@ -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)) {
+10
View File
@@ -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