gui: a Mac window out of sight 30s lets go of its layers (#5530)

A window hidden with orderOut keeps every layer's buffers in WebContent:
WebKit stops drawing a hidden page but holds what it last drew. The
reporter's hidden window held 1133 MB of graphics in 335 buffers
(140 RenderLayerBacking), and it stayed after 90s idle.

Out of sight 30s (the window only, never the tray panel), the page gets
magpie-asleep: content-visibility: hidden on body, laid out at once,
since a hidden page runs no rendering update of its own. WebKit then
drops every layer but the root's. Shown again, the class goes as the window
is told it is back, and the content and scroll positions are as they
were. Telling the page before Show was tried and left out: the page then
reads WebKit's own document.hidden, still true, as it is told it is shown
(TestPanelHiddenByWailsMarksPageOutOfSight went red). Shown within 30s, nothing
changes.

Measured on mote (macOS 27.2, 1x display, real `make app` build, sandbox
HOME, window 1470x820, 40 providers x 30 models; WebKit's occlusion check
turned off in the probe since mote's screen is locked, else the page never
draws at all):
- Plugins (688 buttons), hidden: before 50 PlatformCALayerRemote, 10
  RenderLayerBacking, 27.0 MB dirty graphics, unchanged at 70s (control,
  sleep cleared); after 30s asleep 19 / 1, 20.3 MB.
- Providers (280 buttons): 43 / 7, 14.4 MB hidden; asleep 16 / 1 but
  18.4 MB: the root tiles are drawn again blank and are no longer
  volatile, which costs about one window's tiles when a page has few
  layers. It saves every other layer's buffers, which is the reporter's
  case.
- Shown again: 50 / 10 layers, frames running, content and scroll kept.
Not reproduced: the reporter's 140 large backings; which page made them is
asked on the issue. Taking the webview out of its window while hidden
freed 5 MB more and was left out (a native change for little).

Ran on mote: window-asleep (new), window-visibility and held-animations
in chromium and webkit, all ok. Broken by hand, each red in both engines
in the test that guards it: no sleep timer (the 30s test), the panel put
asleep too (the panel test), the timer not cleared when shown (the
shown-within-30s test). go test ./internal/gui: ok but
TestMainWindowCorners, red the same at origin/main f7cf17290 (#3949);
the budgets and the AppKit visibility tests ok. go vet, GOOS=linux go
vet -tags nogui, GOOS=windows go vet, gofmt: clean. The whole GUI suite
and the full Go suite run after the push; their results go on #5530.
Not tried: a Retina display, the reporter's macOS 26.6, Linux and
Windows (the class is set only when the window is told it is hidden,
which only macOS does).

The core scripts stay in their budget with four comments in app.js cut.

Reported-by: faithleysath
Reported-by: Matrix (Discord)
This commit is contained in:
yetone
2026-11-07 00:09:10 +08:00
parent f7cf17290c
commit 54dc257f10
4 changed files with 114 additions and 16 deletions
+3
View File
@@ -122,6 +122,9 @@ html.magpie-out-of-sight,
html.magpie-out-of-sight *,
html.magpie-out-of-sight *::before,
html.magpie-out-of-sight *::after { animation-play-state: paused !important; }
/* out of sight a while: nothing is drawn, so WebKit lets go of every
layer's buffers, which it keeps for a hidden window (#5530) */
html.magpie-asleep body { content-visibility: hidden; }
body {
font: var(--ui-style, normal) var(--ui-weight, 400) 13px/1.4 var(--ui-font, var(--font)); font-stretch: var(--ui-stretch, 100%);
color: var(--fg);
+15 -15
View File
@@ -6,7 +6,7 @@ const mode = params.get("mode") || "window";
// focus without a scroll, as every focus call here asks
const NO_SCROLL = { preventScroll: true };
// a Mac window hidden by orderOut leaves its page drawing: the app says so (#4293)
let outOfSight = false;
let outOfSight = false, asleep;
for (const [k, off] of [["hidden", true], ["visibilityState", "hidden"]]) {
const own = Object.getOwnPropertyDescriptor(Document.prototype, k)?.get;
try { own && Object.defineProperty(Document.prototype, k, { configurable: true, get() { return outOfSight ? off : own.call(this); } }); } catch {}
@@ -14,33 +14,33 @@ for (const [k, off] of [["hidden", true], ["visibilityState", "hidden"]]) {
window.magpieWindowVisibility = (v) => {
if (outOfSight !== v) return;
outOfSight = !v;
document.documentElement.classList.toggle("magpie-out-of-sight", outOfSight);
const c = document.documentElement.classList;
c.toggle("magpie-out-of-sight", outOfSight);
// out of sight 30s: let go of layers, laid out now since a hidden page
// never draws (#5530)
clearTimeout(asleep); c.remove("magpie-asleep");
if (outOfSight && mode == "window") asleep = setTimeout(() => { c.add("magpie-asleep"); document.body.offsetWidth; }, 3e4);
document.dispatchEvent(new Event("visibilitychange"));
};
addEventListener("focus", () => magpieWindowVisibility(true)); // focused is on screen
// kept: magpie.<k> in localStorage, read as JSON; d when it holds none, or
// not d's kind, or can't be read. keep writes one, for this time only if
// it can't be kept
// kept: magpie.<k> in localStorage as JSON; d when none, not d's kind or
// unreadable. keep writes one, for this time only if it can't be kept
function kept(k, d) { try { const v = JSON.parse(localStorage.getItem("magpie." + k)); return v && typeof v == typeof d && Array.isArray(v) == Array.isArray(d) ? v : d; } catch { return d; } }
function keep(k, v) { try { localStorage.setItem("magpie." + k, JSON.stringify(v)); } catch {} }
// The panel loads Wails for ExecJS readiness, but stays attached to the tray.
// On Linux it is dragged by its header like the window: a Wayland window
// can't be put by the icon, so KWin places it, and since it has no KWin
// title bar (#1283) the header is the only handle it has (#1430).
// The panel stays attached to the tray; on Linux it is dragged by its
// header, as KWin places a Wayland window with no title bar (#1283, #1430).
if (mode === "panel" && !document.body.classList.contains("linux")) $("header.top").style.setProperty("--wails-draggable", "no-drag");
// `magpie web`: the page in a browser tab, with no window of the app's
// around it — it opens links itself, and what is the desktop's is left out
const web = !!window.bootPrefs?.web;
// the version that served this page, which servedAnew compares the one
// answering now with
// the version that served this page, for servedAnew
const pageVersion = window.bootPrefs?.version || "";
// magpie web seen from another computer: localhost is the viewer's (curtinp118)
const remotePage = web && !/^(localhost|127(\.\d+){3}|\[::1\]|::1)$/i.test(location.hostname);
// layout.js applies the mode and platform before the header can paint.
// Gateway mode (gatewaymode.go): magpie web on a server that is only the
// gateway for other computers' agents leaves out this computer's agents'
// pages — Agents, the Library but its MCP tab — and their settings;
// Settings › General turns it off, and they are back.
// Gateway mode (gatewaymode.go): magpie web serving only other computers'
// agents leaves out this one's agents' pages (Agents, the Library but MCP)
// and settings, until Settings › General turns it off.
let gatewayMode = web && !!window.bootPrefs?.gateway;
const GATEWAY_HIDES = ["agents"];
// Plugins › Built-in (builtins.go, Lxxyx): the window's parts switched off,
File diff suppressed because one or more lines are too long
+95
View File
@@ -0,0 +1,95 @@
// A Mac window hidden with orderOut keeps its page's layer buffers
// (#5530: 1133 MB in 335 buffers for a reporter). Out of sight 30s, the
// window's page is put asleep (content-visibility: hidden on body), so
// WebKit lets go of every layer but the root's; shown, it draws again with
// its content and scroll positions as they were.
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 alternateAppJS = process.env.MAGPIE_APP_JS;
function serve() {
const state = { agents: [], profiles: [], settings: { lang: "en", theme: "light" } };
return async (route) => {
const req = route.request();
const url = new URL(req.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:true};' });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname.startsWith("/api/")) return json({});
if (url.pathname === "/app.js" && alternateAppJS) {
return route.fulfill({ body: await fs.readFile(alternateAppJS), contentType: "text/javascript" });
}
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)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
async function open(t, mode) {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await browser.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
await page.clock.install();
await page.route("**/*", serve());
await page.goto(`http://magpie.test/?view=providers${mode ? "&mode=" + mode : ""}`);
await page.waitForFunction(() => typeof window.magpieWindowVisibility === "function");
return page;
}
const look = (page) => page.evaluate(() => ({
asleep: document.documentElement.classList.contains("magpie-asleep"),
drawn: getComputedStyle(document.body).contentVisibility !== "hidden",
scrolled: document.querySelector("#sleepProbe")?.scrollTop,
}));
test(`${engine}: a window out of sight 30s lets go of its layers, and draws again shown`, async (t) => {
const page = await open(t);
await page.evaluate(() => {
const box = document.createElement("div");
box.id = "sleepProbe";
box.style.cssText = "position:fixed;top:0;left:0;width:200px;height:100px;overflow:auto";
box.innerHTML = '<div style="height:2000px">deep</div>';
document.body.append(box);
box.scrollTop = 600;
window.magpieWindowVisibility(false);
});
await page.clock.runFor(29000);
assert.deepEqual(await look(page), { asleep: false, drawn: true, scrolled: 600 });
await page.clock.runFor(1500);
const asleep = await look(page);
assert.equal(asleep.asleep, true);
if (await page.evaluate(() => CSS.supports("content-visibility", "hidden"))) assert.equal(asleep.drawn, false);
await page.evaluate(() => window.magpieWindowVisibility(true));
assert.deepEqual(await look(page), { asleep: false, drawn: true, scrolled: 600 });
assert.equal(await page.evaluate(() => document.querySelector("#sleepProbe").textContent), "deep");
});
test(`${engine}: a window shown again within 30s is never put asleep`, async (t) => {
const page = await open(t);
await page.evaluate(() => window.magpieWindowVisibility(false));
await page.clock.runFor(20000);
await page.evaluate(() => window.magpieWindowVisibility(true));
await page.clock.runFor(60000);
assert.equal((await look(page)).asleep, false);
// hidden again, the 30s start over
await page.evaluate(() => window.magpieWindowVisibility(false));
await page.clock.runFor(20000);
assert.equal((await look(page)).asleep, false);
});
test(`${engine}: the tray panel is never put asleep`, async (t) => {
const page = await open(t, "panel");
await page.evaluate(() => window.magpieWindowVisibility(false));
await page.clock.runFor(60000);
assert.equal((await look(page)).asleep, false);
});
}