gui: the Mac panel's page is told when Wails hides it, so it follows Settings' units (blrbrzkj)

blrbrzkj on Discord: Settings said ¥ 人民币 and 中文(万 / 亿), while the
tray panel's Usage tab still showed ≈$7.18 and 16M.

On the Mac a page in an ordered-out window keeps drawing, so magpie tells
it when it is hidden (hideWebview) and shown (showWebview), and the page
reloads its state, settings included, on the shown signal. The panel is
mostly closed by a click elsewhere, which Wails' HideOnFocusLost does
with a plain Hide, and by Escape (HideOnEscape), likewise. The page was
never told it was hidden there, so the shown signal was a no-op
(magpieWindowVisibility returns early when it was never told otherwise),
and the panel kept the currency and number units it was first drawn
with until magpie restarted.

sayWailsHides (windowvisibility.go), on the panel: on the Mac the page is
told on WindowLostFocus, as hideWebview tells it, and Escape hides the
panel through hideWebview. Other systems are unchanged: WebView2 and
WebKitGTK mark a hidden window's page hidden themselves.

Tests:
- TestPanelHiddenByWailsMarksPageOutOfSight (AppKit, darwin): makes the
  real panel (h.makePanel), closes it by a WindowLostFocus event and by
  the Escape key binding, as Wails does, shows it with showWebview, and
  checks the page saw itself hidden and marked. The probe page now
  reports what it saw when it is told it is shown, so a native hidden
  event before the told one can't be the record it sends.
- panel-units-follow.test.cjs: the page half. A panel open on its Usage
  tab in $ and K/M; Settings picks ¥ and 万 / 亿; hidden and shown, the
  panel re-reads the state and shows ≈¥185, 15.4 亿 (億 in zh-TW) and a
  万 axis, then back to ≈$26.40 and 1.54B. zh, en, zh-TW, ja, de;
  Chromium and WebKit.

Run on mote (macOS 27.2), at this tree:
- go test -run 'TestClosingWindowMarksPageOutOfSight|TestPanelHiddenByWailsMarksPageOutOfSight' ./internal/gui/: ok
- go vet ./internal/gui/, GOOS=linux go vet -tags nogui, GOOS=windows go vet: ok; gofmt -l: nothing
- node --test panel-units-follow, window-visibility, number-units: 20/20

Broken by hand:
- sayWailsHides(w) not called: the AppKit test times out with no hidden
  report.
- only its Escape binding removed: red, "hidden=true marked=false
  play=running".
- the page's visibilitychange without loadBack (a copy of the assets):
  panel-units-follow red, "shown again, the panel reads the state again".
- The panel test written to show without a told hide (the old Mac path)
  was 0/12 on the unchanged page, which is how the cause was found.

Not tried: the real tray panel by hand on a Mac (the AppKit test makes
the real panel window but no status item); blrbrzkj's system isn't
known, and on Windows and Linux the page is marked hidden by the webview
itself, so this changes nothing there.
This commit is contained in:
yetone
2026-11-04 16:32:55 +08:00
parent 75e30625f5
commit 2ba044aa66
4 changed files with 206 additions and 20 deletions
+1
View File
@@ -137,6 +137,7 @@ func (h *host) makePanel() *application.WebviewWindow {
trayOwnClicks()
w.OnWindowEvent(events.Mac.WindowShow, func(*application.WindowEvent) { trayHighlight(true) })
w.OnWindowEvent(events.Mac.WindowHide, func(*application.WindowEvent) { trayHighlight(false) })
sayWailsHides(w)
// The system's close hides the panel, as Escape does: a title bar's X
// (KWin's, #1283), Alt+F4 or the window manager's close key. Closed, it
// was gone while the tray still opened it, and the icon did nothing
@@ -0,0 +1,136 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// The tray panel follows Settings' units (blrbrzkj on Discord, two
// screenshots: Settings said ¥ 人民币 and 中文(万 / 亿), the panel's Usage
// tab still ≈$7.18 and 16M). The panel is open on its Usage tab while
// Settings, in the window, picks another currency and number units; when
// the panel is shown again it reads the settings again, and its cost, its
// counts and its chart's axis say what was picked, not what was picked
// when it was first drawn: ¥ at the rate magpie has, 万 / 亿. Then back to
// $ and K / M / B. Each language: 万 / 亿 is Chinese's alone, so the
// others check the currency only. Chromium and WebKit; no backend, 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(process.env.MAGPIE_PANEL_UNITS_ASSETS || path.join(__dirname, "../assets"));
const midnight = new Date();
midnight.setHours(0, 0, 0, 0);
// a day of one provider: 7000 万 (70M) tokens and $1.2 an hour, from 2am
function ledger() {
const series = Array.from({ length: 24 }, (_, h) => {
const on = h >= 2 ? 1 : 0;
const part = { calls: 9 * on, tokens: 7e7 * on, cost: 1.2 * on };
const by = { provider: { zcode: part }, agent: { claude: part }, model: { "glm-5": part } };
return { label: String(h), time: new Date(midnight.getTime() + h * 3600e3).toISOString(), calls: part.calls, errors: 0,
input: part.tokens * 0.01, output: part.tokens * 0.005, cache_write: part.tokens * 0.05, cache_read: part.tokens * 0.935, cost: part.cost, by };
});
const sum = (k) => series.reduce((a, p) => a + p[k], 0);
const tot = { calls: sum("calls"), errors: 0, input: sum("input"), output: sum("output"), cache_write: sum("cache_write"), cache_read: sum("cache_read"), reasoning: 0, cost: sum("cost"), unpriced: 0 };
const share = (id, name, icon) => ({ id, name, icon, ...tot });
return {
period: "today", rows: [], offset: 0, total: 1, ...tot, bucket: "hour", series,
by: { provider: [share("zcode", "ZCode", "generic")], agent: [share("claude", "Claude Code", "claudecode-color")], model: [share("glm-5", "glm-5", "")] },
agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }], providers: [{ id: "zcode", name: "ZCode", icon: "generic" }],
};
}
// /api/state as magpie answers it: the settings, and beside them the rate
// a cny cost is shown at (none looked up for usd)
function serve(lang, store) {
return async (route) => {
const req = route.request(), 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:"${lang}",theme:"light"};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") { store.stateReads++; return json({ agents: [], profiles: [], settings: store.cur, fx: store.cur.currency === "cny" ? { rate: 7, at: new Date().toISOString(), stale: false } : { rate: 0 } }); }
if (url.pathname === "/api/settings") return json(store.cur);
if (url.pathname === "/api/usage/requests") return json(ledger());
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/gateway/trace" && url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3));
if (url.pathname === "/api/gateway/trace") return json({ mine: true, now: new Date().toISOString(), seq: 0, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true, window: true } });
if (url.pathname.startsWith("/api/")) return json({});
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 });
};
}
// the panel's Usage tab: its tokens, its cost, and its chart's side labels
async function shown(p) {
return p.evaluate(() => {
const v = [...document.querySelectorAll("#panelUsage .pu-tot .blk .v")].map((x) => x.textContent.trim());
const axis = [...document.querySelectorAll("#panelUsage .pu-card .led-chart svg text.axis[text-anchor=end]")].map((x) => x.textContent.trim());
return { tokens: v[0], cost: v[2], axis };
});
}
// the panel hidden and shown again, as the Mac's page is told it is: by
// hideWebview and showWebview, and when Wails hides it itself on a click
// elsewhere or Escape, by sayWailsHides (windowvisibility.go; its AppKit
// half is TestPanelHiddenByWailsMarksPageOutOfSight)
async function hideAndShow(p, store) {
const before = store.stateReads;
await p.evaluate(() => window.magpieWindowVisibility(false));
await p.evaluate(() => window.magpieWindowVisibility(true));
for (let i = 0; i < 100 && store.stateReads === before; i++) await p.waitForTimeout(20);
assert(store.stateReads > before, "shown again, the panel reads the state again");
}
const LANGS = (process.env.MAGPIE_LANGS || "zh,en,zh-TW,ja,de").split(",");
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": the tray panel's Usage tab follows Settings' currency and number units", async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of LANGS) {
await t.test(lang, async () => {
const chinese = lang === "zh" || lang === "zh-TW";
const store = { cur: { lang, theme: "light", currency: "usd", chineseUnits: false, tray: "panel" }, stateReads: 0 };
const ctx = await browser.newContext({ viewport: { width: 380, height: 560 }, reducedMotion: "reduce" });
const p = await ctx.newPage();
const errors = [];
p.setDefaultTimeout(5000);
p.setDefaultNavigationTimeout(60000);
p.on("pageerror", (e) => errors.push(e.message));
await p.route("**/*", serve(lang, store));
await p.goto("http://magpie.test/?mode=panel");
await p.locator('[data-ptab="stats"]').click();
await p.locator("#panelUsage .pu-card .led-chart svg").waitFor();
let s = await shown(p);
assert.equal(s.tokens, "1.54B", lang + ": K/M/B at first");
assert.equal(s.cost, "≈$26.40", lang + ": $ at first");
// Settings, in the window, picks ¥ and 万 / 亿
store.cur = { ...store.cur, currency: "cny", chineseUnits: true };
await hideAndShow(p, store);
await p.waitForFunction(() => /¥/.test(document.querySelectorAll("#panelUsage .pu-tot .blk .v")[2]?.textContent || ""), null, { timeout: 3000 }).catch(() => {});
s = await shown(p);
assert.equal(s.cost, "≈¥185", lang + ": the cost in yuan once Settings picks ¥, got " + s.cost);
if (chinese) {
assert.equal(s.tokens, "15.4 " + (lang === "zh" ? "亿" : "億"), lang + ": the tokens in 万/亿, got " + s.tokens);
assert(s.axis.some((x) => /万|萬/.test(x)), lang + ": the chart's axis in 万, got " + s.axis);
} else {
assert.equal(s.tokens, "1.54B", lang + ": K/M/B, 万/亿 being Chinese's alone");
}
// and back
store.cur = { ...store.cur, currency: "usd", chineseUnits: false };
await hideAndShow(p, store);
await p.waitForFunction(() => /\$/.test(document.querySelectorAll("#panelUsage .pu-tot .blk .v")[2]?.textContent || ""), null, { timeout: 3000 }).catch(() => {});
s = await shown(p);
assert.equal(s.cost, "≈$26.40", lang + ": back in dollars, got " + s.cost);
assert.equal(s.tokens, "1.54B", lang + ": back in K/M/B, got " + s.tokens);
assert(!s.axis.some((x) => /万|萬|亿|億/.test(x)), lang + ": the axis back in K/M/B, got " + s.axis);
assert.deepEqual(errors, []);
await ctx.close();
});
}
});
}
+55 -20
View File
@@ -27,8 +27,21 @@ func TestClosingWindowMarksPageOutOfSight(t *testing.T) {
}
}
// The tray panel is hidden by Wails itself more often than by magpie: on a
// click elsewhere (HideOnFocusLost) and on Escape, a plain Hide that
// hideWebview never sees. Its page is told all the same, or it is never
// told it is back and keeps what it was drawn with: Settings' currency and
// number units never reached it (blrbrzkj on Discord).
func TestPanelHiddenByWailsMarksPageOutOfSight(t *testing.T) {
out, err := runAppKit(t, 30*time.Second, []string{"MAGPIE_TEST_WINDOW_VISIBILITY=panel"})
if err != nil || !strings.Contains(string(out), "window visibility: ok") {
t.Fatalf("panel visibility: %v\n%s", err, out)
}
}
func init() {
if os.Getenv("MAGPIE_TEST_WINDOW_VISIBILITY") != "1" {
which := os.Getenv("MAGPIE_TEST_WINDOW_VISIBILITY")
if which != "1" && which != "panel" {
return
}
ready := make(chan struct{}, 1)
@@ -46,6 +59,12 @@ html.magpie-out-of-sight #probe{animation-play-state:paused!important}
</style><i id="probe"></i><script>
const probe = document.querySelector("#probe");
window.magpieWindowVisibility = (visible) => {
// shown again: what it last saw while hidden, once
const seen = visible && localStorage.getItem("hiddenProbe");
if (seen) {
localStorage.removeItem("hiddenProbe");
fetch("/report?probe=" + encodeURIComponent(seen));
}
document.documentElement.classList.toggle("magpie-out-of-sight", !visible);
document.dispatchEvent(new Event("visibilitychange"));
};
@@ -59,10 +78,6 @@ document.addEventListener("visibilitychange", () => {
}));
}
});
setInterval(() => {
const probe = localStorage.getItem("hiddenProbe");
if (probe) fetch("/report?probe=" + encodeURIComponent(probe));
}, 100);
fetch("/ready");
</script>`)
case "/ready":
@@ -96,10 +111,39 @@ fetch("/ready");
return nil
}
}
// each way the window is closed: the main window by magpie; the panel
// by Wails, on a click elsewhere and on Escape
closes := map[string][]func(*host, *application.WebviewWindow){
"1": {func(h *host, _ *application.WebviewWindow) { application.InvokeSync(h.hideMain) }},
"panel": {
func(_ *host, w *application.WebviewWindow) { w.HandleWindowEvent(uint(events.Common.WindowLostFocus)) },
func(_ *host, w *application.WebviewWindow) { w.HandleKeyEvent("escape") },
},
}
check := func(report url.Values) {
probe := struct {
Hidden bool `json:"hidden"`
State string `json:"state"`
Marked bool `json:"marked"`
Play string `json:"play"`
}{}
if err := json.Unmarshal([]byte(report.Get("probe")), &probe); err != nil {
fail("the page's hidden event is %q: %v", report.Get("probe"), err)
}
if !probe.Hidden || probe.State != "hidden" || !probe.Marked || probe.Play != "paused" {
fail("while hidden the page saw hidden=%v state=%q marked=%v play=%q", probe.Hidden, probe.State, probe.Marked, probe.Play)
}
}
app.Event.OnApplicationEvent(events.Common.ApplicationStarted, func(*application.ApplicationEvent) {
go func() {
var win *application.WebviewWindow
application.InvokeSync(func() {
if which == "panel" {
win = h.makePanel()
h.panel = win
win.Show()
return
}
win = app.Window.NewWithOptions(application.WebviewWindowOptions{
Name: "visibility",
Title: "visibility",
@@ -115,21 +159,12 @@ fetch("/ready");
fail("timed out waiting for the page")
}
application.InvokeSync(h.hideMain)
time.Sleep(500 * time.Millisecond)
application.InvokeSync(func() { showWebview(win).Focus() })
report := wait("the page's hidden report", reports)
probe := struct {
Hidden bool `json:"hidden"`
State string `json:"state"`
Marked bool `json:"marked"`
Play string `json:"play"`
}{}
if err := json.Unmarshal([]byte(report.Get("probe")), &probe); err != nil {
fail("the page's hidden event is %q: %v", report.Get("probe"), err)
}
if !probe.Hidden || probe.State != "hidden" || !probe.Marked || probe.Play != "paused" {
fail("while hidden the page saw hidden=%v state=%q marked=%v play=%q", probe.Hidden, probe.State, probe.Marked, probe.Play)
// the panel by a click elsewhere, then by Escape
for _, hide := range closes[which] {
hide(h, win)
time.Sleep(500 * time.Millisecond)
application.InvokeSync(func() { showWebview(win).Focus() })
check(wait("the page's hidden report", reports))
}
fmt.Println("window visibility: ok")
app.Quit()
+14
View File
@@ -6,6 +6,7 @@ import (
"runtime"
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/wailsapp/wails/v3/pkg/events"
)
// A macOS window hidden with orderOut keeps its WKWebView's page visible, so
@@ -37,6 +38,19 @@ func showWebview(w *application.WebviewWindow) *application.WebviewWindow {
return w
}
// sayWailsHides tells the panel's page when Wails hides the panel itself:
// on a click elsewhere (HideOnFocusLost), the way it is mostly closed, and
// on Escape (HideOnEscape), both a plain Hide that hideWebview never sees.
// A page never told it was hidden isn't told it is back either, so it kept
// the settings it was drawn with: Settings' ¥ and 万 / 亿 never reached the
// panel's Usage tab (blrbrzkj on Discord).
func sayWailsHides(w *application.WebviewWindow) {
if js := pageHiddenJSOn(runtime.GOOS); js != "" {
w.OnWindowEvent(events.Common.WindowLostFocus, func(*application.WindowEvent) { w.ExecJS(js) })
}
w.RegisterKeyBinding("escape", func(application.Window) { hideWebview(w) })
}
// pageHiddenJSOn is what a page on goos is told as its window hides.
func pageHiddenJSOn(goos string) string {
if goos != "darwin" {