gui: in a narrow window the title bar's tools show their icons, then the title gives way; nothing lies over it (#2625, linusxiong)

Beside the sidebar, Library's, Plugins' and Settings' heads sit in the
title bar after the breadcrumb, between --tools-l (the crumb's right +
16) and the window's buttons, laid out flex-end. When the tools needed
more than that room they ran on to the left, over the crumb: at about
650pt with the sidebar, Library -> MCP servers had 「发现」 over
「MCP 服务器」's last character. The crumb never gave way to them.

app.js tools() now shares the room out, laying out and reading each
step in its one frame, the next only if the tools still run over:
1. the crumb whole (its natural width from its parts, the last one's
   scrollWidth) and the tools with their words;
2. body.tools-tight: Library's Discover / Library folder / Backups and
   Plugins' "Mirrors in China" show their icon (or switch) alone. Each
   keeps its name as aria-label (a hidden span leaves the accessible
   name) and its tooltip as before (the folder's path, the backups'
   note and path, Discover's and the mirrors' sentences);
3. --crumb-max: the crumb drops its leading parts ("Work /"), a part
   and its slash at a time, and last cuts the page's name at its end.
In the side-nav head the Library buttons and the mirror switch are
flex: none and Plugins' search keeps 120px, so what doesn't fit shows
as running over rather than shrinking out of sight. The views'
MutationObserver also asks tools() again, as a tab's own tools change
(Discover only on MCP servers and Skills) without the crumb resizing.

title-bar-tools.test.cjs (new): every Library tab, Plugins' three and
Settings, sidebar picked, window mode, at 560 (the window's least),
650, 760, 900, 1024 and 1280px, in zh, zh-TW, ja, de and en, Chromium
and WebKit. No tool lies over the shown title or another tool or out
of the bar, no label is cut, an icon-only tool has aria-label and
title, only leading crumb parts go and the page's name shows, whole
from 650px. Against the old assets (MAGPIE_GUI_ASSETS) it fails in all
five languages at 560px Library Instructions ("a tool lies over the
title"); with the change Chromium 5/5 and WebKit 5/5. Looked at
screenshots of zh Library MCP servers and Plugins Discover at 560, 650
and 760px.

docs/subsystems/gui-shell.md says how the title bar gives way.

Run with both #2623's and #2625's changes, on b7d9616d0 (macOS, Go
1.26.8, load average 80-270 from other sessions):
- gofmt -l: nothing. go vet -tags nogui ./... with GOOS darwin, linux and
  windows: clean.
- set -o pipefail; go test -timeout 45m ./...: every package ok except
  internal/agent (2702s) and internal/gateway (2721s), which ran past
  45m under the load (#2544, #2108; no test hung, each was seconds into
  its run). Rerun with -timeout 90m: internal/agent ok (2816s);
  internal/gateway's only red is TestDesktopSubagentUnsetDoesNotDecode,
  "allocated 1 times" (10/10 green alone, filed as #2699). The textcalls
  tests passed in that run.
- The whole GUI suite, both engines (NODE_PATH at playwright@1.62.0). It
  ran in two parts, because another session deleted the first part's log
  mid-run; the files from provider-* on were run again. title-bar-tools
  passed 10/10 inside the suite. The reds are red the same way on
  b7d9616d0's assets, rerun beside them (MAGPIE_GUI_ASSETS) at
  concurrency 1-2:
  - segs-glide 20/20: filed #2683.
  - sidebar under load: filed #2684; 4/6 red on the old assets.
  - lightweight: filed #2638.
  - Already filed:
    - usage-agents-hide (#2276), routing-bodies (#2559, #2658),
      routing-keys-fold (#1612), routing-model-rest (#2115),
      routing-wb-restricted (#1905), rest-try-now (#2564), s3-sync (#2448).
    - quota-count-wrap, quota-name-translated and usage-fold (#2399),
      usage-checkin (#2549), usage-refresh (#2184), usage-ledger (#1876).
    - codex-predictions (#2624), github-sync (#2631), login-import (#1307).
  - The rest were Playwright launch timeouts under load (#2371).
- After rebasing on origin/main 85eef5d87: title-bar-tools Chromium 5/5,
  WebKit 5/5. Before that, WebKit zh and ja failed on a page error, "Fetch
  API cannot load /api/providers due to access control checks". That is
  WebKit's report of a sidebar read cancelled by the test going to the
  next page (#1350, #1307). The test now leaves that one WebKit message
  out. Against b7d9616d0's assets, WebKit ja is still red: "a tool lies
  over the title at 560px library instructions".

Not tried in the real app on Linux (WebKitGTK) or Windows (WebView2);
no motion or new browser API is involved, only layout.
This commit is contained in:
yetone
2026-10-17 18:41:43 +08:00
parent 7ea8aeaba7
commit 17557132cb
6 changed files with 214 additions and 5 deletions
+1 -1
View File
@@ -16,7 +16,7 @@ three.
| 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: `plugins.js` and `context.js`, and those a plugin adds under `assets/plugins/<id>/` (the Gateway, Sessions, Library, Routing and Usage pages, see [plugin runtime](plugin-runtime.md)) (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`, and a plugin's own in its `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) |
| Window navigation | In the window from 1024 points wide (`SIDE_AT`, the same width as app.css's `side-nav` rules), `layoutNav` moves the brand, the pages (`#nav`) and Settings into the sidebar (`#side`): the pages in four groups (Work, Models, Insights, Extend; a group none of whose pages shows, as in gateway mode, leaves out its name), the gateway's address at its foot (`sideGwRead`, read from `/api/providers` only while there is a sidebar), and the header a breadcrumb (`renderCrumb`). The open page's own tabs (`NAV_SUBS`: Usage, Library, Plugins, Settings) are listed under it as `.nav-s` rows (`role="tab"`, `data-of` the page tab's id) and the page's strip is hidden; a row's click clicks that tab at once, the selection (`.nav-hl`) having set off as the row was pressed (`navSubGlide`; back if the press leaves the row), and is the list's only shape: a row hovered or pressed has no ground of its own, and a `MutationObserver` draws the list again when the strip changes. A page's tabs share its one scroll, so a row that picks another tab opens it at its top (`scrollOnPurpose` with the row's click); the tab already open, picked again, leaves the page where it is (`sidebar-tab-top.test.cjs`). The list opens and folds with an iOS-like spring (`navSubEnter`, `navSubLeave`; none under reduced motion), and a folding list is out of reach at once. Narrower, the page beside a sidebar would be narrower than Usage's requests table needs (768 points), so they go back into the header's row, as a Mac sidebar gives way in a narrow window. At every width the reader can pick the sidebar or the header's tabs from the title bar's button (`#sideToggle`, ⌃⌘S or Ctrl+Shift+S; `toggleSideNav`), kept in localStorage `magpie.navLayout` (`side` or `top`) and so laid out from the first frame; none picked, the sidebar comes from `SIDE_AT`. Picked in a narrow window the sidebar is narrower (184 points under 860), and magpie web on a phone keeps its own tab bar and has no button. The two layouts trade places in a view transition (`navMorph`, app.css `.nav-morph`): the sidebar slides, each page's tab flies to its place in the other, and the page slides as one (its old image dropped, so no line prints twice); without view transitions, under reduced motion, or in the Linux app the change is at once: WebKitGTK with compositing off (`WEBKIT_DISABLE_COMPOSITING_MODE`, which `webkit_linux.go` sets under Wayland) crashes in a view transition. Elsewhere a transition still going after `MORPH_MAX` (1.5s) is skipped, so a webview that never ends one can't leave the window on the old layout's picture. See `side-toggle.test.cjs`. A window made wider or narrower drops what a click held (`heldWidth`): the page laid out again isn't the click's doing. The reader's own place is kept instead for a second while the page is laid out again (`relaid`, a `ResizeObserver` on the open page's parts calling `backToReader`): crossing `SIDE_AT` the browser clamps the scroll to each layout it passes through, and the page ended short of its foot (#1672, `text-size.test.cjs`). See `sidebar.test.cjs`. A sidebar longer than a short window keeps no scroll bar beside its pages: the native bars of `.side-scroll` and `.side-foot` are hidden, and `sideBars` lays a thin bar over each box's edge that shows while it scrolls, fades about a second after it stops (kept while hovered or dragged), can be dragged or clicked to page, and is gone when the box fits, the same in WebKit, WebView2 and WebKitGTK. See `sidebar-overlay-scrollbar.test.cjs`. The window opens on the page the reader last left, as a Mac app comes back as it was (molvqingtai and lc on Discord): `show` keeps the page in localStorage `magpie.lastView` (which the app's webview keeps across restarts, as it keeps `magpie.navLayout`), and `keptView` opens it at start. A page asked for in the address (`?view=`, the tray's links, a reload) wins, Agents too; a kept name that is no page opens the first page, and one gateway mode leaves out opens Providers (`show`). Opening on it scrolls nothing. See `last-page.test.cjs`. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/app.css`](../../internal/gui/assets/app.css) |
| Window navigation | In the window from 1024 points wide (`SIDE_AT`, the same width as app.css's `side-nav` rules), `layoutNav` moves the brand, the pages (`#nav`) and Settings into the sidebar (`#side`): the pages in four groups (Work, Models, Insights, Extend; a group none of whose pages shows, as in gateway mode, leaves out its name), the gateway's address at its foot (`sideGwRead`, read from `/api/providers` only while there is a sidebar), and the header a breadcrumb (`renderCrumb`). A page whose head holds only its tools (Library, Plugins, Settings) has them in the title bar after the breadcrumb, `tools` setting the room between it and the window's own buttons. When they don't fit there the tools show their icons alone (`tools-tight`; each keeps its name as `aria-label` and in its tooltip), then the breadcrumb drops its leading parts, and last the page's name is cut at its end, so no tool lies over the title (#2625, `title-bar-tools.test.cjs`). The open page's own tabs (`NAV_SUBS`: Usage, Library, Plugins, Settings) are listed under it as `.nav-s` rows (`role="tab"`, `data-of` the page tab's id) and the page's strip is hidden; a row's click clicks that tab at once, the selection (`.nav-hl`) having set off as the row was pressed (`navSubGlide`; back if the press leaves the row), and is the list's only shape: a row hovered or pressed has no ground of its own, and a `MutationObserver` draws the list again when the strip changes. A page's tabs share its one scroll, so a row that picks another tab opens it at its top (`scrollOnPurpose` with the row's click); the tab already open, picked again, leaves the page where it is (`sidebar-tab-top.test.cjs`). The list opens and folds with an iOS-like spring (`navSubEnter`, `navSubLeave`; none under reduced motion), and a folding list is out of reach at once. Narrower, the page beside a sidebar would be narrower than Usage's requests table needs (768 points), so they go back into the header's row, as a Mac sidebar gives way in a narrow window. At every width the reader can pick the sidebar or the header's tabs from the title bar's button (`#sideToggle`, ⌃⌘S or Ctrl+Shift+S; `toggleSideNav`), kept in localStorage `magpie.navLayout` (`side` or `top`) and so laid out from the first frame; none picked, the sidebar comes from `SIDE_AT`. Picked in a narrow window the sidebar is narrower (184 points under 860), and magpie web on a phone keeps its own tab bar and has no button. The two layouts trade places in a view transition (`navMorph`, app.css `.nav-morph`): the sidebar slides, each page's tab flies to its place in the other, and the page slides as one (its old image dropped, so no line prints twice); without view transitions, under reduced motion, or in the Linux app the change is at once: WebKitGTK with compositing off (`WEBKIT_DISABLE_COMPOSITING_MODE`, which `webkit_linux.go` sets under Wayland) crashes in a view transition. Elsewhere a transition still going after `MORPH_MAX` (1.5s) is skipped, so a webview that never ends one can't leave the window on the old layout's picture. See `side-toggle.test.cjs`. A window made wider or narrower drops what a click held (`heldWidth`): the page laid out again isn't the click's doing. The reader's own place is kept instead for a second while the page is laid out again (`relaid`, a `ResizeObserver` on the open page's parts calling `backToReader`): crossing `SIDE_AT` the browser clamps the scroll to each layout it passes through, and the page ended short of its foot (#1672, `text-size.test.cjs`). See `sidebar.test.cjs`. A sidebar longer than a short window keeps no scroll bar beside its pages: the native bars of `.side-scroll` and `.side-foot` are hidden, and `sideBars` lays a thin bar over each box's edge that shows while it scrolls, fades about a second after it stops (kept while hovered or dragged), can be dragged or clicked to page, and is gone when the box fits, the same in WebKit, WebView2 and WebKitGTK. See `sidebar-overlay-scrollbar.test.cjs`. The window opens on the page the reader last left, as a Mac app comes back as it was (molvqingtai and lc on Discord): `show` keeps the page in localStorage `magpie.lastView` (which the app's webview keeps across restarts, as it keeps `magpie.navLayout`), and `keptView` opens it at start. A page asked for in the address (`?view=`, the tray's links, a reload) wins, Agents too; a kept name that is no page opens the first page, and one gateway mode leaves out opens Providers (`show`). Opening on it scrolls nothing. See `last-page.test.cjs`. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/app.css`](../../internal/gui/assets/app.css) |
| Built-in plugins | Plugins › Built-in, the page's first tab (`drawBuiltin` in `plugins.js`, rows by `renderBuiltins` in `app.js`), lists magpie's built-in plugins, each with a name, a line on what it is and a switch: Routing groups, Library, Observability, Sessions, Warm-up and check-in, and the Gateway and Routing pages (Essential). A plugin on with settings has their rows under its row, drawn from its schema by the kernel's `ui.form`, and a change posts `{id, config}`. The Gateway page is drawn by its plugin's own scripts through the window's kernel (`kernel.js`, `assets/plugins/gateway/`); see the [plugin runtime](plugin-runtime.md), "The window's kernel". They are `plugins/*` registered with the [plugin runtime](plugin-runtime.md); `GET /api/plugins/builtin` says each one (`builtinJSON`: on is active, the user's own choice, what of it is in use) and `POST {id, on}` (or `{id, config}`) writes plugins.yml. A page marks what goes with a plugin `data-feature="<id>"`. Off, `featureStyle` hides everything so marked (rows drawn later too), `navHides` leaves its page's tab out of the sidebar and the header, `show` opens Agents for an address kept for it, and `setSetTab`, `partShows` and `findSettings` leave its Settings tab and rows out, of the search too. One in use stays on: its switch is disabled and the row says what uses it, and the POST refuses it off. A plugins.yml that doesn't parse is said above the list and no switch moves. `boot.js` says which are off (`featuresOff`) and their settings (`pluginConfig`) before the first paint, and `settings.builtins` carries the list on every state read. The TUI doesn't follow them. See `builtins.test.cjs`, `builtins_test.go`. | [`builtins.go`](../../internal/gui/builtins.go), [`assets/plugins.js`](../../internal/gui/assets/plugins.js), [`assets/app.js`](../../internal/gui/assets/app.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`](../../internal/cli/gui_off.go) |
+10
View File
@@ -422,6 +422,16 @@ body.side-nav.mac :is(#view-library .lib-head, #view-plugins .pm-head, #view-set
body.side-nav :is(#view-library .lib-head, #view-plugins .pm-head, #view-settings .set-head) > * { pointer-events: auto; --wails-draggable: no-drag; min-width: 0; }
body.side-nav :is(#view-library .lib-head, #view-plugins .pm-head)::before { display: none; }
body.side-nav :is(#view-library .lib-headacts) { flex-wrap: nowrap; }
/* a narrow window (#2625): the buttons keep their size and the fields
their least, so what doesn't fit shows as too wide (app.js tools), never
run left over the title. First the buttons give their words up for
their icons, the name kept as the button's and its tooltip; only then
is the title cut: its first parts go, then its last is cut at its end */
body.side-nav :is(#view-library .lib-headacts, #view-plugins .pm-mirror) { flex: none; }
body.side-nav #view-plugins .pm-find { min-width: 120px; }
body.side-nav.tools-tight :is(#view-library .lib-headacts button, #view-plugins .pm-mirror) > span:not(.lib-mini, .lib-switch) { display: none; }
body.side-nav .crumb { max-width: var(--crumb-max, none); }
body.side-nav .crumb > [hidden] { display: none; }
body.side-nav :is(#view-library, #view-plugins, #view-settings) { padding-top: 8px; }
/* the gateway, under Settings: where it listens; a click opens its page */
.side-gw { display: flex; align-items: center; gap: 8px; height: 26px; margin-top: 2px; padding: 0 9px; border-radius: 6px; font-size: 11.5px; color: var(--muted); text-align: left; white-space: nowrap; }
+44 -4
View File
@@ -23256,7 +23256,7 @@ if (mode === "window") {
// there or by a link) is drawn again in the sidebar, once a frame
let queued = false;
const again = () => { if (queued) return; queued = true; requestAnimationFrame(() => { queued = false; navSubs(); }); };
const mo = new MutationObserver(again);
const mo = new MutationObserver(() => { again(); if (document.body.classList.contains("side-nav")) tools(); });
for (const v of Object.keys(NAV_SUBS)) mo.observe($("#view-" + v), { childList: true, subtree: true, attributes: true, attributeFilter: ["class", "hidden"] });
// a page whose head is only its tools (Library, Plugins, Settings) has them
// in the title bar beside the sidebar (app.css): between where the reader
@@ -23268,12 +23268,52 @@ if (mode === "window") {
if (toolsAt) return;
toolsAt = requestAnimationFrame(() => {
toolsAt = 0;
const top = $(".top"), c = $("#crumb").getBoundingClientRect(), a = $(".actions").getBoundingClientRect();
const st = document.documentElement.style;
const top = $(".top"), crumb = $("#crumb"), a = $(".actions").getBoundingClientRect();
const st = document.documentElement.style, body = document.body;
const set = (k, v) => { if (st.getPropertyValue(k) !== v) st.setProperty(k, v); };
set("--top-h", top.offsetHeight + "px");
set("--tools-l", Math.ceil(c.right + 16) + "px");
set("--tools-r", Math.ceil(innerWidth - a.left + 8) + "px");
// the room the title and the tools share (#2625): the title whole and
// the tools with their words; else the tools as icons; else the title
// cut at its end, so nothing lies over it. Each step is laid out and
// read again here, in this frame, the next only if it ran over
const kids = [...crumb.children];
for (const e of kids) if (e.hidden) e.hidden = false;
if (!body.classList.contains("side-nav")) {
body.classList.remove("tools-tight");
set("--crumb-max", "none");
return;
}
const head = $(":is(#view-library .lib-head, #view-plugins .pm-head, #view-settings .set-head):not([hidden] *)");
const c = crumb.getBoundingClientRect(), gap = parseFloat(getComputedStyle(crumb).columnGap) || 0;
const wide = kids.map((e) => (e.tagName === "B" ? e.scrollWidth : e.getBoundingClientRect().width) + gap);
const whole = Math.ceil(wide.reduce((w, x) => w + x, 0) - (kids.length ? gap : 0));
const over = () => {
const h = head.getBoundingClientRect();
let left = h.right;
for (const e of head.querySelectorAll("button, label, input")) {
if (!e.getClientRects().length || e.closest(".lib-tabs, .set-tabs")) continue;
left = Math.min(left, e.getBoundingClientRect().left);
}
return { over: left < h.left - 0.5, need: h.right - left };
};
body.classList.remove("tools-tight");
set("--crumb-max", "none");
set("--tools-l", Math.ceil(c.left + whole + 16) + "px");
if (!head || !over().over) return;
body.classList.add("tools-tight");
const o = over();
if (!o.over) return;
const max = Math.max(0, Math.floor(a.left - 8 - 16 - o.need - c.left));
// where the reader is keeps its last word: "Work / Library /" goes,
// a part and its slash at a time, before "MCP servers" is cut
let w = whole;
for (let i = 0; i + 1 < kids.length - 1 && w > max; i += 2) {
kids[i].hidden = kids[i + 1].hidden = true;
w -= wide[i] + wide[i + 1];
}
set("--crumb-max", max + "px");
set("--tools-l", Math.ceil(c.left + max + 16) + "px");
});
};
const ro = new ResizeObserver(tools);
+1
View File
@@ -792,6 +792,7 @@
b.disabled = mirrorSaving;
b.setAttribute("role", "switch");
b.setAttribute("aria-checked", on ? "true" : "false");
b.setAttribute("aria-label", t("Mirrors in China"));
b.title = t("Download the plugin list, plugins and Bun from mirrors in China first (npmmirror, jsDelivr), their official addresses after. Each is a copy of the very file, checked as the original is");
const sw = el("span", "lib-switch" + (on ? " on" : ""));
sw.append(el("i"));
@@ -754,16 +754,21 @@ magpie.plugin("library", (ctx) => {
});
go.append(glyph(GLYPH.search, "lib-mini"), el("span", "", t("Discover")));
go.title = tab === "mcp" ? t("Go to the MCP servers you can add, under the list") : t("Go to the skills you can add, under the list");
// a narrow window's title bar shows the icon alone (app.css
// .tools-tight): the name stays the button's, not only its tooltip's
go.setAttribute("aria-label", t("Discover"));
acts.append(go);
}
const more = button("", "lib-more", () => lib && reveal(lib.dir));
more.append(glyph(GLYPH.folder, "lib-mini"), el("span", "", t("Library folder")));
more.setAttribute("aria-label", t("Library folder"));
if (lib) more.title = tilde(lib.dir);
else more.disabled = true;
// magpie's backups beside it, on every tab: at the foot of a long
// page they were hard to find (Dade on Discord: 备份在最底部)
const back = button("", "lib-backups", () => lib && reveal(lib.backups));
back.append(glyph(GLYPH.backup, "lib-mini"), el("span", "", t("Backups")));
back.setAttribute("aria-label", t("Backups"));
if (lib) back.title = t("magpie keeps a copy of every file before it writes it.") + "\n" + tilde(lib.backups);
else back.disabled = true;
acts.append(more, back);
+153
View File
@@ -0,0 +1,153 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// #2625 (linusxiong): beside the sidebar, a page whose head is only its
// tools (Library, Plugins, Settings) has them in the title bar, after
// where the reader is ("Work / Library / MCP servers"). In a narrow
// window the tools ran on to the left, over the title: 「MCP 服务器」's
// last character sat on 「发现」. Now nothing in the title bar lies over
// anything else, the tools keep inside it, and the title shows whole
// wherever the tools can make room for it by showing only their icons;
// a tool shown as its icon keeps its name for the reader and a tooltip.
// Every Library tab, Plugins' and Settings', the window from its least
// width (560px) up, the sidebar picked, in all five languages, 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_GUI_ASSETS || path.join(__dirname, "../assets"));
const HOME = "/Users/tester";
const agent = (id, name, icon) => ({ id, name, icon, skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` });
function serve(lang) {
const view = {
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
agents: [agent("claude", "Claude Code", "claudecode-color")],
instructions: { agents: [], sets: [] },
servers: [{ name: "filesystem", transport: "stdio", command: "npx", args: ["-y", "fs"], agents: ["claude"] }],
foundServers: [], projects: [], foundSkills: [], problems: [], hooks: [], subagents: [],
skills: [{ name: "pdf", kind: "folder", description: "PDFs", agents: ["claude"], source: `${HOME}/skills/pdf` }],
};
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",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, theme: "light" } });
if (url.pathname === "/api/plugins") return json({ plugins: [], mirror: false });
if (url.pathname === "/api/library") return json(view);
if (url.pathname === "/api/library/market/servers") return json({ items: [{ id: "fetch", name: "fetch", title: "Fetch", description: "Read the web.", transport: "stdio", runs: "uvx", featured: true }] });
if (url.pathname === "/api/library/market/skills") return json({ items: [] });
if (url.pathname === "/api/library/rtk") return json({ path: `${HOME}/.local/bin/rtk`, version: "0.51.0", url: "https://www.rtk-ai.app", agents: [{ id: "claude", name: "Claude Code", icon: "", on: true }] });
if (url.pathname === "/api/plugins/builtin") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true, url: "http://127.0.0.1:3425" } });
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)];
const body = await fs.readFile(file).catch(() => null);
await (body ? route.fulfill({ body, contentType }) : route.fulfill({ status: 404, body: "" }));
};
}
// what the title bar shows, once it has settled: the title's parts as
// far as they show, each tool, and the window's own buttons
function bar(head) {
const box = (r) => ({ left: Math.round(r.left), right: Math.round(r.right), top: Math.round(r.top), bottom: Math.round(r.bottom) });
const crumb = document.querySelector("#crumb"), c = crumb.getBoundingClientRect();
const parts = [...crumb.children].map((e) => {
const r = e.getBoundingClientRect();
return { text: e.textContent, shown: r.width > 0, right: Math.min(r.right, c.right), cut: r.right > c.right + 0.5 || e.scrollWidth > e.clientWidth + 0.5 };
});
const h = document.querySelector(head);
const tools = [...h.querySelectorAll("button, label, input")].filter((e) => e.getClientRects().length && getComputedStyle(e).visibility !== "hidden" && !e.closest("[hidden]") && !e.closest(".lib-tabs, .set-tabs"))
.filter((e) => !e.parentElement.closest("button, label"))
.map((e) => {
const label = [...e.querySelectorAll("span")].find((s) => s.textContent.trim() && !s.closest(".lib-mini"));
return {
...box(e.getBoundingClientRect()), aria: e.getAttribute("aria-label"), title: e.title,
label: label ? label.getClientRects().length > 0 : null, clipped: e.scrollWidth > e.clientWidth + 1,
};
});
const acts = document.querySelector(".top .actions").getBoundingClientRect();
return { parts, crumb: box(c), tools, acts: box(acts), side: document.querySelector("#side").getBoundingClientRect().right, view: innerWidth };
}
const pages = [
...["instructions", "mcp", "skills", "hooks", "subagents", "rtk"].map((tab) => ({ name: "library " + tab, url: "?view=library", head: "#view-library .lib-head", init: ["magpie.libTab", tab] })),
...["builtin", "discover", "installed"].map((tab) => ({ name: "plugins " + tab, url: "?view=plugins", head: "#view-plugins .pm-head", init: ["magpie.pluginTab", tab] })),
{ name: "settings", url: "?view=settings", head: "#view-settings .set-head" },
];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["zh", "zh-TW", "ja", "de", "en"]) {
test(`${engine} ${lang}: the title bar's tools never lie over where the reader is`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const width of [560, 650, 760, 900, 1024, 1280]) {
const context = await browser.newContext({ viewport: { width, height: 640 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(5000);
const errors = [];
let on = "";
// going from page to page cancels the reads still on their way, and
// WebKit reports each one as a page error, "Fetch API cannot load …
// due to access control checks" (#1350, #1307): not this test's
page.on("pageerror", (e) => {
if (engine === "webkit" && /^Fetch API cannot load .* due to access control checks/.test(e.message)) return;
errors.push(`${width}px ${on}: ${e.stack}`);
});
await page.route("**/*", serve(lang));
await page.addInitScript(() => { localStorage.setItem("magpie.navLayout", "side"); });
for (const p of pages) {
on = p.name;
if (p.init) await page.evaluate(([k, v]) => localStorage.setItem(k, v), p.init).catch(() => {});
await page.goto("http://magpie.test/" + p.url);
if (p.init) { await page.evaluate(([k, v]) => localStorage.setItem(k, v), p.init); await page.reload(); }
await page.locator(p.head).waitFor();
await page.locator("#crumb b").waitFor();
// the Library's buttons have their tooltips once it has loaded
if (p.name.startsWith("library")) await page.locator("#view-library .lib-more:not([disabled])").waitFor();
if (p.name === "library mcp") await page.locator("#view-library .lib-discover").waitFor();
if (/plugins (discover|installed)/.test(p.name)) await page.locator("#view-plugins .pm-mirror").waitFor();
// settled: two frames with the same bar
let b = null;
for (let i = 0; i < 40; i++) {
await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
const now = await page.evaluate(bar, p.head);
if (b && JSON.stringify(now) === JSON.stringify(b)) break;
b = now;
}
const at = `${width}px ${p.name}: ${JSON.stringify(b)}`;
// Plugins' Built-in has no search and no mirrors to pick
assert(b.tools.length > 0 || p.name === "plugins builtin", `no tools in the bar at ${at}`);
const title = b.parts[b.parts.length - 1];
const shown = Math.max(...b.parts.map((x) => x.right));
for (const tool of b.tools) {
assert(tool.left >= shown + 8, `a tool lies over the title at ${at}`);
assert(tool.left >= b.side && tool.right <= b.acts.left, `a tool runs out of the bar at ${at}`);
assert(!tool.clipped, `a tool's label is cut at ${at}`);
if (tool.label === false) assert(tool.aria && tool.title, `a tool shown as its icon has no name or tooltip at ${at}`);
}
for (let i = 1; i < b.tools.length; i++) {
const [x, y] = [b.tools[i - 1], b.tools[i]].sort((m, n) => m.left - n.left);
assert(x.right <= y.left, `two tools lie over each other at ${at}`);
}
assert(b.crumb.right <= b.acts.left, `the title runs under the window's buttons at ${at}`);
// the page the reader is on shows, if its start only; the parts
// before it go first
assert(title.shown && title.right - (b.crumb.left) > 0, `the page's name is gone at ${at}`);
const kept = b.parts.findIndex((x) => x.shown);
assert(b.parts.slice(kept).every((x) => x.shown), `the title lost a part in its middle at ${at}`);
if (title.cut) assert(b.parts.slice(0, -1).every((x) => !x.shown), `the page's name is cut while parts before it show at ${at}`);
// where the tools have their icons alone, nothing more of them
// can give way: the title shows whole wherever it fits beside them
if (width >= 650) assert(!title.cut, `the title is cut at ${at}`);
}
assert.deepEqual(errors, []);
await context.close();
}
});
}
}