diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index c3336695f..96e7f2b62 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -19,7 +19,7 @@ three. | 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) | | Another magpie in a window | Settings › Network and sharing › Another magpie (`renderRemote` in `plugins/gateway/settings.js`) opens a magpie elsewhere, a server's (`magpie daemon install --web`, `magpie web`, another app's Browser access), in a window of the app's own, so its routing and usage are read from the desktop (xuanwo on X). The window (`OpenRemote`, `remote_app.go`) loads that magpie's own web page with `?k=` and signs in through its `webGuard` as a browser does: nothing is served here, and the page in it reaches that magpie alone (a remote page gets no bound calls). The address is the link that magpie printed (its `k=` taken out as the key) or a bare address, https:// when no scheme is typed; plain http only to an IP, localhost, a `.local` or a one-word name (`remoteAddr`), as a Mac's webview allows, so the key never crosses the internet in the clear. Before the window opens, `remoteProbe` asks for the link without following it: only a 303 setting a `magpie_web_*` cookie is that magpie taking the key; a 401, a 403 (allowed addresses), an untrusted certificate, no answer or anything else is said in Settings. Address and key live in `remote-magpie.json` beside settings.json (0600, never in settings.json); `GET /api/remote` says the address and whether a key is kept, never the key, and `POST /api/remote` with no key uses the one kept for the same address. The routes are on the app's own windows' API only (`!isWeb`), and a host that can't open windows refuses. See `TestRemoteAddr`, `TestRemoteOpensTheOtherMagpie`, `TestRemoteNotMagpie`, `TestRemoteNotOnBrowserPages` and `another-magpie.test.cjs`. | [`remote.go`](../../internal/gui/remote.go), [`remote_app.go`](../../internal/gui/remote_app.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; 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) | +| 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. 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`). 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 cc51cfc5f..9458edfbc 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -339,24 +339,43 @@ body:not(.side-nav) #nav button[data-view="groups"], body.side-nav .rt-togroups .top.packed .seg { min-width: 0; flex: 0 1 auto; overflow-x: auto; overflow-y: hidden; scrollbar-width: none; } .top.packed .seg::-webkit-scrollbar { display: none; } /* magpie web on a phone, or a browser as narrow (phoneWeb): the magpie and - the icons in a row, the tabs at their size in a row of their own under - them, sliding sideways when they don't fit (they were squeezed into the - room between, too small to read or tap) */ + the icons in the header, the pages a tab bar at the foot, as an iPhone + app's: each tab its mark over its word, five at most, the fifth More + when there are more (phonetabs.js). A strip that slid sideways hid the + pages past its edge (geraldpppppp on X) */ @media (max-width: 760px), (pointer: coarse) and (max-width: 1024px) { + body.web:not(.panel) { --tabbar: calc(50.5px + env(safe-area-inset-bottom)); padding-bottom: var(--tabbar); } body.web .top { - height: auto; min-height: 48px; flex-wrap: wrap; gap: 4px 8px; - padding: calc(6px + env(safe-area-inset-top)) max(12px, env(safe-area-inset-right)) 8px max(12px, env(safe-area-inset-left)); + height: auto; min-height: 48px; gap: 4px 8px; + padding: calc(6px + env(safe-area-inset-top)) max(12px, env(safe-area-inset-right)) 4px max(12px, env(safe-area-inset-left)); } body.web .top .brand, body.web .top .actions { min-height: 40px; align-items: center; } - body.web .top #nav { - position: relative; left: auto; top: auto; transform: none; - order: 3; flex: 0 0 100%; min-width: 0; max-width: 100%; - overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: none; + body.web:not(.panel) .top #nav { + position: fixed; z-index: 15; left: 0; right: 0; top: auto; bottom: 0; transform: none; + display: flex; height: var(--tabbar); padding: 0 max(4px, env(safe-area-inset-right)) env(safe-area-inset-bottom) max(4px, env(safe-area-inset-left)); + border-radius: 0; border-top: .5px solid var(--line); + background: color-mix(in srgb, var(--bg) 86%, transparent); + -webkit-backdrop-filter: saturate(1.6) blur(20px); backdrop-filter: saturate(1.6) blur(20px); } - body.web .top #nav::-webkit-scrollbar { display: none; } - body.web .top #nav button { flex: none; height: 40px; padding: 0 14px; font-size: 14px; } + body.web:not(.panel) .top #nav > :is(.thumb, .tb-over), body.web:not(.side-nav, .panel) .top #nav > [data-view="groups"] { display: none; } + body.web:not(.panel) .top #nav > button { + flex: 1 1 0; min-width: 0; height: 50px; padding: 5px 2px 3px; border-radius: 0; + display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px; + font-size: 10.5px; font-weight: 500; line-height: 1.1; color: var(--muted); + } + body.web:not(.panel) .top #nav > button.on { color: var(--fg); } + body.web:not(.panel) .top #nav > button > span { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + body.web:not(.panel) .top #nav .nav-ic { display: block; flex: none; width: 23px; height: 23px; } + body.web:not(.panel) .top #nav > button.has-dot::after { top: 5px; right: calc(50% - 17px); } body.web .top .actions { gap: 4px; } + /* a status line comes up over the bar, not under it */ + html body.web:not(.panel) :is(.foot .status:not(:empty):not(.lift), .status.lift) { bottom: calc(var(--tabbar) + 10px); } } +/* More's menu: each page with its tab's mark */ +.nav-more-menu .pm-head { display: none; } +.nav-more-menu .pm-item { align-items: center; gap: 10px; padding: 9px 10px; } +.nav-more-menu .nav-ic { display: block; flex: none; width: 20px; height: 20px; color: var(--fg-2); } +.nav-more-menu .pm-name { font-size: 14px; } @keyframes update-in { from { opacity: 0; max-width: 0; margin-right: 0; padding: 0; } } @keyframes spin { to { transform: rotate(360deg); } } @@ -4338,7 +4357,7 @@ body.panel .modal { padding: 16px 12px; } body.web .view { --view-left: max(12px, env(safe-area-inset-left)); --view-right: max(12px, env(safe-area-inset-right)); - padding: 2px max(0px, calc(var(--view-right) - var(--bar, 0px))) max(12px, env(safe-area-inset-bottom)) var(--view-left); + padding: 2px max(0px, calc(var(--view-right) - var(--bar, 0px))) 12px var(--view-left); /* the tab bar keeps the home indicator clear */ } body.web .foot .status { min-width: 0; overflow-wrap: anywhere; } body.web .row-head { height: auto; min-height: 40px; flex-wrap: wrap; gap: 4px; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 0b98f0d9f..8899748f8 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -23202,7 +23202,7 @@ async function show(v) { $("#pageTitle").textContent = t(title); if (mode === "window") { markNav(v); - if (!sideNav()) { slide($("#nav"), "nav"); navInSight(); } + if (!sideNav()) slide($("#nav"), "nav"); else navTopGo($("#nav").querySelector("button[data-view].on"), true); } $("#prefs").classList.toggle("on", v === "settings"); @@ -23542,18 +23542,9 @@ function wag() { document.querySelector(".brand")?.addEventListener("mouseenter", wag); setTimeout(wag, 250); -// magpie web on a phone, or a browser as narrow: the header is two rows, -// the magpie and the icons over the tabs, which scroll sideways when they -// don't fit, the one open kept in sight +// magpie web on a phone, or a browser as narrow: the tabs are a bar at the foot function phoneWeb() { return document.body.classList.contains("web") && matchMedia("(max-width: 760px), (pointer: coarse) and (max-width: 1024px)").matches; } -function navInSight() { - const nav = $("#nav"), on = nav?.querySelector("button.on"); - if (!phoneWeb() || !on || nav.scrollWidth <= nav.clientWidth) return; - const l = on.offsetLeft - 16, r = on.offsetLeft + on.offsetWidth + 16 - nav.clientWidth; - if (nav.scrollLeft > l) nav.scrollLeft = l; - else if (nav.scrollLeft < r) nav.scrollLeft = r; -} -matchMedia("(max-width: 760px), (pointer: coarse) and (max-width: 1024px)").addEventListener?.("change", () => { layoutNav(); fitTop(); navInSight(); }); +matchMedia("(max-width: 760px), (pointer: coarse) and (max-width: 1024px)").addEventListener?.("change", () => { layoutNav(); fitTop(); }); // A narrow window has no room for the whole header: the name goes, leaving // the magpie, and Update becomes its arrow; narrower still, the tabs stop @@ -23623,7 +23614,8 @@ try { navPick = localStorage.getItem("magpie.navLayout") || ""; } catch { /* by if (navPick !== "side" && navPick !== "top") navPick = ""; function layoutNav() { if (mode !== "window") return; - // magpie web on a phone has its own tab bar and no title bar + // magpie web on a phone has its own tab bar (phonetabs.js) and no title bar + if (phoneWeb()) import("./phonetabs.js").catch(() => {}); const on = !phoneWeb() && (navPick ? navPick === "side" : sideQuery.matches); if (layoutNav.done && on === sideNav()) { // the button goes with the phone's layout all the same @@ -23654,7 +23646,7 @@ function layoutNav() { navSubs.quiet = true; navSubs(); navSubs.quiet = false; - if (!on) { slide(nav, "nav"); navInSight(); } else { sideGwRead(); renderSideGw(); } + if (!on) slide(nav, "nav"); else { sideGwRead(); renderSideGw(); } navTopGo(navTopOn(), false); sideWidth(); renderSideToggle(); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 0f05edab5..a30fe6745 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4620,6 +4620,7 @@ const I18N = { "npm didn't answer: {error}": "npm 没有响应:{error}", "Couldn't read the folder's README: {error}": "无法读取该文件夹的 README:{error}", "More in Plugins": "插件中还有更多", + "More pages": "更多", "Subscriptions magpie doesn't sign in to itself: install a plugin for one in the Plugins tab": "magpie 未内置的订阅:在「插件」页安装对应插件即可", "Agents magpie has no setup of its own for: install a plugin for one in the Plugins tab, and it is listed here": "magpie 未内置的 Agent:在「插件」页安装对应插件,它就会出现在这里", "look for a plugin": "找找插件", @@ -9525,6 +9526,7 @@ const I18N = { "npm didn't answer: {error}": "npm 沒有回應:{error}", "Couldn't read the folder's README: {error}": "無法讀取該資料夾的 README:{error}", "More in Plugins": "外掛中還有更多", + "More pages": "更多", "Subscriptions magpie doesn't sign in to itself: install a plugin for one in the Plugins tab": "magpie 未內建的訂閱:在「外掛」頁安裝對應外掛即可", "Agents magpie has no setup of its own for: install a plugin for one in the Plugins tab, and it is listed here": "magpie 未內建的 Agent:在「外掛」頁安裝對應外掛,它就會出現在這裡", "look for a plugin": "找找外掛", @@ -14451,6 +14453,7 @@ const I18N = { "npm didn't answer: {error}": "npm から応答がありません:{error}", "Couldn't read the folder's README: {error}": "フォルダの README を読めませんでした:{error}", "More in Plugins": "プラグインにもっとあります", + "More pages": "その他", "Subscriptions magpie doesn't sign in to itself: install a plugin for one in the Plugins tab": "magpie が自分ではサインインしないサブスクリプション:「プラグイン」タブで対応するプラグインをインストールしてください", "Agents magpie has no setup of its own for: install a plugin for one in the Plugins tab, and it is listed here": "magpie に設定が組み込まれていないエージェント:「プラグイン」タブで対応するプラグインをインストールすると、ここに表示されます", "look for a plugin": "プラグインを探す", @@ -19391,6 +19394,7 @@ const I18N = { "npm didn't answer: {error}": "npm hat nicht geantwortet: {error}", "Couldn't read the folder's README: {error}": "README des Ordners konnte nicht gelesen werden: {error}", "More in Plugins": "Mehr unter Erweiterungen", + "More pages": "Mehr", "Subscriptions magpie doesn't sign in to itself: install a plugin for one in the Plugins tab": "Abos, bei denen sich magpie nicht selbst anmeldet: Installieren Sie dafür eine Erweiterung im Tab Erweiterungen", "Agents magpie has no setup of its own for: install a plugin for one in the Plugins tab, and it is listed here": "Agents, für die magpie keine eigene Einrichtung hat: Installieren Sie dafür eine Erweiterung im Tab Erweiterungen, dann erscheint er hier", "look for a plugin": "nach einer Erweiterung suchen", diff --git a/internal/gui/assets/phonetabs.js b/internal/gui/assets/phonetabs.js new file mode 100644 index 000000000..0452fce08 --- /dev/null +++ b/internal/gui/assets/phonetabs.js @@ -0,0 +1,53 @@ +// magpie web on a phone (app.js phoneWeb): the pages are a tab bar at the +// window's foot, as an iPhone app's (app.css). Five fit; with more, the +// fifth is More, a menu of the rest, marked while one of them is open +// (geraldpppppp on X: Agents and the Library were past the edge of a +// strip that scrolled sideways, and nothing said it did). Imported by +// layoutNav the first time the page is a phone's. +const nav = $("#nav"); +const more = el("button", "nav-more"); +more.type = "button"; +more.setAttribute("aria-haspopup", "menu"); +more.setAttribute("aria-expanded", "false"); +more.innerHTML = ''; +const word = el("span"); +more.append(word); +let over = []; + +function fit() { + for (const b of nav.querySelectorAll(".tb-over")) b.classList.remove("tb-over"); + // what the bar has: the pages shown, gateway mode's, a plugin's and + // the switched-off ones left out (app.js navHides, app.css) + const pages = phoneWeb() ? [...nav.querySelectorAll(":scope > button[data-view]")].filter((b) => getComputedStyle(b).display !== "none") : []; + over = pages.length > 5 ? pages.slice(4) : []; + for (const b of over) b.classList.add("tb-over"); + if (!over.length) more.remove(); + else if (nav.lastElementChild !== more) nav.append(more); + // "More" alone is the heatmap's 多; the tab's is its own word + const said = t("More pages"); + word.textContent = said === "More pages" ? "More" : said; + more.setAttribute("aria-label", said); + const open = over.find((b) => b.classList.contains("on")); + more.classList.toggle("on", !!open); + if (open) more.setAttribute("aria-current", "page"); else more.removeAttribute("aria-current"); + more.classList.toggle("has-dot", over.some((b) => b.classList.contains("has-dot"))); + watch.takeRecords(); // its own changes aren't news +} +const watch = new MutationObserver(fit); +// a page shown or left out, the one open, a dot, a language's words +watch.observe(nav, { childList: true, attributes: true, subtree: true, attributeFilter: ["class", "hidden", "data-replaced"] }); +matchMedia("(max-width: 760px), (pointer: coarse) and (max-width: 1024px)").addEventListener?.("change", fit); + +more.onclick = () => { + if (more.classList.contains("open")) return closeProtoMenu(); + const open = over.find((b) => b.classList.contains("on")); + openProtoMenu(more, over.map((b) => ({ v: b.dataset.view, name: b.textContent.trim(), literalName: true })), open?.dataset.view ?? "", + (v) => over.find((b) => b.dataset.view === v)?.click(), "More pages", "nav-more-menu", "right"); + // each page with its tab's mark, as an iPhone's More list has + const box = document.querySelector(".nav-more-menu"); + box?.querySelectorAll(".pm-item").forEach((item, i) => { + const ic = over[i]?.querySelector(".nav-ic"); + if (ic) item.querySelector(".pm-words").before(ic.cloneNode(true)); + }); +}; +fit(); diff --git a/internal/gui/tests/group-from-model-add.test.cjs b/internal/gui/tests/group-from-model-add.test.cjs index f7e162a83..27302de8d 100644 --- a/internal/gui/tests/group-from-model-add.test.cjs +++ b/internal/gui/tests/group-from-model-add.test.cjs @@ -106,11 +106,18 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.mouse.wheel(0, 120); await page.waitForTimeout(60); } - let now = await seen(); + // and back up until the whole of Add is in the view: a press on + // its middle, with its top still under the header, can land on + // the header in WebKit + const whole = () => add.evaluate((btn) => { + const r = btn.getBoundingClientRect(), v = btn.closest("main.view").getBoundingClientRect(); + return r.top >= v.top && r.bottom <= v.bottom; + }); + let now = (await whole()) && (await seen()); for (let i = 0; i < 80 && !now; i++) { - await page.mouse.wheel(0, -120); + await page.mouse.wheel(0, -60); await page.waitForTimeout(60); - now = await seen(); + now = (await whole()) && (await seen()); } assert.ok(now, "Add is under the pointer's reach to be clicked"); await page.mouse.click(now.x, now.y); diff --git a/internal/gui/tests/market-more.test.cjs b/internal/gui/tests/market-more.test.cjs index 800aaf2f1..dc6c71d22 100644 --- a/internal/gui/tests/market-more.test.cjs +++ b/internal/gui/tests/market-more.test.cjs @@ -90,7 +90,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // a click adds cards under the ones shown and moves nothing (the // button brought into view by the wheel, as a reader would) await box.hover(); - while (await button.evaluate((b) => b.getBoundingClientRect().bottom > innerHeight)) await page.mouse.wheel(0, 600); + // (the page ends above a phone's tab bar, so its own foot, not the window's) + while (await button.evaluate((b) => b.getBoundingClientRect().bottom > b.closest("main.view").getBoundingClientRect().bottom)) await page.mouse.wheel(0, 600); // the wheel's last scroll told the page, a frame on await page.evaluate(() => new Promise((ok) => requestAnimationFrame(() => requestAnimationFrame(ok)))); const first = cards.nth(59); diff --git a/internal/gui/tests/mobile-web.test.cjs b/internal/gui/tests/mobile-web.test.cjs index 96204d9a3..7ca018bea 100644 --- a/internal/gui/tests/mobile-web.test.cjs +++ b/internal/gui/tests/mobile-web.test.cjs @@ -13,7 +13,7 @@ const path = require("node:path"); const { execFileSync } = require("node:child_process"); const { test } = require("node:test"); const { chromium, webkit } = require("playwright"); -const { reach } = require("./reader.cjs"); +const { reach, openPage } = require("./reader.cjs"); const { PNG } = require("playwright-core/lib/utilsBundle"); const assets = path.resolve(__dirname, "../assets"); @@ -133,10 +133,10 @@ async function open(browser, lang, width, { original = false, touch = true, open } async function go(page, view) { - // Playwright scrolls each real navigation button into sight before clicking; - // this exercises the phone's horizontal navigation strip too. - await page.locator(view === "settings" ? "#prefs" : `#nav [data-view="${view}"]`).click(); - await page.locator(`#view-${view}`).waitFor(); + // the page's tab, or on a phone's tab bar More and its row for a page + // past the fifth (phonetabs.js) + if (view === "settings") await page.locator("#prefs").click(); + await (view === "settings" ? page.locator(`#view-${view}`).waitFor() : openPage(page, view)); if (view === "library") await page.locator("#view-library .lib-more:not(:disabled)").waitFor(); if (view === "plugins") await page.locator("#view-plugins .pm-find").waitFor(); if (view === "usage") { diff --git a/internal/gui/tests/name-suffix-saved.test.cjs b/internal/gui/tests/name-suffix-saved.test.cjs index 39484ea06..456ae8671 100644 --- a/internal/gui/tests/name-suffix-saved.test.cjs +++ b/internal/gui/tests/name-suffix-saved.test.cjs @@ -13,6 +13,7 @@ // is written. Every language, at a wide and a narrow window. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); +const { openPage } = require("./reader.cjs"); const path = require("node:path"); const { test } = require("node:test"); const { chromium, webkit } = require("playwright"); @@ -113,7 +114,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // the groups tab is the sidebar's; the header's row reaches them from Routing const tab = page.locator('#nav button[data-view="groups"]'); if (await tab.isVisible()) await tab.click(); - else { await page.locator('#nav button[data-view="routing"]').click(); await page.locator("#rtToGroups").click(); } + else { await openPage(page, "routing"); await page.locator("#rtToGroups").click(); } await picked(page.locator(".rt-gnames .opt.on"), await tr("Off")); assert.deepEqual(posts, [], "nothing is written"); assert.deepEqual(errors, []); diff --git a/internal/gui/tests/old-webkit.test.cjs b/internal/gui/tests/old-webkit.test.cjs index 66efbc537..1f4f2d3a7 100644 --- a/internal/gui/tests/old-webkit.test.cjs +++ b/internal/gui/tests/old-webkit.test.cjs @@ -168,10 +168,10 @@ test("compat.js is the first of the page's own scripts", async () => { // panelarrange.js when its Allowances tab's Arrange is, modelfind.js // when Model settings draws many models, agentsmanager.js when the // Agents page's Manage is pressed, agentsuffix.js when an agent's Details - // open; + // open, phonetabs.js when magpie web is laid out for a phone; // the checks above // still read them - for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); + for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); }); test("the styles hold up in Safari 15.0", async () => { diff --git a/internal/gui/tests/phone-no-sideways.test.cjs b/internal/gui/tests/phone-no-sideways.test.cjs index da70320a4..b7b7f18f4 100644 --- a/internal/gui/tests/phone-no-sideways.test.cjs +++ b/internal/gui/tests/phone-no-sideways.test.cjs @@ -9,6 +9,7 @@ // 390 and 430 in English, Chromium and WebKit; no backend, the API is // faked. MAGPIE_ASSETS runs it on older assets. const assert = require("node:assert/strict"); +const { openPage } = require("./reader.cjs"); const fs = require("node:fs/promises"); const path = require("node:path"); const { test } = require("node:test"); @@ -182,7 +183,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", if (process.env.ARTIFACT_DIR) await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-${view}-${sub ?? ""}.png`) }); } // the Requests table, wider than the phone, scrolls in its own box - await page.locator("#nav [data-view=usage]").click(); + await openPage(page, "usage"); await page.locator("#usageTab .opt").nth(1).click(); assert(await page.locator("#ledWrap").evaluate((e) => e.scrollWidth > e.clientWidth + 100), "the table is wider than the phone"); assert.deepEqual(bad, [], "views wider than the phone, or a band held at its foot"); diff --git a/internal/gui/tests/phone-tabs.test.cjs b/internal/gui/tests/phone-tabs.test.cjs new file mode 100644 index 000000000..c504f333e --- /dev/null +++ b/internal/gui/tests/phone-tabs.test.cjs @@ -0,0 +1,158 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// magpie web on a phone (geraldpppppp on X: 优化移动端 UI,为什么看不到agent +// 以及资源库之类的那些入口?). The pages were a strip that scrolled sideways +// with nothing saying it did, and Agents and the Library lay past its edge. +// Now they are a tab bar at the window's foot, as an iPhone app's: five tabs, +// the fifth More when more pages show, its menu the rest with their icons. +// Every page is a tap or two away, the bar covers no part of a page or its +// status line, and nothing scrolls sideways. In gateway mode (Agents left +// out) and with every page; in every language; at 390px. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const LANGS = { en: "More", zh: "更多", "zh-TW": "更多", ja: "その他", de: "Mehr" }; + +function serve(lang, gateway) { + const providers = { providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }; + const state = { agents: [], profiles: [], settings: { lang, theme: "light", redact: true } }; + 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:true${gateway ? ",gateway:true" : ""}};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/settings") return json({ lang, theme: "light", web: true, gatewayOn: gateway, gatewayWhy: gateway ? "no-agents" : "" }); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/plugins/market") return json({ listings: [], state: { bun: true, bunVersion: "1.3.0", plugins: [], picker: false } }); + 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: "" }); } + }; +} + +async function open(browser, lang, gateway, view) { + const context = await browser.newContext({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, hasTouch: true, isMobile: browser.browserType().name() === "chromium", reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.errors = []; + page.on("pageerror", (e) => page.errors.push(e.message)); + await page.route("**/*", serve(lang, gateway)); + await page.goto("http://magpie.test/" + (view ? "?view=" + view : "")); + await page.waitForSelector("#nav", { state: "visible" }); + await page.waitForFunction(() => document.querySelector("#nav .nav-more") || document.querySelectorAll("#nav > button[data-view]").length); + await page.waitForTimeout(300); + return page; +} + +// the tabs the bar shows, in order, each with its box +const tabs = (page) => page.$$eval("#nav > button", (bs) => bs.filter((b) => { + const r = b.getBoundingClientRect(); + return getComputedStyle(b).display !== "none" && r.width > 0 && r.height > 0; +}).map((b) => { + const r = b.getBoundingClientRect(); + return { view: b.dataset.view || "more", on: b.classList.contains("on"), x: r.x, y: r.y, w: r.width, h: r.height, label: b.textContent.trim() }; +})); +// every page the reader may open: the nav's buttons that a phone's bar or its More list carries +const pages = (page) => page.$$eval("#nav > button[data-view]", (bs) => bs.filter((b) => !b.hidden && !b.dataset.replaced && b.dataset.view !== "groups" && getComputedStyle(b).display !== "none" || b.classList.contains("tb-over")).map((b) => b.dataset.view)); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const [lang, moreWord] of Object.entries(LANGS)) { + for (const gateway of [false, true]) { + test(`${engine} ${lang}${gateway ? " gateway mode" : ""}: every page is reachable from the tab bar at 390px`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await open(browser, lang, gateway, gateway ? "providers" : "agents"); + const all = await pages(page); + assert.ok(all.includes("library"), "the Library is a page here"); + assert.equal(all.includes("agents"), !gateway, "Agents shows unless gateway mode leaves it out"); + const bar = await tabs(page); + assert.equal(bar.length, 5, "five tabs: " + JSON.stringify(bar.map((b) => b.view))); + assert.equal(bar[4].view, "more", "the fifth is More"); + assert.equal(bar[4].label, moreWord, "More in this language"); + const vw = await page.evaluate(() => innerWidth), vh = await page.evaluate(() => innerHeight); + for (const b of bar) { + assert.ok(b.x >= 0 && b.x + b.w <= vw + 0.5, b.view + " is inside the window: " + JSON.stringify(b)); + assert.ok(b.y + b.h <= vh + 0.5 && b.y > vh - 100, b.view + " sits at the window's foot: " + JSON.stringify(b)); + assert.ok(b.h >= 44, b.view + " is a touch target"); + } + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "nothing scrolls sideways"); + const onBar = bar.slice(0, 4).map((b) => b.view); + // the bar's own pages open with a tap + for (const v of onBar) { + await page.locator(`#nav > button[data-view="${v}"]`).tap(); + await page.waitForSelector("#view-" + v, { state: "visible" }); + } + // the rest are in More's list, each with its icon, and open from it + const rest = all.filter((v) => !onBar.includes(v)); + assert.ok(rest.length >= 1); + for (const v of rest) { + await page.locator("#nav .nav-more").tap(); + const menu = page.locator(".nav-more-menu"); + await menu.waitFor({ state: "visible" }); + const items = await menu.locator(".pm-item").count(); + assert.equal(items, rest.length, "More lists every page the bar hasn't"); + assert.equal(await menu.locator(".pm-item .nav-ic").count(), rest.length, "each with its tab's icon"); + const mb = await menu.boundingBox(), more = await page.locator("#nav .nav-more").boundingBox(); + assert.ok(mb.y + mb.height <= more.y + 1, "the menu opens above the bar"); + assert.ok(mb.x >= 0 && mb.x + mb.width <= vw + 0.5, "inside the window"); + await menu.locator(".pm-item").nth(rest.indexOf(v)).tap(); + await page.waitForSelector("#view-" + v, { state: "visible" }); + assert.equal(await page.locator(".nav-more-menu").count(), 0, "the menu closes"); + const now = await tabs(page); + assert.ok(now.find((b) => b.view === "more").on, "More is marked while " + v + " is open"); + assert.ok(!now.slice(0, 4).some((b) => b.on), "no other tab is marked"); + } + // back on a tab of the bar, More lets go of its mark + await page.locator(`#nav > button[data-view="${onBar[0]}"]`).tap(); + await page.waitForSelector("#view-" + onBar[0], { state: "visible" }); + assert.equal((await tabs(page)).find((b) => b.view === "more").on, false); + assert.deepEqual(page.errors, []); + }); + } + } + + test(`${engine}: the bar covers no part of a page or its status line`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await open(browser, "en", false, "settings"); + const bar = await page.locator("#nav").boundingBox(); + // the page's foot scrolls clear of the bar + const last = await page.evaluate(async () => { + const v = document.querySelector(".view:not([hidden])"); + v.scrollTop = v.scrollHeight; + await new Promise((r) => setTimeout(r, 200)); + return Math.min(v.getBoundingClientRect().bottom, Math.max(...[...v.children].filter((e) => e.getBoundingClientRect().height > 0).map((e) => e.getBoundingClientRect().bottom))); + }); + assert.ok(last <= bar.y + 1, `the page's last line (${last}) ends above the bar (${bar.y})`); + // a status message sits above it + await page.evaluate(() => { const s = document.querySelector(".foot .status") || document.querySelector(".status"); s.textContent = "Saved"; }); + await page.waitForTimeout(100); + const st = await page.evaluate(() => { const s = document.querySelector(".foot .status") || document.querySelector(".status"); const r = s.getBoundingClientRect(); return { y: r.y, h: r.height, shown: getComputedStyle(s).display !== "none" }; }); + if (st.shown && st.h > 0) assert.ok(st.y + st.h <= bar.y + 1, "the status line is above the bar: " + JSON.stringify(st)); + assert.deepEqual(page.errors, []); + }); + + test(`${engine}: a desktop browser keeps the header's tabs, with no More`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const context = await browser.newContext({ viewport: { width: 1280, height: 800 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + await page.route("**/*", serve("en", false)); + await page.goto("http://magpie.test/?view=providers"); + await page.waitForSelector("#view-providers", { state: "visible" }); + await page.waitForTimeout(300); + assert.equal(await page.locator("#nav .nav-more").count(), 0); + assert.equal(await page.locator("#nav .tb-over").count(), 0); + const nav = await page.locator("#nav").boundingBox(); + assert.ok(nav.y < 200, "the tabs are at the top: " + JSON.stringify(nav)); + }); +} diff --git a/internal/gui/tests/phone-web.test.cjs b/internal/gui/tests/phone-web.test.cjs index e93c5368e..ef255bff2 100644 --- a/internal/gui/tests/phone-web.test.cjs +++ b/internal/gui/tests/phone-web.test.cjs @@ -1,7 +1,7 @@ // Run with Node's test runner and Playwright on the module path; see README.md. // magpie web on a phone (jiakun_zhao on X: 移动端的显示效果非常不友好,甚至滚动 -//会抽搐). The header is two rows, the magpie and the icons over the tabs at -// their size, sliding sideways, the one open in sight; a setting's control +//会抽搐). The header is the magpie and the icons, the tabs a bar at the +// window's foot (geraldpppppp on X), the one open marked in sight; a setting's control // too wide beside its name goes under it rather than cut the name; iOS isn't // let zoom into a field it focuses. And a flick's scroll, which goes on // after the finger is lifted with no touch event, is the reader's: the page @@ -89,15 +89,18 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); t.after(() => browser.close()); - // the header: two rows, the tabs at their size, the one open in sight + // the header: the magpie and the icons; the tabs a bar at the foot, as + // an iPhone app's, each its mark over its word (phone-tabs.test.cjs) let page = await open(browser, phone, true, "plugins"); const [top, nav, actions, brand] = [await box(page, ".top"), await box(page, "#nav"), await box(page, ".top .actions"), await box(page, ".top .brand")]; + const vh = await page.evaluate(() => innerHeight); assert.ok(nav.y >= actions.y + actions.height - 1 && nav.y >= brand.y + brand.height - 1, "the tabs are under the magpie and the icons"); - assert.ok(nav.width >= top.width - 30, `the tabs take the row: ${nav.width} of ${top.width}`); - const tab = await page.locator("#nav button").first().evaluate((b) => [parseFloat(getComputedStyle(b).fontSize), b.getBoundingClientRect().height]); - assert.ok(tab[0] >= 13 && tab[1] >= 30, `a tab is readable and tappable: ${tab}`); - const on = await box(page, "#nav button.on"); - assert.ok(on.x >= nav.x - 1 && on.x + on.width <= nav.x + nav.width + 1, "Plugins, open, is in sight"); + assert.ok(Math.abs(nav.y + nav.height - vh) <= 1, `the tabs are at the window's foot: ${nav.y + nav.height} of ${vh}`); + assert.ok(nav.width >= top.width - 1, `the tabs take the window's width: ${nav.width} of ${top.width}`); + const tab = await page.locator("#nav button").first().evaluate((b) => [parseFloat(getComputedStyle(b).fontSize), b.getBoundingClientRect().height, getComputedStyle(b.querySelector(".nav-ic")).display]); + assert.ok(tab[0] >= 10 && tab[1] >= 44 && tab[2] !== "none", `a tab is readable and tappable, with its mark: ${tab}`); + const on = await box(page, "#nav > button.on:not(.tb-over)"); // a page under More hides its own tab + assert.ok(on && on.x >= nav.x - 1 && on.x + on.width <= nav.x + nav.width + 1, "Plugins, open, is marked in sight (More while it is past the fifth)"); assert.equal(await page.evaluate(() => document.documentElement.scrollWidth), 390, "nothing runs off the side"); assert.equal(await page.locator(".top").getAttribute("class"), "top", "none of the narrow window's squeezing"); assert.match(await page.locator('meta[name="viewport"]').getAttribute("content"), /maximum-scale=1/, "iOS doesn't zoom into a field"); diff --git a/internal/gui/tests/reader.cjs b/internal/gui/tests/reader.cjs index bcebd3713..328c60766 100644 --- a/internal/gui/tests/reader.cjs +++ b/internal/gui/tests/reader.cjs @@ -320,4 +320,18 @@ async function closeRequest(page) { await page.locator("#ledReqPane").waitFor({ state: "hidden" }); } -module.exports = { openRequest, closeRequest, provPrefsProviders, openProvPrefs, inEditor, settled, inView, reach, wheelTo, click, openPart, watchSettingsReads, settingsDrawn, agentRow, openAgentSettings, pickItem }; +// openPage opens a page from the navigation as the reader does: its tab, or, +// on a phone's tab bar where it is past the fifth, More and then its row in +// More's menu (phonetabs.js). +async function openPage(page, view) { + const tab = page.locator(`#nav [data-view="${view}"]`); + if (await tab.isVisible()) await tab.click(); + else { + await page.locator("#nav .nav-more").click(); + const name = (await tab.textContent()).trim(); + await page.locator(".nav-more-menu .pm-item", { hasText: name }).first().click(); + } + await page.locator(`#view-${view}`).waitFor(); +} + +module.exports = { openPage, openRequest, closeRequest, provPrefsProviders, openProvPrefs, inEditor, settled, inView, reach, wheelTo, click, openPart, watchSettingsReads, settingsDrawn, agentRow, openAgentSettings, pickItem }; diff --git a/internal/gui/tests/routing-held-dot.test.cjs b/internal/gui/tests/routing-held-dot.test.cjs index dd5666531..4ef3fecba 100644 --- a/internal/gui/tests/routing-held-dot.test.cjs +++ b/internal/gui/tests/routing-held-dot.test.cjs @@ -8,6 +8,7 @@ const fs = require("node:fs/promises"); const path = require("node:path"); const { test } = require("node:test"); const { chromium, webkit } = require("playwright"); +const { openPage } = require("./reader.cjs"); const assets = path.resolve(__dirname, "../assets"); const iso = (ms) => new Date(ms).toISOString(); @@ -75,7 +76,7 @@ for (const engine of engines) for (const lang of langs) for (const width of widt // another view first, the request already under way await page.goto("http://magpie.test/?view=agents"); await page.waitForTimeout(800); - await page.locator('#nav button[data-view="routing"]').click(); + await openPage(page, "routing"); await page.waitForFunction(() => document.querySelector(".rt-sky .pkt.held"), null, { timeout: 6000 }); await page.waitForTimeout(400); const atSeat = async (when) => {