diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 6cf558272..d4f9c7aa7 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -15,7 +15,7 @@ three. | Backend | `startBackend` starts the gateway this process serves, unless another magpie already serves it. In that case this process only shows the other one's status (`gw` is nil). `stopServing` drains requests in flight. | [`backend.go`](../../internal/gui/backend.go) | | API and assets | `Handler` serves `assets/` (embedded with `//go:embed assets`) and the `/api/*` routes, such as `/api/state`, `/api/set` and `/api/agents/{action}/{id}`. `held` lets one API request's reads share one catalog build (`provider.Hold`), and drops it after any write. `revalidated` and `versionedPage` name each script by its content hash, so a cache never serves an old `app.js` under a new page; a file asked for under its current hash (`?v=`) is cached for good (`immutable`), anything else is revalidated by its ETag. | [`api.go`](../../internal/gui/api.go) | | Browser mode | `StartWeb` serves the page and the gateway for `magpie web`. The browser signs in with a run key in a link. Gateway mode shows Providers, Gateway, Routing, Usage, Sessions, Plugins and Settings on a machine that is only a gateway. `webHandler` gzips the page's text files and the API's JSON for a browser that takes gzip (`webCompressed`, with a `-gzip` ETag that still answers 304); the app's own windows read the page in-process and get it uncompressed. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go) | -| The page | `app.js` keeps one state object per view and renders it into a list, with no framework. The views have their own files: `routing.js`, `library.js`, `plugins.js`, `sessions.js` and `context.js` (Usage's Context tab, and the context window card the Routing page draws under a request's story, fed by `/api/context` in `context.go`, which scores and tags each agent; clicking a part, a cell or an item opens its text from `/api/context/text`, the last 10 requests' masked bodies in memory (`openCtxText`), rendered 100 items and 20000 characters at a time; its "Tuned for you" cards are fed by `/api/tune` in `tune.go`, see [agent wiring](agent-wiring.md)). Strings go through `t()` with translations in `i18n.js` (zh, zh-TW, ja and de; the English text is the key and the fallback). zh-TW is Traditional Chinese with Taiwan's words; a system language of zh-TW, zh-HK, zh-MO or any zh-Hant picks it, and the tray menu and notifications follow (`trayLang`). Dropdowns use `openProtoMenu`. Every app menu (`openProtoMenu`, `openRowMenu`, `openSessCombo`) is placed by `placeMenu`: under its anchor, or over it when the window runs out below; one that fits neither way takes the larger room, its height held to it, and scrolls inside itself, and a scroll inside a menu doesn't close it (#1437, `removed-groups-menu-scroll.test.cjs`). Scrolling is done only by `scrollOnPurpose(e)` with the reader's event. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/i18n.js`](../../internal/gui/assets/i18n.js) | +| The page | `app.js` keeps one state object per view and renders it into a list, with no framework. The views have their own files: `routing.js`, `library.js`, `plugins.js`, `sessions.js` and `context.js` (Usage's Context tab, and the context window card the Routing page draws under a request's story, fed by `/api/context` in `context.go`, which scores and tags each agent; clicking a part, a cell or an item opens its text from `/api/context/text`, the last 10 requests' masked bodies in memory (`openCtxText`), rendered 100 items and 20000 characters at a time; its "Tuned for you" cards are fed by `/api/tune` in `tune.go`, see [agent wiring](agent-wiring.md)). Strings go through `t()` with translations in `i18n.js` (zh, zh-TW, ja and de; the English text is the key and the fallback). zh-TW is Traditional Chinese with Taiwan's words; a system language of zh-TW, zh-HK, zh-MO or any zh-Hant picks it, and the tray menu and notifications follow (`trayLang`). Dropdowns use `openProtoMenu`. Every app menu (`openProtoMenu`, `openRowMenu`, `openSessCombo`) is placed by `placeMenu`: under its anchor, or over it when the window runs out below; one that fits neither way takes the larger room, its height held to it, and scrolls inside itself, and a scroll inside a menu doesn't close it (#1437, `removed-groups-menu-scroll.test.cjs`). The highest any popover goes is `popTop`: 8px under `header.top` on a Mac window, where the traffic lights are drawn over the page, and 8px from the top elsewhere; `placeMenu`, the field picker's `placePop` (which also holds `#pop`'s height to that room) and an agent's model list (`openAgentModels`) all use it (#1573, `popover-mac-chrome.test.cjs`). Scrolling is done only by `scrollOnPurpose(e)` with the reader's event. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/i18n.js`](../../internal/gui/assets/i18n.js) | | No GUI build | `-tags nogui` builds magpie without the GUI: `hasGUI` is false and `runGUI` says to use `magpie tui`. The files of `internal/gui` that need Wails build under `!nogui`. | [`gui_off.go`](../../gui_off.go) | ## Runtime path diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 126a577bc..512bab660 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -2863,13 +2863,13 @@ async function openAgentModels(a, anchor, ev) { document.body.append(box); // under the line, or over it where there's no room; the list scrolls - const r = anchor.getBoundingClientRect(), pad = 8; + const r = anchor.getBoundingClientRect(), pad = 8, top = popTop(pad); const w = Math.min(railed ? 580 : 380, innerWidth - pad * 2); box.style.width = w + "px"; const x = Math.max(pad, Math.min(r.left - 10, innerWidth - w - pad)); box.style.left = x + "px"; box.style.setProperty("--ox", Math.max(18, Math.min(w - 18, r.left + Math.min(r.width, 60) / 2 - x)) + "px"); - const below = innerHeight - r.bottom - 8 - pad, above = r.top - 8 - pad; + const below = innerHeight - r.bottom - 8 - pad, above = r.top - 8 - top; const want = Math.min(560, box.scrollHeight); if (want > below && above > below) { box.classList.add("up"); @@ -3739,11 +3739,29 @@ function score(q, o) { return 0; } +// popTop is the highest a popover's top edge may go, pad under the window's +// own chrome: on a Mac window the traffic lights are drawn over the page's +// header.top, so a list that opens upward in a short window stops under it +// rather than over them (#1573, lyston11). Elsewhere the header is the +// page's own row and the edge is pad, as it always was. The header's +// measured bottom already counts the text size (--zoom). +function popTop(pad) { + const b = document.body.classList; + if (!b.contains("window") || !b.contains("mac")) return pad; + const head = document.querySelector("header.top"); + return Math.max(0, head ? head.getBoundingClientRect().bottom : 0) + pad; +} + function placePop(anchor, w, h) { const pop = $("#pop"); - const r = anchor.getBoundingClientRect(), pad = 8; + const r = anchor.getBoundingClientRect(), pad = 8, top = popTop(pad); w = Math.min(w, innerWidth - pad * 2); - h = Math.min(h, innerHeight - pad * 2); + // a window too short for it holds it to the room between the chrome and + // the foot, and its list scrolls, rather than running off the bottom + const most = innerHeight - pad - top; + pop.style.maxHeight = ""; + if (!(parseFloat(getComputedStyle(pop).maxHeight) <= most)) pop.style.maxHeight = most + "px"; + h = Math.min(h, most); pop.style.width = w + "px"; let x = Math.max(pad, Math.min(r.left, innerWidth - w - pad)); let y = r.bottom + 5; @@ -3753,13 +3771,13 @@ function placePop(anchor, w, h) { pop.style.setProperty("--ox", Math.max(16, Math.min(w - 16, r.left + r.width / 2 - x)) + "px"); // h is the most it can be: opened upward, its bottom edge is held to the // button, so a short list sits on the button rather than h above it - if (y + h > innerHeight - pad && r.top - 5 - h >= pad) { + if (y + h > innerHeight - pad && r.top - 5 - h >= top) { pop.classList.add("up"); pop.style.top = "auto"; pop.style.bottom = innerHeight - r.top + 5 + "px"; return; } - if (y + h > innerHeight - pad) y = Math.max(pad, innerHeight - pad - h); + if (y + h > innerHeight - pad) y = Math.max(top, innerHeight - pad - h); pop.style.bottom = "auto"; pop.style.top = y + "px"; } @@ -12928,19 +12946,19 @@ function closeProtoMenu() { // itself, so its last item can be reached in a short window (#1437). align // "right" lines its right edge up with the anchor's; dx nudges it sideways. function placeMenu(box, anchor, align = "left", dx = 0) { - const r = anchor.getBoundingClientRect(), h = box.offsetHeight, pad = 8; + const r = anchor.getBoundingClientRect(), h = box.offsetHeight, pad = 8, top = popTop(pad); let y = r.bottom + 5; - const below = innerHeight - pad - y, above = r.top - 5 - pad; + const below = innerHeight - pad - y, above = r.top - 5 - top; if (h > below && above >= h) { y = r.top - 5 - h; box.classList.add("up"); } else if (h > below && above > below) { box.style.maxHeight = above + "px"; - y = pad; + y = top; box.classList.add("up"); } else if (h > below) box.style.maxHeight = Math.max(below, 0) + "px"; const w = box.offsetWidth; const left = (align === "right" ? r.right - w : r.left) + dx; box.style.left = Math.max(pad, Math.min(left, innerWidth - w - pad)) + "px"; - box.style.top = Math.max(pad, y) + "px"; + box.style.top = Math.max(top, y) + "px"; } function openProtoMenu(anchor, opts, value, choose, head = "Protocol this key speaks", cls = "", align = "left", live = false, search = "") { closeProtoMenu(); diff --git a/internal/gui/tests/popover-mac-chrome.test.cjs b/internal/gui/tests/popover-mac-chrome.test.cjs new file mode 100644 index 000000000..fbce086cf --- /dev/null +++ b/internal/gui/tests/popover-mac-chrome.test.cjs @@ -0,0 +1,151 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// lyston11 (#1573): in a short Mac window, a popover opened upward from near +// the window's foot was held only to 8px from the top, so it covered the +// traffic lights and the header they are drawn over. Every placer that opens +// upward stops under the window's chrome now: an agent's model list (Pick), +// the field picker (#pop) and the app menu (.proto-menu). On a Mac window +// each one's top edge sits under header.top's bottom; on Windows they are +// where they were, 8px from the top. Each is opened from an anchor at the +// foot of a short, narrow window; no click moves the page. English and +// Chinese, Chromium and WebKit; no backend, the API is faked here. +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 models = () => [ + ...["gpt-5.5", "gpt-5.5-mini", "gpt-5.4", "gpt-5.3-codex", "o4", "o4-mini"].map((m, i) => + ({ id: "openai/" + m, name: m.toUpperCase(), group: "OpenAI", icon: "openai", context: 400e3, inUse: i === 0 })), + ...Array.from({ length: 30 }, (_, i) => ({ id: "openrouter/m" + i, name: "Router Model " + i, group: "OpenRouter", icon: "openrouter", context: 128e3 })), +]; + +function server(lang) { + const list = models(); + const options = list.map((m) => ({ value: "magpie/" + m.id, label: m.name, ref: m.id })); + const state = () => ({ + agents: [{ + id: "codex", name: "Codex", path: "/test/config.toml", icon: "codex-color", wired: true, + fields: [{ key: "model", label: "model", value: options[0].value, options }], + models: { shown: list.length, listed: list.length, by: [{ name: "OpenAI", icon: "openai", n: 6 }, { name: "OpenRouter", icon: "openrouter", n: 30 }] }, + }], + profiles: [], settings: { lang, theme: "light" }, + }); + return async (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:"${lang}",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(state()); + if (url.pathname === "/api/agent-models/codex") return json({ models: list }); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + 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)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const settled = (page) => page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const platform of ["MacIntel", "Win32"]) for (const lang of ["en", "zh"]) { + test(`${engine} ${platform} ${lang}: a popover opened upward stays under the window's chrome`, async (t) => { + const mac = platform === "MacIntel"; + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const ctx = await browser.newContext({ viewport: { width: 480, height: 560 } }); + await ctx.addInitScript((p) => { Object.defineProperty(Navigator.prototype, "platform", { get: () => p }); }, platform); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang)); + await page.goto("http://magpie.test/?mode=window"); + assert.equal(await page.evaluate(() => document.body.classList.contains("mac")), mac); + const head = await page.evaluate(() => document.querySelector("header.top").getBoundingClientRect().bottom); + if (mac) assert(head >= 49, `a Mac window's header reaches under the traffic lights: ${head}`); + // the highest a popover may start: under the chrome on a Mac, 8px elsewhere + const floor = mac ? head + 8 : 8; + + const row = page.locator('.row.agent[data-id="codex"]'); + await row.locator(".ag-link").click(); + const entry = row.locator(".ag-exp .ag-chips .ag-quiet"); + await entry.waitFor(); + await page.waitForFunction(() => document.getAnimations().length === 0); + // the window made short enough that the anchor is at its foot, with + // more room over it than under it; clicked where it is, as a person + // does (Playwright's own click scrolls it into view first, and a + // scroll closes a popover) + const atFoot = async (loc, room) => { + const b = await loc.boundingBox(); + await page.setViewportSize({ width: 480, height: Math.round(b.y + b.height + 24) }); + await settled(page); + const r = await loc.boundingBox(); + assert(r.y > room, `the anchor has room over it: ${r.y}`); + return () => page.mouse.click(r.x + Math.min(r.width / 2, 30), r.y + r.height / 2); + }; + const tops = () => page.evaluate(() => [scrollY, $("#view-agents").scrollTop]); + + // 1. the agent's model list (Pick), the reporter's case + let click = await atFoot(entry, 200); + let was = await tops(); + await click(); + const am = page.locator(".am-pop:not(.leaving)"); + await am.waitFor(); + await page.waitForFunction(() => document.querySelector(".am-pop:not(.leaving)")?.getAnimations().length === 0); + assert(await am.evaluate((e) => e.classList.contains("up")), "it opens upward"); + let b = await am.boundingBox(); + assert(b.y >= floor - 0.5, `the model list's top ${b.y} is under ${floor}`); + assert(b.y < floor + 40, `the model list still uses the room it has: ${b.y}`); + assert.deepEqual(await tops(), was, "opening it moves nothing"); + await page.keyboard.press("Escape"); + await page.waitForFunction(() => !document.querySelector(".am-pop:not(.leaving)")); + + // 2. the field picker (#pop) from the model field at the row's foot: + // too tall to fit under or over it, it is held to the window's top + await page.setViewportSize({ width: 480, height: 560 }); + const field = row.locator('.field[data-key="model"]').first(); + click = await atFoot(field, 120); + was = await tops(); + await click(); + const pop = page.locator("#pop:not([hidden])"); + await pop.locator("#list li").first().waitFor(); + await page.waitForFunction(() => document.querySelector("#pop").getAnimations().length === 0); + b = await pop.boundingBox(); + assert(b.y >= floor - 0.5, `the picker's top ${b.y} is under ${floor}`); + assert(b.y + b.height <= (await page.evaluate(() => innerHeight)) + 0.5, "the picker is on the screen whole"); + assert.deepEqual(await tops(), was, "opening it moves nothing"); + await page.keyboard.press("Escape"); + await page.waitForFunction(() => document.querySelector("#pop").hidden); + + // 3. an app menu (.proto-menu) taller than the room under its anchor + was = await tops(); + await page.evaluate(() => { + const a = document.createElement("button"); + a.id = "pm-anchor"; + a.textContent = "menu"; + a.style.cssText = `position:fixed;left:20px;top:${innerHeight - 40}px;height:24px`; + document.body.append(a); + openProtoMenu(a, Array.from({ length: 40 }, (_, i) => ({ v: "v" + i, name: "Choice " + i, note: "", literalName: true })), "v0", () => {}); + }); + const menu = page.locator(".proto-menu"); + await menu.waitFor(); + await page.waitForFunction(() => document.querySelector(".proto-menu").getAnimations().length === 0); + b = await menu.boundingBox(); + assert(await menu.evaluate((e) => e.classList.contains("up")), "the menu opens upward"); + assert(b.y >= floor - 0.5, `the menu's top ${b.y} is under ${floor}`); + assert(b.y + b.height <= (await page.evaluate(() => innerHeight)) - 30, "the menu ends over its anchor"); + assert.deepEqual(await tops(), was, "opening it moves nothing"); + + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${platform}-${lang}-popover.png`) }); + } + assert.deepEqual(errors, []); + }); + } +}