diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index ea0ec7d40..0953a4094 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -18,7 +18,7 @@ three. | Browser mode | `StartWeb` serves the page and the gateway for `magpie web`. The browser signs in with a run key in a link. Added to a phone's home screen the page opens as an app of its own, with no browser bars (ninja_s6114 on Discord): `index.html` names `manifest.json` (display standalone), an apple-touch-icon and the iOS meta tags, the status bar keeps its own ground (`default`), and its theme colours match only `(display-mode: standalone)`, so a browser's tab and the app's windows take none. `webGuard` serves those three files (`webAppFiles`: the manifest, `icons/apple-touch-icon.png`, `icons/icon-512.png`) without the key, to GET and HEAD at those exact paths alone, as a home screen may ask without the cookie; see `TestWebAppAddsToHomeScreen` and `web-app-standalone.test.cjs`. The cookie is SameSite=Lax, which a browser sends with any request from the same site, other ports and sibling subdomains included, so `webOwnPage` answers `/api` for the page's own origin only: a write goes through net/http's `CrossOriginProtection` (Sec-Fetch-Site same-origin or none; from a browser without it, an Origin that is absent or names the Host or `MAGPIE_PUBLIC_URL`), and any request whose Sec-Fetch-Site says another origin sent it is refused, a GET too; see `TestWebAPIAnswersItsOwnPageOnly`. The desktop window's `/api` is in-process with no cookie and isn't held to it. Gateway mode shows every page but Agents on a machine that is only a gateway (`GATEWAY_HIDES`); the Library has its MCP servers and the MCP router alone, for other computers' apps to reach with a gateway key (treeman_26897 on Discord, `gateway-mode.test.cjs`, `library-mcp-agentless.test.cjs`). `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; never an event stream, which gzip would hold back until its buffer fills); the app's own windows read the page in-process and get it uncompressed. The page's port answers the gateway's client routes too (`onePort`, `gateway.ClientPath`: `/v1/…`, `/v1beta/…`, `/mcp/…`, the Codex backend path and the routes without `/v1`; never `/api/*` or `/_magpie/*`, never a path that isn't clean), so one reverse-proxy location serves the page and the agents (zgcwkj on Discord). They skip the page's key and gzip and go to the gateway's own guards, always as a request from another machine (`gateway.FromPagePort`, the `X-Magpie-Page-Port` mark: `local` is false for it, from loopback too and under `MAGPIE_TRUST_PROXY`, so magpie must be shared and the request carry an enabled gateway key), since a raw TCP forward or a proxy that adds no forwarding header reaches this port from loopback looking like an agent here (reported privately by Coffemon); agents here use the gateway's own port. `Server.Front` (lanGuard over Handler) serves them in process when this process serves the gateway, or `toGateway`, a reverse proxy to `gateway.URL()`, when another magpie does; it keeps the Host, the forwarding headers and the mark, adds X-Forwarded-For for a peer that isn't loopback, and the peer's loopback address as X-Forwarded-For when none came, so a gateway of an older magpie that doesn't know the mark still asks for a key. `lanGuard` moves the mark into the request's context and takes the header off, so it never goes upstream. The page itself calls no client route. See `TestWebOnePortServedHere`, `TestWebOnePortServedElsewhere`, `TestWebOnePortAgentsHereUseTheGatewayPort`, `TestPagePortMarkIsNeverLocal` and `TestClientPathCoversHandler`. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go), [`oneport.go`](../../internal/gateway/oneport.go) | | The app's page in a browser | Settings › Network and sharing › Browser access (`renderWebPage` in `plugins/gateway/settings.js`, drawn with the Web pages rows) has the app serve its own page to a browser while it runs, so a tunnel (Cloudflare Tunnel, SSH) or a computer on the network can reach it without `magpie web` kept running in a terminal (jiakun_zhao on X). Off, This computer (`127.0.0.1`, which a tunnel's service points at) or Local network (every address; a "Not encrypted" row without `--tls-cert`). It is `magpie web`'s page and guard, not a second kind: `startAppPage` (from `Run`, after `startBackend`) serves `webServed` over a `Handler` of its own, whose `Windows` is `appWebHost` (a browser tab for `isWeb`, but not `ownWeb`, so the app's windows aren't taken for `magpie web`'s: `webPage` and gateway mode stay the app's; quitting quits the app, and a restart to update from it brings back the windows the app has up, `restartFrom`). The key is always asked for: no mode serves without it. It lives with the mode and port in `web-page.json` beside settings.json (0600, never in settings.json, so sync and backup don't carry it), is made the first time the page is turned on, kept across restarts (a browser's cookie stays good), and replaced by New key, which turns away every browser signed in with the old one (the guard is swapped atomically, `appPage.cur`). A file that can't be read, or names no known mode, is off and says why; Settings rewrites it only given a whole choice. A port another program holds (`magpie web`; the magpie before a restart to update) is said and tried again every 4 s (`appPageRetry`); the port must be 1024 up and not the gateway's. `GET/POST /api/web-page` are on the app's own windows' API only, never a browser's, so a browser on the page can neither read the key it came in without nor turn the page off under itself. `magpie web` on the port the app serves prints the app's link and opens it rather than starting a second (`gui.AppPage`, `samePort`). Sessions are warmed once a process however many `Handler`s there are (`warmOnce`). See `TestAppPageServesOnlyWithItsKey`, `TestAppPageWaitsForABusyPort`, `TestAppPageUnreadFileServesNothing`, `TestAppPageTurnsDownBadChoices`, `TestAppPageBrowserIsATab` and `browser-access.test.cjs`. | [`apppage.go`](../../internal/gui/apppage.go), [`web_cli.go`](../../internal/cli/web_cli.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//` (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; 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 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. 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, 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 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. 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) | | 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) | | 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) | diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 526c7a2de..7a127da83 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -394,7 +394,16 @@ body.side-drag, body.side-drag * { cursor: col-resize !important; user-select: n the button and the magpie beside them, level with them (see .top above) */ body.window.mac .side-top { height: calc(50px / var(--zoom, 1)); padding: calc(2px / var(--zoom, 1)) 0 0 calc(96px / var(--zoom, 1)); } .side-scroll { flex: 1; min-height: 0; overflow-y: auto; padding: 0 10px 10px; } -.side-foot { flex: none; max-height: 55%; overflow-y: auto; display: flex; flex-direction: column; gap: 1px; padding: 8px 10px 10px; border-top: .5px solid var(--line-2); } +/* laid from its end, Settings' button and the gateway's line kept where + they are as Settings' tabs open over the button and the foot grows up + (jen_celeus on X), and a foot too short for them scrolls from its end. + The order is the reading order, top down: tabs, Settings, the gateway */ +.side-foot { flex: none; max-height: 55%; overflow-y: auto; display: flex; flex-direction: column-reverse; gap: 1px; padding: 8px 10px 10px; border-top: .5px solid var(--line-2); } +/* a foot too short for them scrolls, its rows kept whole */ +.side-foot > * { flex: none; } +.side-foot > .side-gw { order: 0; } +.side-foot > #prefs { order: 1; } +.side-foot > .nav-sub { order: 2; } /* a short window's sidebar keeps no bar beside its pages: a thin one is laid over them while they scroll and fades once they stop, as a Mac's overlay scroll bar does (app.js sideBars), the same in WebKit, WebView2 and @@ -437,6 +446,11 @@ body.side-nav #nav button.has-dot::after { top: 50%; right: 10px; margin-top: -3 /* the open page's tabs, under it on a thin line */ .nav-sub { position: relative; display: flex; flex-direction: column; gap: 1px; margin: 2px 0 6px 16px; padding-left: 8px; } .nav-sub.moving { overflow: hidden; } +/* Settings' tabs, over its button at the sidebar's foot (app.js navSubs), + close to the button they come from; the foot takes more of a short + sidebar while they show */ +.side-foot > .nav-sub { margin: 6px 0 2px 16px; } +.side-foot:has(> .nav-sub) { max-height: 80%; } .nav-sub::before { content: ""; position: absolute; left: 0; top: 3px; bottom: 3px; width: 1px; background: var(--line); } /* rows keep their size while the list unrolls or folds: squeezed, a strip drawn again then (Installed gets its count) marked the selection a third diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index d51261fe4..0687f3789 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -23668,10 +23668,8 @@ function layoutNav() { renderSideToggle(); fitTop(); } -// the sidebar's width, the reader's own once they drag its edge (sideDrag): -// kept for the window, as a Mac app keeps it; none set, app.css's. A narrow -// window has it no wider than a third of itself and a little, so the page -// keeps the room +// the sidebar's width, the reader's own once dragged (sideDrag), else +// app.css's; at most ~a third of a narrow window var SIDE_MIN = 168, SIDE_MAX = 320; var sideW = 0; try { sideW = Math.round(+localStorage.getItem("magpie.sideWidth")) || 0; } catch { /* app.css's, then */ } @@ -23731,10 +23729,7 @@ function sideDrag(edge) { }); addEventListener("resize", () => { if (sideW) sideWidth(); }); } -// a box of the sidebar that runs longer than the window has no bar of its -// own (app.css .side-bar): a thin one is laid over its edge while it -// scrolls and fades once it stops, as a Mac's overlay bar does; held under -// the pointer it stays, and dragged it scrolls the box +// a sidebar box's overlay bar, as a Mac's (app.css .side-bar) function sideBars() { const side = $("#side"); if (!side) return; @@ -23754,7 +23749,9 @@ function sideBars() { bar.style.top = box.offsetTop + "px"; bar.style.height = ch + "px"; const h = Math.max(24, Math.round(ch * ch / sh)); - const y = Math.round((ch - h) * box.scrollTop / (sh - ch)); + // the foot is laid from its end (app.css): scrollTop 0 there + const from = getComputedStyle(box).flexDirection === "column-reverse" ? sh - ch : 0; + const y = Math.round((ch - h) * (box.scrollTop + from) / (sh - ch)); thumb.style.height = h + "px"; thumb.style.transform = `translateY(${y}px)`; }; @@ -23853,8 +23850,10 @@ function navSubs() { navSubsAt = sig; let box = document.querySelector(".nav-sub:not(.leaving)"); const want = side && at && items.length > 1; + // Settings' list is over its button, which stays put (jen_celeus on X) + const above = at?.id === "prefs"; // another page's list folds away as this one's opens, both at once - if (box && (!want || box.dataset.view !== view || box.previousElementSibling !== at)) { navSubLeave(box); box = null; } + if (box && (!want || box.dataset.view !== view || (above ? box.nextElementSibling : box.previousElementSibling) !== at)) { navSubLeave(box); box = null; } if (want) { const fresh = !box; if (fresh) { @@ -23869,7 +23868,7 @@ function navSubs() { e.preventDefault(); all[(to + all.length) % all.length].focus(); }; - at.after(box); + if (above) at.before(box); else at.after(box); } box.setAttribute("aria-label", (at.querySelector("span[data-t]") || at.querySelector("span"))?.textContent || ""); for (const s of box.querySelectorAll(".nav-s")) s.remove(); @@ -24025,8 +24024,12 @@ function navSubEnter(box) { box.classList.add("moving"); box.animate([{ height: "0px", marginTop: "0px", marginBottom: "0px", opacity: 0 }, to], { duration: 300, easing: NAV_EASE }) .finished.then(() => box.classList.remove("moving"), () => {}); - [...box.querySelectorAll(".nav-s")].forEach((s, i) => s.animate( - [{ opacity: 0, transform: "translateY(-6px)" }, { opacity: 1, transform: "none" }], + // Settings' rises from its button, the nearest row first + const up = !!box.closest(".side-foot"); + const rows = [...box.querySelectorAll(".nav-s")]; + if (up) rows.reverse(); + rows.forEach((s, i) => s.animate( + [{ opacity: 0, transform: `translateY(${up ? 6 : -6}px)` }, { opacity: 1, transform: "none" }], { duration: 260, delay: 40 + Math.min(i, 12) * 20, easing: NAV_EASE, fill: "backwards" })); box.querySelector(".nav-hl").animate([{ opacity: 0 }, { opacity: 1 }], { duration: 200, delay: 80, fill: "backwards" }); } diff --git a/internal/gui/tests/sidebar-settings-steady.test.cjs b/internal/gui/tests/sidebar-settings-steady.test.cjs new file mode 100644 index 000000000..6e878b1bd --- /dev/null +++ b/internal/gui/tests/sidebar-settings-steady.test.cjs @@ -0,0 +1,114 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Settings at the sidebar's foot stays where it was clicked (jen_celeus on +// X): its tabs used to be listed under it, so the foot grew upward and the +// button rose with it, out from under the pointer. The list now opens +// above the button, growing from it, and folds back the same way; the +// button never moves, while the list unrolls or after, in a wide window, a +// narrow one, a short one and one too short for the whole list. +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_ASSETS || path.resolve(__dirname, "../assets")); + +function serve(lang) { + 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:${JSON.stringify(lang)},theme:"light",web:false,sideGateway:{url:"http://127.0.0.1:3425",running:true,boot:true}};` }); + 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/providers") return json({ providers: [], presets: [], excluded: [], gateway: { url: "http://127.0.0.1:3425", running: true, window: true } }); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +// every frame for a while, the furthest Settings' button got from where it was +const drift = (page, ms) => page.evaluate((ms) => new Promise((done) => { + const b = document.querySelector("#prefs"), at = b.getBoundingClientRect(); + let most = 0; + const end = performance.now() + ms; + const look = () => { + const r = b.getBoundingClientRect(); + most = Math.max(most, Math.abs(r.top - at.top), Math.abs(r.bottom - at.bottom), Math.abs(r.left - at.left), Math.abs(r.right - at.right)); + if (performance.now() < end) requestAnimationFrame(look); else done(most); + }; + requestAnimationFrame(look); +}), ms); + +const sizes = [ + { name: "wide", width: 1200, height: 760 }, + { name: "narrow", width: 760, height: 760, side: true }, + { name: "short", width: 1200, height: 460 }, + // too short for the whole list: the foot scrolls, its end in sight + { name: "tiny", width: 1200, height: 340, over: true }, +]; +const langs = ["en", "zh", "zh-TW", "ja", "de"]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: Settings stays where it was clicked`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const size of sizes) for (const lang of langs) await t.test(`${size.name} ${lang}`, async () => { + const context = await browser.newContext({ viewport: { width: size.width, height: size.height } }); + if (size.side) await context.addInitScript(() => { try { localStorage.setItem("magpie.navLayout", "side"); } catch {} }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + await page.goto("http://magpie.test/"); + await page.waitForSelector("#nav button.on"); + assert.ok(await page.evaluate(() => document.body.classList.contains("side-nav")), "the sidebar shows"); + const prefs = page.locator("#side .side-foot #prefs"); + const before = await prefs.boundingBox(); + + // clicked, the list unrolls and the button stays under the pointer + await page.mouse.click(before.x + before.width / 2, before.y + before.height / 2); + const opening = await drift(page, 700); + const subs = page.locator("#side .nav-sub:not(.leaving) .nav-s"); + await subs.first().waitFor(); + assert.equal(await subs.count(), 8, "Settings' tabs are listed"); + const after = await prefs.boundingBox(); + assert.ok(opening < 1, `the button moved ${opening}px while the list opened`); + assert.ok(Math.abs(after.y - before.y) < 1 && Math.abs(after.x - before.x) < 1, `the button stays put: ${JSON.stringify(before)} then ${JSON.stringify(after)}`); + assert.ok(await page.locator("#prefs").evaluate((b) => b.classList.contains("on")), "Settings is open"); + // the list grows from the button: it sits right above it, the open tab in sight + const [listBottom, btnTop] = await page.evaluate(() => [document.querySelector(".nav-sub:not(.leaving)").getBoundingClientRect().bottom, document.querySelector("#prefs").getBoundingClientRect().top]); + assert.ok(listBottom <= btnTop + 0.5 && btnTop - listBottom < 12, `the list is just above the button: ${listBottom} ${btnTop}`); + // and is read in the order shown, tabs then Settings then the gateway + assert.deepEqual(await page.locator(".side-foot").evaluate((f) => [...f.children].map((c) => c.id || c.className)), ["nav-sub", "prefs", "sideGw"], "read top down"); + const inSight = (sel) => page.locator(sel).evaluate((s) => { + const r = s.getBoundingClientRect(), f = s.closest(".side-foot").getBoundingClientRect(); + return r.top >= f.top - 0.5 && r.bottom <= f.bottom + 0.5; + }); + assert.ok(await inSight("#prefs"), "the button is in sight"); + const over = await page.locator(".side-foot").evaluate((f) => f.scrollHeight > f.clientHeight + 1); + assert.equal(over, !!size.over, "the foot scrolls only when the list can't fit"); + if (!size.over) assert.ok(await inSight(".nav-s.cur"), "the open tab is in sight"); + + // a tab picked there: the button still where it was + await page.locator(".nav-s[data-of=setTab-network]").click(); + await page.waitForFunction(() => document.querySelector("#setTab-network").classList.contains("on")); + assert.ok((await drift(page, 300)) < 1, "picking a tab leaves the button put"); + assert.ok(Math.abs((await prefs.boundingBox()).y - before.y) < 1); + + // another page: the list folds away and the button never moved + await page.locator('#nav button[data-view="agents"]').click(); + const closing = await drift(page, 600); + await page.waitForFunction(() => !document.querySelector(".nav-sub")); + assert.ok(closing < 1, `the button moved ${closing}px while the list folded`); + assert.ok(Math.abs((await prefs.boundingBox()).y - before.y) < 1, "the button is where it began"); + + assert.deepEqual(errors, []); + await context.close(); + }); + }); +}