Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
web: magpie web added to a phone's home screen opens as an app (ninja_s6114 on Discord)
yetone9022169f6ace
diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.mdindex ffd741cb2..ac75dec47 100644--- a/docs/subsystems/gui-shell.md+++ b/docs/subsystems/gui-shell.md@@ -14,7 +14,7 @@ three.| Native host | `Run` starts the Wails v3 app: the tray icon, the panel, the main window, single-instance handover, `magpie://` import links and open at login. `host` implements `Windows` for the API: show and hide, open URLs and folders, copy to the clipboard, fit and tint the panel, and set the text size. A copy on Linux sets PRIMARY before CLIPBOARD, since GTK 3 serves CLIPBOARD empty when PRIMARY is set after it on a compositor with no primary selection (KDE Plasma with middle-click paste off, #1881); on Wayland the copy is read back through the compositor, and one that doesn't read back whole answers `/api/copy` with 501, so the page tries its clipboard API, then the copy command, then says the copy failed with the text to copy by hand (`copy-fallback.test.cjs`). | [`app.go`](../../internal/gui/app.go), [`clipboard_gtk3.go`](../../internal/gui/clipboard_gtk3.go), [`clipboard_gtk3.h`](../../internal/gui/clipboard_gtk3.h), [`mainwindow.go`](../../internal/gui/mainwindow.go), [`traymenu.go`](../../internal/gui/traymenu.go) || Backend | `startBackend` starts the gateway this process serves, unless another magpie already serves it. In that case this process only shows the other one's status (`gw` is nil). `stopServing` drains requests in flight. A restart to update can hand the listening socket to the new version instead (see [A restart to update hands the gateway over](#a-restart-to-update-hands-the-gateway-over)). | [`backend.go`](../../internal/gui/backend.go) || API and assets | `Handler` serves `assets/` (embedded with `//go:embed assets`) and the `/api/*` routes, such as `/api/state`, `/api/set`, `/api/agents/{action}/{id}` and `/api/agents/restart/{id}` (a desktop app's Restart, after the row's confirm). `held` lets one API request's reads share one catalog build (`provider.Hold`), and drops it after any write. `revalidated` and `versionedPage` name each script by its content hash, so a cache never serves an old `app.js` under a new page; a file asked for under its current hash (`?v=`) is cached for good (`immutable`), anything else is revalidated by its ETag. | [`api.go`](../../internal/gui/api.go) |-| Browser mode | `StartWeb` serves the page and the gateway for `magpie web`. The browser signs in with a run key in a link. Gateway mode shows Providers, Gateway, Routing, Usage, Sessions, Plugins and Settings on a machine that is only a gateway. `webHandler` gzips the page's text files and the API's JSON for a browser that takes gzip (`webCompressed`, with a `-gzip` ETag that still answers 304); the app's own windows read the page in-process and get it uncompressed. 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: `Server.Front` (lanGuard over Handler) in process when this process serves the gateway, or `toGateway`, a reverse proxy to `gateway.URL()`, when another magpie does; it keeps the Host and the forwarding headers and adds X-Forwarded-For for a peer that isn't loopback, so the other gateway judges the request as it came. See `TestWebOnePortServedHere`, `TestWebOnePortServedElsewhere` and `TestClientPathCoversHandler`. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go), [`oneport.go`](../../internal/gateway/oneport.go) |+| 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`. Gateway mode shows Providers, Gateway, Routing, Usage, Sessions, Plugins and Settings on a machine that is only a gateway. `webHandler` gzips the page's text files and the API's JSON for a browser that takes gzip (`webCompressed`, with a `-gzip` ETag that still answers 304); the app's own windows read the page in-process and get it uncompressed. 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: `Server.Front` (lanGuard over Handler) in process when this process serves the gateway, or `toGateway`, a reverse proxy to `gateway.URL()`, when another magpie does; it keeps the Host and the forwarding headers and adds X-Forwarded-For for a peer that isn't loopback, so the other gateway judges the request as it came. See `TestWebOnePortServedHere`, `TestWebOnePortServedElsewhere` and `TestClientPathCoversHandler`. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go), [`oneport.go`](../../internal/gateway/oneport.go) || The page | `app.js` keeps one state object per view and renders it into a list, with no framework. The views have their own files: `plugins.js` and `context.js`, and those a plugin adds under `assets/plugins/<id>/` (the Gateway, Sessions, Library, Routing and Usage pages, see [plugin runtime](plugin-runtime.md)) (Usage's Context tab, and the context window card the Routing page draws under a request's story, fed by `/api/context` in `context.go`, which scores and tags each agent; clicking a part, a cell or an item opens its text from `/api/context/text`, the last 10 requests' masked bodies in memory (`openCtxText`), rendered 100 items and 20000 characters at a time; its "Tuned for you" cards are fed by `/api/tune` in `tune.go`, see [agent wiring](agent-wiring.md)). Strings go through `t()` with translations in `i18n.js`, and a plugin's own in its `i18n.js` (zh, zh-TW, ja and de; the English text is the key and the fallback). zh-TW is Traditional Chinese with Taiwan's words; a system language of zh-TW, zh-HK, zh-MO or any zh-Hant picks it, and the tray menu and notifications follow (`trayLang`). Dropdowns use `openProtoMenu`. Every app menu (`openProtoMenu`, `openRowMenu`, `openSessCombo`) is placed by `placeMenu`: under its anchor, or over it when the window runs out below; one that fits neither way takes the larger room, its height held to it, and scrolls inside itself, and a scroll inside a menu doesn't close it (#1437, `removed-groups-menu-scroll.test.cjs`). The highest any popover goes is `popTop`: 8px under `header.top` on a Mac window, where the traffic lights are drawn over the page, and 8px from the top elsewhere; `placeMenu`, the field picker's `placePop` (which also holds `#pop`'s height to that room) and an agent's model list (`openAgentModels`) all use it (#1573, `popover-mac-chrome.test.cjs`). Scrolling is done only by `scrollOnPurpose(e)` with the reader's event. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/i18n.js`](../../internal/gui/assets/i18n.js) || Window navigation | In the window from 1024 points wide (`SIDE_AT`, the same width as app.css's `side-nav` rules), `layoutNav` moves the brand, the pages (`#nav`) and Settings into the sidebar (`#side`): the pages in four groups (Work, Models, Insights, Extend; a group none of whose pages shows, as in gateway mode, leaves out its name), the gateway's address at its foot (`sideGwRead`, read from `/api/providers` only while there is a sidebar, 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) || 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`), *Try it* (`renderMaskTry`, the text as the vendor would get it from `/api/masking/preview`, kept in no storage) and *Sharing*. See [gateway routing](gateway-routing.md) for what is recorded. | [`assets/app.js`](../../internal/gui/assets/app.js), [`masking.go`](../../internal/gui/masking.go) |diff --git a/internal/gui/assets/icons/apple-touch-icon.png b/internal/gui/assets/icons/apple-touch-icon.pngnew file mode 100644index 000000000..96949dbcbBinary files /dev/null and b/internal/gui/assets/icons/apple-touch-icon.png differdiff --git a/internal/gui/assets/icons/icon-512.png b/internal/gui/assets/icons/icon-512.pngnew file mode 100644index 000000000..30b0c4362Binary files /dev/null and b/internal/gui/assets/icons/icon-512.png differdiff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.htmlindex 4da6b6476..63572f543 100644--- a/internal/gui/assets/index.html+++ b/internal/gui/assets/index.html@@ -5,6 +5,20 @@<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"><title>magpie</title><link rel="icon" href="icons/favicon.svg" type="image/svg+xml">+<!-- added to a phone's home screen, magpie web opens as an app of its own,+ with no browser bars (ninja_s6114 on Discord); webGuard serves these+ few files without the key, as a home screen may ask for them without+ the page's cookie.+ The theme colours are the window's in standalone alone, so a browser's+ tab and the app's own windows look as they did -->+<link rel="manifest" href="manifest.json">+<link rel="apple-touch-icon" href="icons/apple-touch-icon.png">+<meta name="apple-mobile-web-app-capable" content="yes">+<meta name="mobile-web-app-capable" content="yes">+<meta name="apple-mobile-web-app-title" content="magpie">+<meta name="apple-mobile-web-app-status-bar-style" content="default">+<meta name="theme-color" media="(display-mode: standalone) and (prefers-color-scheme: light)" content="#f4f4f6">+<meta name="theme-color" media="(display-mode: standalone) and (prefers-color-scheme: dark)" content="#1a1a1e"><script src="boot.js"></script><script src="theme.js"></script><script src="omarchy.js"></script>diff --git a/internal/gui/assets/manifest.json b/internal/gui/assets/manifest.jsonnew file mode 100644index 000000000..2509c7af8--- /dev/null+++ b/internal/gui/assets/manifest.json@@ -0,0 +1,13 @@+{+ "name": "magpie",+ "short_name": "magpie",+ "start_url": "./",+ "scope": "./",+ "display": "standalone",+ "background_color": "#f4f4f6",+ "theme_color": "#f4f4f6",+ "icons": [+ { "src": "icons/apple-touch-icon.png", "sizes": "180x180", "type": "image/png" },+ { "src": "icons/icon-512.png", "sizes": "512x512", "type": "image/png" }+ ]+}diff --git a/internal/gui/tests/web-app-standalone.test.cjs b/internal/gui/tests/web-app-standalone.test.cjsnew file mode 100644index 000000000..27842df49--- /dev/null+++ b/internal/gui/tests/web-app-standalone.test.cjs@@ -0,0 +1,139 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// magpie web added to an iPhone's home screen opened in Safari with its+// address bar (ninja_s6114 on Discord). The page now names a web app+// manifest and the iOS meta tags, so it opens as an app of its own. Opened+// so, with the status bar, the notch and the home indicator over the+// screen's edges, the header's magpie, icons and tabs are inside the safe+// area; the theme colour is the app window's alone, so a browser's tab+// and the desktop app's window take none of it.+const assert = require("node:assert/strict");+const fs = require("node:fs/promises");+const os = require("node:os");+const path = require("node:path");+const { test } = require("node:test");+const { chromium, webkit, devices } = require("playwright");++const assets = path.resolve(__dirname, "../assets");++function serve(web) {+ const providers = { providers: [], presets: [], excluded: [], gateway: { running: true, window: true } };+ const state = { agents: [], profiles: [], settings: { lang: "en", theme: "light" } };+ return async (route) => {+ const url = new URL(route.request().url());+ const json = (data) => route.fulfill({ json: data });+ if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"en",theme:"light",web:${web}};` });+ 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/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", ".json": "application/json" }[path.extname(file)];+ await route.fulfill({ body: await fs.readFile(file), contentType });+ };+}++async function open(browser, opts, web) {+ const context = await browser.newContext({ reducedMotion: "reduce", ...opts });+ return load(await context.newPage(), web);+}+async function load(page, web) {+ page.setDefaultTimeout(5000);+ page.errors = [];+ page.on("pageerror", (e) => page.errors.push(e.message));+ await page.route("**/*", serve(web));+ await page.goto("http://magpie.test/?view=providers");+ await page.waitForSelector("#view-providers", { state: "visible" });+ await page.waitForTimeout(300);+ return page;+}++// magpie web opened from the home screen: Chromium's app window (--app),+// opened on a data: page (about:blank isn't made an app), whose+// display-mode is standalone as a home-screen app's is (CDP's+// emulated media has no display-mode), with an iPhone's safe area+async function openStandalone(t, opts, insets) {+ const { isMobile, defaultBrowserType, ...rest } = opts;+ opts = rest;+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "magpie-webapp-"));+ const context = await chromium.launchPersistentContext(dir, { channel: "chromium", reducedMotion: "reduce", ...opts, args: ["--app=data:text/html,magpie"] });+ t.after(async () => { await context.close(); await fs.rm(dir, { recursive: true, force: true }); });+ const page = context.pages()[0] || await context.newPage();+ const cdp = await context.newCDPSession(page);+ await cdp.send("Emulation.setSafeAreaInsetsOverride", { insets });+ // a phone's touch screen (pointer: coarse); isMobile would take the+ // app window's display-mode away+ await cdp.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 5 });+ return load(page, true);+}+const box = (page, s) => page.locator(s).first().boundingBox();+const themeColours = (page) => page.evaluate(() => [...document.querySelectorAll('meta[name="theme-color"]')].filter((m) => matchMedia(m.media || "all").matches).map((m) => m.content));++for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ const phone = { ...devices["iPhone 13"] };+ if (engine === "chromium") delete phone.defaultBrowserType;+ const launch = () => (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));++ test(`${engine}: the page names what a home screen needs`, async (t) => {+ const browser = await launch();+ t.after(() => browser.close());+ const page = await open(browser, phone, true);+ const attr = (s, a) => page.locator(s).getAttribute(a);+ assert.equal(await attr('meta[name="apple-mobile-web-app-capable"]', "content"), "yes");+ assert.equal(await attr('meta[name="mobile-web-app-capable"]', "content"), "yes");+ assert.equal(await attr('meta[name="apple-mobile-web-app-status-bar-style"]', "content"), "default", "the status bar keeps its own ground, the page starting under it");+ const manifest = JSON.parse(await fs.readFile(path.join(assets, await attr('link[rel="manifest"]', "href")), "utf8"));+ assert.equal(manifest.display, "standalone");+ assert.equal(manifest.name, "magpie");+ // the files are there (TestWebAppAddsToHomeScreen checks how they are served)+ for (const ic of [...manifest.icons, { src: await attr('link[rel="apple-touch-icon"]', "href") }]) {+ await fs.access(path.join(assets, ic.src));+ }+ // a browser's tab takes no theme colour from magpie+ assert.deepEqual(await themeColours(page), []);+ // nor does the app's window+ const win = await open(browser, { viewport: { width: 1200, height: 800 } }, false);+ assert.deepEqual(await themeColours(win), []);+ assert.deepEqual([...page.errors, ...win.errors], []);+ });++ test(`${engine}: a phone's browser tab keeps its header where it was`, async (t) => {+ const browser = await launch();+ t.after(() => browser.close());+ const page = await open(browser, phone, true);+ const brand = await box(page, ".top .brand");+ assert.ok(brand.y < 20, `the magpie at the top as before: ${brand.y}`);+ assert.deepEqual(page.errors, []);+ });++ if (engine !== "chromium") continue; // WebKit can't be made a home-screen app++ test(`${engine}: opened from the home screen, the header is inside the safe area`, async (t) => {+ // an iPhone 13 upright: the status bar over the notch, the home indicator+ const page = await openStandalone(t, phone, { top: 47, bottom: 34, left: 0, right: 0 });+ assert.equal(await page.evaluate(() => matchMedia("(display-mode: standalone)").matches), true, "the page is a home-screen app");+ assert.equal(await page.evaluate(() => matchMedia("(pointer: coarse)").matches), true, "on a touch screen");+ assert.deepEqual(await themeColours(page), ["#f4f4f6"], "the light window's colour");+ for (const s of [".top .brand", ".top .actions", ".top #nav"]) {+ const b = await box(page, s);+ assert.ok(b.y >= 47, `${s} under the status bar: ${b.y}`);+ }+ const foot = await box(page, ".foot");+ if (foot && foot.height) assert.ok(foot.y + foot.height <= 844 + 1, "the foot on the screen");+ // turned on its side: the notch at one side, and both sides kept clear+ const side = await openStandalone(t, { ...phone, viewport: { width: 844, height: 390 } }, { top: 0, bottom: 21, left: 47, right: 47 });+ for (const s of [".top .brand", ".top .actions"]) {+ const b = await box(side, s);+ assert.ok(b.x >= 47 && b.x + b.width <= 844 - 47, `${s} clear of the notch: ${b.x}..${b.x + b.width}`);+ }+ assert.deepEqual([...page.errors, ...side.errors], []);+ });++ test(`${engine}: opened from the home screen in the dark`, async (t) => {+ const page = await openStandalone(t, { ...phone, colorScheme: "dark" }, { top: 47, bottom: 34, left: 0, right: 0 });+ assert.deepEqual(await themeColours(page), ["#1a1a1e"], "the dark window's colour");+ });+}diff --git a/internal/gui/web.go b/internal/gui/web.goindex 8283cda3e..0784d87c4 100644--- a/internal/gui/web.go+++ b/internal/gui/web.go@@ -227,6 +227,14 @@ func webGuard(cookie, key string, keep time.Duration, next http.Handler) http.HasignIn(rw, r, u.RequestURI())return}+ // what a phone's home screen reads to add the page as an app+ // (index.html's manifest and icons; ninja_s6114 on Discord):+ // fixed bytes of the build, which a browser may ask for without+ // the page's cookie. These paths alone, read alone.+ if webAppFiles[r.URL.Path] && (r.Method == http.MethodGet || r.Method == http.MethodHead) {+ next.ServeHTTP(rw, r)+ return+ }if r.URL.Path == webSignInPath && r.Method == http.MethodPost {r.Body = http.MaxBytesReader(rw, r.Body, 4096)back := localPath(r.PostFormValue("back"))@@ -260,6 +268,17 @@ func webGuard(cookie, key string, keep time.Duration, next http.Handler) http.Ha})}+// webAppFiles are the files webGuard serves without the key: the web app+// manifest and the icons it and index.html name, so "Add to Home Screen"+// gets them whether or not the browser sends its cookie with them. Each is+// a file of the build, the same for every magpie; nothing in it is the+// user's.+var webAppFiles = map[string]bool{+ "/manifest.json": true,+ "/icons/apple-touch-icon.png": true,+ "/icons/icon-512.png": true,+}+// webSignInPath takes the key pasted into the form a page turned away shows.const webSignInPath = "/_magpie/sign-in"diff --git a/internal/gui/web_app_test.go b/internal/gui/web_app_test.gonew file mode 100644index 000000000..8cf78f0c3--- /dev/null+++ b/internal/gui/web_app_test.go@@ -0,0 +1,139 @@+package gui++import (+ "bytes"+ "encoding/json"+ "fmt"+ "image"+ _ "image/png"+ "net/http"+ "net/http/httptest"+ "path/filepath"+ "regexp"+ "strings"+ "testing"+)++// magpie web added to an iPhone's home screen opened in Safari, with its+// address bar (ninja_s6114 on Discord): the page named no web app+// manifest and no apple-mobile-web-app-capable. Now it does, and the+// manifest and the icons it and the page name are served, with their+// types, to a browser that asks for them without the page's cookie, as a+// home screen or an install prompt may. Nothing else is.+func TestWebAppAddsToHomeScreen(t *testing.T) {+ h := t.TempDir()+ t.Setenv("HOME", h)+ t.Setenv("USERPROFILE", h)+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))+ t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))+ const key = "0123456789abcdef-key"+ srv := webHandler("3430", key, 0, Handler(webHost{}, nil))+ do := func(method, path string, signedIn bool) *httptest.ResponseRecorder {+ r := httptest.NewRequest(method, path, nil)+ if signedIn {+ r.AddCookie(&http.Cookie{Name: "magpie_web_3430", Value: key})+ }+ rec := httptest.NewRecorder()+ srv.ServeHTTP(rec, r)+ return rec+ }++ page := do("GET", "/", true)+ if page.Code != http.StatusOK {+ t.Fatalf("the page, signed in: %d", page.Code)+ }+ html := page.Body.String()+ for _, want := range []string{+ `<meta name="apple-mobile-web-app-capable" content="yes">`,+ `<meta name="mobile-web-app-capable" content="yes">`,+ `<meta name="apple-mobile-web-app-status-bar-style"`,+ } {+ if !strings.Contains(html, want) {+ t.Errorf("the page lacks %s", want)+ }+ }+ // a theme colour a browser's tab would take too would change how magpie+ // web looks in Safari and Chrome; only the app's window takes it+ for _, m := range regexp.MustCompile(`<meta name="theme-color"[^>]*>`).FindAllString(html, -1) {+ if !strings.Contains(m, `media="(display-mode: standalone)`) {+ t.Errorf("a theme colour outside standalone: %s", m)+ }+ }++ link := func(rel string) string {+ m := regexp.MustCompile(`<link rel="` + rel + `" href="([^"]+)"`).FindStringSubmatch(html)+ if m == nil {+ t.Fatalf("the page names no %s", rel)+ }+ return "/" + m[1]+ }+ // type and size of the png at path, fetched with no cookie+ icon := func(path, sizes string) {+ rec := do("GET", path, false)+ if rec.Code != http.StatusOK || rec.Header().Get("Content-Type") != "image/png" {+ t.Errorf("%s without the cookie: %d %q", path, rec.Code, rec.Header().Get("Content-Type"))+ return+ }+ c, _, err := image.DecodeConfig(bytes.NewReader(rec.Body.Bytes()))+ if err != nil {+ t.Errorf("%s: %v", path, err)+ return+ }+ if got := fmt.Sprintf("%dx%d", c.Width, c.Height); got != sizes {+ t.Errorf("%s is %s, named %s", path, got, sizes)+ }+ }+ icon(link("apple-touch-icon"), "180x180")++ mf := link("manifest")+ rec := do("GET", mf, false)+ if rec.Code != http.StatusOK || !strings.HasPrefix(rec.Header().Get("Content-Type"), "application/json") {+ t.Fatalf("%s without the cookie: %d %q", mf, rec.Code, rec.Header().Get("Content-Type"))+ }+ var m struct {+ StartURL string `json:"start_url"`+ Icons []struct{ Src, Sizes, Type string }+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &m); err != nil {+ t.Fatal(err)+ }+ var raw map[string]any+ json.Unmarshal(rec.Body.Bytes(), &raw)+ if raw["name"] != "magpie" || raw["display"] != "standalone" || m.StartURL == "" {+ t.Errorf("manifest: name %v, display %v, start_url %q", raw["name"], raw["display"], m.StartURL)+ }+ big := false+ for _, ic := range m.Icons {+ icon("/"+ic.Src, ic.Sizes)+ big = big || ic.Sizes == "512x512"+ }+ if !big {+ t.Error("the manifest has no 512px icon, which Chrome on Android wants to install the page")+ }+ if rec := do("HEAD", mf, false); rec.Code != http.StatusOK {+ t.Errorf("HEAD %s without the cookie: %d", mf, rec.Code)+ }++ // every other file and route still wants the key, and so do these+ // files asked for any other way+ for _, c := range []struct{ method, path string }{+ {"GET", "/"},+ {"GET", "/index.html"},+ {"GET", "/app.js"},+ {"GET", "/boot.js"},+ {"GET", "/icons/favicon.svg"},+ {"GET", "/icons/magpie.svg"},+ {"GET", "/api/state"},+ {"GET", "/api/providers"},+ {"GET", "/manifest.json/"},+ {"GET", "/Manifest.json"},+ {"GET", "/icons/../app.js"},+ {"GET", "/icons/apple-touch-icon.png/../../app.js"},+ {"POST", "/manifest.json"},+ {"PUT", "/icons/icon-512.png"},+ } {+ if rec := do(c.method, c.path, false); rec.Code != http.StatusUnauthorized {+ t.Errorf("%s %s without the cookie: %d, want 401", c.method, c.path, rec.Code)+ }+ }+}