diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 7f110251f..5ddcdd33b 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -21,7 +21,7 @@ three. | 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//` (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; a client whose User-Agent names only an HTTP library, a runtime or an API SDK (`usage.IsLibrary`: curl, Bun, python-httpx, Go-http-client, OpenAI/Python), or nothing (`other`), is no agent and goes on one card, `scripts`, named Scripts with its libraries listed, read from each route's kept agent so older history folds too, while the Usage page's Agents list keeps each by its own name (theforeveriris on X, `context_scripts_test.go`, `context-scripts.test.cjs`); clicking a part, a cell or an item opens its text from `/api/context/text`, the last 10 requests' masked bodies in memory, else the request archive's copy masked the same way, with a 404 saying why there is none (`archive`: off, missing, cut, unread; `context_archive.go`), and its Reply the reply from `/api/context/reply` (`openCtxText`, in `ctxtext.js`, `context-text.test.cjs`), rendered 100 items and 20000 characters at a time; a session's details on the Sessions page and Usage's Sessions list draw a Context line of its requests from `/api/context/session`, which reads only the days from its first to its last (30 at most) and keeps that one session, so the tab's 80-session cap never leaves it out (`sessCtxLine` in `plugins/usage/page.js`, liang_yongxiang on Discord, `context_session_test.go`, `sessions-context-line.test.cjs`); 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, or drawn at once from boot.js's `sideGateway`; on a page other machines open, `magpie web`, it is `MAGPIE_PUBLIC_URL` while they are let in, as the Gateway page's address and About's Gateway URL are, noahhrreion on Discord; a port applied in Settings redraws it), 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; Settings' are listed above its button at the foot, which is laid from its end (`.side-foot`'s `column-reverse`, its rows kept whole and scrolled from the end when the window is too short), so the list grows up from the button and the button and the gateway's line stay where they were clicked (jen_celeus on X, `sidebar-settings-steady.test.cjs`); 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. The open page's row folds its list and unfolds it, as a Mac sidebar's disclosure (hkwok06 on X: Settings' list unrolled and only another page, the gateway, put it away): the row carries a muted chevron (`.nav-fold`, `aria-expanded`), turned down to the list while it shows (up for Settings', which opens above its button) and to the side while folded, and the row clicked again, or Enter on it, folds or unfolds the list and leaves the page and its tab as they were (`navFold` and `navFoldRows` in `navicons.js`, imported with the first list; `navSubs` asks `navList("Folded")`). A folded list stays folded, per page, in localStorage `magpie.navFolded`, until its row opens it again. See `nav-sub-fold.test.cjs`. The open page's own row is marked the same way, by one shape (`.nav-top-hl`, the rows' own ground given up to it, hovered or pressed too) that `navTopGo` moves to the row picked on a damped spring, as iOS moves a selection (`NAV_SPRING`, SwiftUI's response 0.42s and damping 0.84; `navTopStep` steps it each frame): it sets off as the row is pressed and comes back if the press leaves the row or the page isn't left, turns with the speed it has when the press changes its mind, and follows its row while the list above it folds, landing where the row ends up. It is put in place, not sent, when the window opens on a page or the rows move under it at rest (a `ResizeObserver`), is away while Settings is open (it has its own selection at the foot), comes back fading in on its row, jumps under reduced motion, and isn't drawn in the header's tabs, which have their `.thumb`. `#nav` is `position: relative` in the sidebar for it, so `.seg`'s centring `left` and `top` are reset. See `sidebar-glide.test.cjs`. 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. That tab bar (`phoneWeb`, app.css `body.web .top #nav`) lies at the window's foot, as an iPhone app's, over the home indicator's inset (`--tabbar`), with each page's icon over its name. It holds five tabs: with more pages shown than that, the first four and More, whose app menu lists the rest with their icons and ticks the open one, and More is marked while one of them is open and carries a page's dot (`phonetabs.js`, imported by `layoutNav` the first time the page is a phone's; a `MutationObserver` fits it again when a page is shown, left out or opened). Before it the tabs were a strip that scrolled sideways with nothing saying it did, and Agents and the Library lay past its edge (geraldpppppp on X). Status messages sit above the bar. See `phone-tabs.test.cjs`. 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`). Settings › General › Sidebar pages (`navpages.js`, loaded when Settings draws; youimark on X) leaves pages out of the sidebar for this browser alone: localStorage `magpie.navHidden`, read by `navMine` (through `navList`, which reads `magpie.navFolded` too), which `navHides` asks beside gateway mode and the built-in plugins. A hidden page's link, `?view=` or search hit still opens it (`offView` redirects only a page gateway mode or a switched-off plugin leaves out); only the window's kept place gives way, to the first page or Providers when Agents is hidden too (`keptView` in `start.js`), and Providers cannot be hidden (`nav-pages-hidden.test.cjs`). The same menu puts the built-in pages in the reader's order (chet030714 on X): a row dragged by its grip (with a mouse, a finger or a pen: `dragRows` through `dragListen`, which cancels only on the row's own `lostpointercapture`, since a finger's implicit capture on the grip is lost to the row and bubbles up; 40 points wide where the pointer is coarse), or moved with Alt+↑/↓, is kept in localStorage `magpie.navOrder`; `navArrange` in `navorder.js` (which `navHides` imports only once an order is kept, and `navpages.js` with the menu) moves the `#nav` buttons into it, so the sidebar, the header's tabs and a phone's tab bar (`phonetabs.js`: the first four, the rest under More) all follow, and while the order isn't the home one the groups' names are taken out of `#nav`. `navOrder` puts a page the kept order doesn't name (new in an update) after the page it follows at home; Default order removes the key. Plugin pages keep their own order in their group (`nav-pages-order.test.cjs`). 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) | | Settings › Privacy | The page opens on what masking kept from vendors (`drawMaskObs` in app.js, fed by `/api/masking/summary`): the values masked over 7 or 30 days with a chart of the days, the kinds, what only the local model found, agents to providers, and the values masked most, each shown only while pointed at (`maskTip`, `/api/masking/value`, which says it is gone after a restart). Its records (`drawMaskRecs`, `/api/masking/records` and `/api/masking/record`) take the page's place, filtered by kind, finder, agent or provider, a day at a time, each opening on the text the vendor saw with its placeholders marked. `maskedBadge`, on the Gateway page's recent calls and the Routing page's log, opens a request's own record (`openMaskRecord`), in amber with the count sent as written when every value found was on Warn. Below the card, *What to mask*, *How it's found* (the rules, always on while anything is masked, and the local model on top of them), *When a value is found* (Mask, Warn or Block per kind, the secret kinds first and the personal ones behind *Show all kinds*, and the *Never mask* list; `renderMaskActions`, with *Never mask* and *Masked words* drawn a value a row by `wordList` in `plugins/redact/settings.js`, saved as the same list of strings the one comma-separated box saved, `redact-words-list.test.cjs`), *Try it* (`renderMaskTry`, the text as the vendor would get it from `/api/masking/preview`, kept in no storage) and *Sharing*. *Agents' session history* (`renderSessionReads`, read from `/api/sessions/reads` only while the Privacy part is shown) has *Agents found later* and a row per agent found, the choice the Sessions page asks first on a fresh install; see [gateway sessions](gateway-sessions.md#which-agents-sessions-magpie-reads). While anything is masked, *Instead of masking, send to* (`redactRouteRow` in `plugins/redact/settings.js`, the redact plugin's part of Settings, which wraps `renderRedact` so app.js carries none of it) picks, in the app menu, a model a request masking would change goes to as written: Off by default, and only the models `/api/settings` lists as `maskRouteModels` (every route of theirs unmasked, `gateway.MaskRoute`), saved with `POST /api/settings/redact-route` (`redact-route.test.cjs`). See [gateway routing](gateway-routing.md) for what is recorded. | [`assets/app.js`](../../internal/gui/assets/app.js), [`masking.go`](../../internal/gui/masking.go) | -| 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=""`. 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. Settings' search lists the built-ins themselves after its own rows, off or on, by name, line or a setting in their schema (Gateway's Recent calls at a time is on its own page), and Open lights the row in Plugins › Built-in (`setFeatsFind` in the lazy [`setfeats.js`](../../internal/gui/assets/setfeats.js), `settings-search.test.cjs`). Its provider links are drawn the first time a search wants them (`provlinks.js`). 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) | +| 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=""`. 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. Settings' search lists the built-ins themselves after its own rows, off or on, by name, line or a setting in their schema (Gateway's Recent calls at a time is on its own page), and Open lights the row in Plugins › Built-in (`setFeatsFind` in the lazy [`setfeats.js`](../../internal/gui/assets/setfeats.js), `settings-search.test.cjs`). Its provider links are drawn the first time a search wants them (`provlinks.js`). A part is found by its name, not its tab's id ("usage" no longer brings all of Allowances; Observability also answers to otel). A hit under a folded Advanced is unfolded while the search lasts and folded again when it ends (`setFolds`). The settings an agent's sheet or the Claude editor builds only when opened (Claude Code's prompt cache and commit signature, an agent's own fields, the run mode) have links there too, whose Open opens the sheet or editor and lights the row (`sheetLinks`, `lightWhen`; `settings-search-reach.test.cjs`). 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) | | The app's log | `runGUI` and `runPanel` (so `magpie`, `app`, `tray`, `panel`, a window view and a `magpie:` link) call `startLog` before `gui.Run`: `applog.Start` sends the standard logger, which the gateway, the plugin host and Wails' error handler write to, to `app.log` in `appdir.Logs` as well as stderr (`quiet`, which never fails, first, since io.MultiWriter stops at a failed writer and an app opened from Explorer has no stderr), and points `debug.SetCrashOutput` at it, so a panic is in it. Opened from the Finder, the Dock or the Start menu the app has no terminal, and wrote its log nowhere (rayem1w on X, 0.1.2330). The folder is `~/Library/Logs/magpie` on macOS (beside the launch agent's `serve.log`, which launchd writes for `magpie serve`: the two processes never share a file), `%LOCALAPPDATA%\magpie\logs` on Windows, `$XDG_STATE_HOME/magpie` (`~/.local/state/magpie`) elsewhere, and `logs` in a portable data folder. The file is 0600. At 5 MiB (`Limit`) it becomes `app.old.log`; when another magpie (an update's new process) rotated it already (`os.SameFile` of the open file and the path differs), it is only opened again, and when it can't be moved it is emptied. Each line goes through `scrub`, which masks bearer and basic credentials, key and token query parameters, and `sk-`, `AIza`, `gh?_` and JWT shapes, though nothing logged is meant to carry one. Settings › About's Log row (`#logRow`, `settingsJSON.Log` from `applog.Current`, so `magpie web`, which writes no file, shows none) has its path and an Open (`POST /api/settings/log/reveal`) that shows its folder; `magpie log` prints where every log is, `-n` the last lines, `-f` follows across a rotation (`TestTheAppWritesItsLog`, `TestLogFollows`). | [`internal/applog/applog.go`](../../internal/applog/applog.go), [`gui_on.go`](../../internal/cli/gui_on.go), [`log_cli.go`](../../internal/cli/log_cli.go) | | 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) | | The terminal quitting | `magpie tui` that served the gateway with an agent connected hands the gateway on as it quits, on Linux where nothing opens magpie at login (a WSL distro, a server over SSH; zaidu259434 on X): `keepGateway` starts magpie's service when it is installed, installs it (`daemon.Install`) when the user never removed it (`daemon.Removed`, a mark `magpie daemon uninstall` leaves), and otherwise starts `magpie serve` in its own session (`serveInBackground`, log in magpie's cache). Elsewhere, or with nothing connected, it only says the gateway stopped. Where magpie opens at login (`autostart.Enabled`, which on Linux counts a package's own autostart entry, also on a box no desktop logs into) it leaves the gateway to the app, and the note says `magpie autostart off` has the terminal hand it on where no desktop logs in (`atLoginNote`, #3756). | [`keep.go`](../../internal/tui/keep.go) | diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 94dda5210..d6915d0f1 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -19964,7 +19964,7 @@ function findSettings() { let any = false; for (const id of SET_TABS) { const page = $("#setPage-" + id), tab = $("#setTab-" + id); - const part = setText(tab) + " " + id; + const part = setText(tab) + (id === "otel" ? " otel" : ""); // not "usage" for Allowances let hits = 0, head = ""; const lit = new Set(); for (const n of page.querySelectorAll(".row-head, .row")) { @@ -19999,6 +19999,7 @@ function findSettings() { page.hidden = !hits; any ||= hits > 0; } + window.setFolds?.(v); // a hit under a folded Advanced (provlinks.js) // the built-ins that match (setfeats.js) if (window.setFeatsFind) any = setFeatsFind(words) > 0 || any; else import("./setfeats.js").then(() => setQuery && findSettings(), () => {}); @@ -20012,6 +20013,7 @@ function searchSettings(q) { const v = $("#view-settings"); v.classList.remove("set-searching"); for (const n of v.querySelectorAll(".set-miss")) n.classList.remove("set-miss"); + window.setFolds?.(v, 1); $("#setNone").hidden = true; window.setFeatsFind?.([]); setSetTab(setTab); diff --git a/internal/gui/assets/provlinks.js b/internal/gui/assets/provlinks.js index 54054b701..0ddf5fc0e 100644 --- a/internal/gui/assets/provlinks.js +++ b/internal/gui/assets/provlinks.js @@ -3,10 +3,91 @@ // opening the provider's editor. They show only while searching, so // app.js imports this when a search first wants them, and it weighs // nothing on the core. A row goes with its list's plugin (warm-ups), and -// with no such provider to open (findSettings, by its agents). +// with no such provider to open (findSettings, by its agents). The +// settings an agent's sheet builds when it opens (Claude Code's prompt +// cache and commit signature, its own fields under Advanced) and the +// Claude editor's run mode, which aren't in the page until then, have +// rows here too. +const prefLink = (name, en, where, says, open) => { + const row = el("div", "row pref agent-pref-link"), who = el("div", "who"), n = el("div", "name", name); + n.dataset.en = en || name; + who.append(n, el("div", "sub", where)); + if (says) { + const w = el("span", "", says[0]); + w.hidden = true; + w.dataset.en = says[1] || says[0]; + who.append(w); + } + const go = el("button", "text", t("Open")); + go.type = "button"; + go.onclick = open; + row.append(who, go); + return row; +}; +// opened, the row it names is brought into sight and lit once drawn, and +// again if the page draws it anew (the editor once the list is in) +const lightWhen = (find) => { + let n = 0; + const look = () => { + const r = find(); + if (r && !r.classList.contains("flash")) { + const fold = r.closest("details:not([open])"); + if (fold) fold.open = true; + r.scrollIntoView({ block: "center" }); + r.classList.add("flash"); + } + if (++n < 40) setTimeout(look, 50); + }; + look(); +}; +// an agent's sheet's own rows, by the class compactFill gives them +const SHEET_ROWS = { + claude: [["Prompt cache · main conversation", ".claude-cache", 0], ["Prompt cache · subagents", ".claude-cache", 1], ["Commit signature (Co-Authored-By)", ".claude-attribution", 0]], +}; +function sheetLinks(box) { + const by = new Map(); + for (const a of state.agents) { + if (a.id.includes("@wsl:") || !agentPrefsOf(a)) continue; + const rows = [...(SHEET_ROWS[kindOf(a)] || []).map(([label, sel, i]) => ({ label, sel, i })), + ...(a.own || []).map((f) => ({ label: f.label[0].toUpperCase() + f.label.slice(1), own: true }))]; + for (const r of rows) { + const k = r.label + "\n" + (r.sel || "own"); + by.has(k) ? by.get(k).agents.push(a) : by.set(k, { ...r, agents: [a] }); + } + } + for (const { label, sel, i, own, agents } of by.values()) { + box.append(prefLink(t(label), label, t("In {agent}'s settings, on the Agents page", { agent: agents.map((a) => a.name).join(", ") }), null, async () => { + if (await show("agents") === false) return; + await openAgentPrefs(agents[0]); + lightWhen(() => own ? [...document.querySelectorAll("#modal .own-fields .row")].find((r) => r.querySelector(".name")?.textContent === t(label)) : document.querySelectorAll("#modal " + sel)[i]); + })); + } +} +// opens the editor of the first provider of these agents, Advanced open +async function openIn(agents, find) { + if (!await show("providers")) return; + const p = providers?.providers.find((x) => agents.includes(x.account?.agent)); + if (!p) return; + advanced = { of: p.id, open: true }; + await openProvider(p.id); + lightWhen(find); +} +// Settings' search: a hit under a folded Advanced is unfolded while the +// search lasts (findSettings), and folded again when it ends +window.setFolds = (v, end) => { + for (const d of v.querySelectorAll(end ? "details[data-found]" : "details:not([open]):not([hidden])")) { + if (end) delete d.dataset.found, d.open = false; + else if ([...d.querySelectorAll(".row:not(.set-miss)")].some((r) => !r.closest("[hidden]") && !featureHides(r))) d.open = d.dataset.found = true; + } +}; window.provPrefLinksDraw = function () { const box = $("#provPrefLinks"); box.replaceChildren(); + // the Claude editor's run mode, drawn as the editor opens + const run = prefLink(t("Claude Code runs as"), "Claude Code runs as", t("In {provider}'s editor, on the Providers page", { provider: subNames(["claude"]) }), + [t("Interactive mode (TUI)") + " claude -p", "Interactive mode (TUI) claude -p"], () => openIn(["claude"], () => $(".editor .claude-mode"))); + run.agents = ["claude"]; + box.append(run); const ids = [...new Set(Object.values(PROV_PREFS).flat())]; const by = (list) => list.classList.contains("ci-plugin") ? [list.dataset.provider] : Object.keys(PROV_PREFS).filter((k) => PROV_PREFS[k].includes(list.id)); for (const list of [...ids.map((id) => $("#" + id)), ...$("#pluginCheckinList").children]) { @@ -15,36 +96,13 @@ window.provPrefLinksDraw = function () { for (const r of list.querySelectorAll(":scope > .row.pref:not(.ci-acct):not(.ci-now-row):not(.warm-now):not([hidden])")) { const name = r.querySelector(".who > .name"); if (!name) continue; - const row = el("div", "row pref agent-pref-link"); + const sub = r.querySelector(".sub:not(.err)"); + const row = prefLink(name.textContent, name.dataset.en, t("In {provider}'s editor, on the Providers page", { provider: subNames(agents.slice(0, 1)) }), sub && [sub.textContent, sub.dataset.en], () => openIn(agents, () => r.isConnected && r)); const f = list.closest("[data-feature]")?.dataset.feature; if (f) row.dataset.feature = f; row.agents = agents; - const who = el("div", "who"); - const n = el("div", "name", name.textContent); - n.dataset.en = name.dataset.en || name.textContent; - who.append(n, el("div", "sub", t("In {provider}'s editor, on the Providers page", { provider: subNames(agents.slice(0, 1)) }))); - const sub = r.querySelector(".sub:not(.err)"); - if (sub) { - const says = el("span", "", sub.textContent); - says.hidden = true; - says.dataset.en = sub.dataset.en || sub.textContent; - who.append(says); - } - const go = el("button", "text", t("Open")); - go.type = "button"; - go.onclick = async () => { - if (!await show("providers")) return; - const p = providers?.providers.find((x) => agents.includes(x.account?.agent)); - if (!p) return; - // its field is under the editor's Advanced: opened, and the row lit - advanced = { of: p.id, open: true }; - await openProvider(p.id); - if (!r.isConnected) return; - r.scrollIntoView({ block: "center" }); - r.classList.add("flash"); - }; - row.append(who, go); box.append(row); } } + sheetLinks(box); }; diff --git a/internal/gui/tests/settings-search-reach.test.cjs b/internal/gui/tests/settings-search-reach.test.cjs new file mode 100644 index 000000000..0f1266a54 --- /dev/null +++ b/internal/gui/tests/settings-search-reach.test.cjs @@ -0,0 +1,137 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// What Settings' search reaches beyond the rows drawn in its page: +// - a tab's id is not a word of it: "usage" doesn't bring all of +// Allowances (its id), only the rows that say it; +// - a hit under a folded Advanced (Network and sharing's Name) is +// unfolded while the search lasts, and folded again when it ends; +// - the settings an agent's sheet builds as it opens (Claude Code's +// prompt cache and commit signature, its own fields) and the Claude +// editor's run mode (claude -p) are found as links, and Open reaches +// the row, lit. +// Every language, 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 { provPrefsProviders, agentRow } = require("./reader.cjs"); + +const assets = path.resolve(__dirname, "../assets"); + +function server(lang, posts) { + const cur = { + theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd", textSize: 100, + proxy: "", redact: false, redactPersonal: false, redactWords: [], trayUsage: "", trayUsageEvery: 3, + version: "0.1.400", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425", + proxyNow: "none", proxySource: "none", visionModels: [], imageGenModels: [], workbuddyCheckins: [], lanURLs: [], + claudeCache: [{ knob: "cache_ttl", value: "1h" }, { knob: "subagent_cache_ttl" }], + fx: { rate: 7.2, at: new Date().toISOString(), stale: false }, + }; + const claude = { ...agentRow("claude", "Claude Code"), own: [{ key: "permissions.defaultMode", label: "permission mode", value: "", options: [{ value: "plan" }] }] }; + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + if (req.method() !== "GET" && url.pathname !== "/api/update/using" && url.pathname !== "/api/page-away") posts.push(url.pathname); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false,textSize:100};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [claude, agentRow("codex", "Codex")], profiles: [], settings: { lang, theme: "light", textSize: 100 }, fx: cur.fx }); + if (url.pathname === "/api/settings") return json(cur); + if (url.pathname === "/api/claude/mode") return json({ why: "", tui: true }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/providers") return json(provPrefsProviders(["codex", "claude"], { codex: "ChatGPT", claude: "Claude" })); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/window/fit") return route.fulfill({ status: 204 }); + 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 parts = (page) => page.evaluate(() => [...document.querySelectorAll("#view-settings > [role=tabpanel]")].filter((p) => p.getClientRects().length).map((p) => p.id.replace("setPage-", ""))); +const seen = (page, sel) => page.locator(sel).first().evaluate((e) => !!e.getClientRects().length && getComputedStyle(e).visibility !== "hidden"); + +const LANGS = ["en", "zh", "zh-TW", "ja", "de"]; +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": what Settings' search reaches", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const open = async (lang, posts) => { + const context = await browser.newContext({ viewport: { width: 900, height: 700 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.errors = []; + page.on("pageerror", (e) => { if (engine === "webkit" && /due to access control checks/.test(e.message)) return; page.errors.push(e.message); }); + await page.route("**/*", server(lang, posts)); + await page.goto("http://magpie.test/?view=settings&tab=general"); + await page.locator("#themeSegs .opt").first().waitFor(); + await page.locator("#netMoreList .instance-name-row").waitFor({ state: "attached" }); + return page; + }; + const type = async (page, s) => { + await page.locator("#setQ").fill(s); + await page.waitForTimeout(150); + }; + const link = (page, name) => page.locator("#provPrefLinks .agent-pref-link:visible", { has: page.locator(".name", { hasText: name }) }); + + for (const lang of LANGS) { + await t.test(lang, async () => { + const posts = []; + const page = await open(lang, posts); + const tr = (s, vars) => page.evaluate(([s, vars]) => t(s, vars), [s, vars]); + + // "usage" is Allowances' id, not a word of it: its rows that don't + // say it stay out + await type(page, "usage"); + assert.equal(await seen(page, "#trayCostSegs"), false, "Menu bar cost isn't brought by the tab's id"); + + // a hit under Network and sharing's folded Advanced is unfolded + assert.equal(await page.locator("#netMore").evaluate((d) => d.open), false); + await type(page, await tr("Shown in the browser tab’s title")); + assert((await parts(page)).includes("network"), "under Network and sharing"); + assert.equal(await page.locator("#netMore").evaluate((d) => d.open), true, "its Advanced unfolded"); + assert(await seen(page, "#netMoreList .instance-name-row"), "the Name row shows"); + // and folded again when the search ends + await type(page, ""); + assert.equal(await page.locator("#netMore").evaluate((d) => d.open), false, "folded again after the search"); + + // Claude Code's sheet's rows, found as links + for (const [word, name] of [["Co-Authored", "Commit signature (Co-Authored-By)"], [(await tr("Prompt cache · subagents")).split(" · ")[0], "Prompt cache · subagents"], [await tr("Permission mode"), "Permission mode"]]) { + await type(page, word); + const l = link(page, await tr(name)); + assert.equal(await l.count(), 1, `"${word}" finds ${name}`); + assert.equal(await l.locator(".sub").textContent(), await tr("In {agent}'s settings, on the Agents page", { agent: "Claude Code" })); + } + // and the Claude editor's run mode, by claude -p + await type(page, "claude -p"); + assert.equal(await link(page, await tr("Claude Code runs as")).count(), 1, "claude -p finds Claude Code's run mode"); + assert.deepEqual(posts, [], "searching posts nothing"); + + // Open reaches the row in the sheet, lit + await type(page, "Co-Authored"); + await link(page, await tr("Commit signature (Co-Authored-By)")).locator("button").click(); + await page.locator("#modal .claude-attribution.flash").waitFor(); + await page.keyboard.press("Escape"); + await page.locator("#modal").waitFor({ state: "hidden" }); + // its own field, under the sheet's folded Advanced, unfolded + await page.goto("http://magpie.test/?view=settings&tab=general"); + await page.locator("#themeSegs .opt").first().waitFor(); + await type(page, await tr("Permission mode")); + await link(page, await tr("Permission mode")).locator("button").click(); + await page.locator("#modal .own-fields[open] .own-field.flash").waitFor(); + await page.keyboard.press("Escape"); + await page.locator("#modal").waitFor({ state: "hidden" }); + // the run mode's Open reaches the Claude editor's row + await page.goto("http://magpie.test/?view=settings&tab=general"); + await page.locator("#themeSegs .opt").first().waitFor(); + await type(page, "claude -p"); + await link(page, await tr("Claude Code runs as")).locator("button").click(); + await page.locator(".editor .claude-mode.flash").waitFor(); + assert.deepEqual(page.errors, []); + await page.context().close(); + }); + } + }); +}