From ceeb73a0f1c2e290f121d3523aad7f0e1967ed38 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 31 Oct 2026 14:05:11 +0800 Subject: [PATCH] =?UTF-8?q?app:=20the=20desktop=20app=20writes=20its=20log?= =?UTF-8?q?=20to=20app.log;=20magpie=20log=20and=20Settings=20=E2=80=BA=20?= =?UTF-8?q?About=20=E2=80=BA=20Log=20find=20it?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit rayem1w on X (0.1.2330, macOS) was asked for ~/Library/Logs/magpie/serve.log while chasing a Codex "hit a snag" through the gateway, and had no such folder. Only the launch agent (magpie daemon install, written by launchd) and a gateway magpie tui left running wrote a log; the app opened from the Finder, the Dock or the Start menu logged to a stderr nobody reads, on every system. Now runGUI and runPanel (magpie, app, tray, panel, a window view, a magpie: link) call applog.Start before gui.Run. It sends the standard logger (the gateway, the plugin host, providers and Wails' error handler all log through it) to app.log as well as stderr, and points debug.SetCrashOutput at it so a panic's trace is there too: macOS ~/Library/Logs/magpie/app.log Windows %LOCALAPPDATA%\magpie\logs\app.log Linux $XDG_STATE_HOME/magpie/app.log, else ~/.local/state/magpie/app.log portable data/logs/app.log app.log, not serve.log: on a Mac launchd writes serve.log for the service, another process. The file is 0600. At 5 MiB it becomes app.old.log (two files at most); when another magpie (an update's new process) rotated it already, it is only opened again; when it can't be moved it is emptied. stderr goes first, through a writer that never fails, since io.MultiWriter stops at a failed writer and an app opened from Explorer has no stderr. Secrets: the log calls name header names and paths without queries; no key or token was found logged (grep of log.Print* in gateway, provider, plugin, gui, agent). scrub masks bearer/basic credentials, key/token query parameters and sk-, AIza, gh?_ and JWT shapes anyway. How a user finds it: Settings › About › Log, with the path, Copy and an Open that shows its folder (POST /api/settings/log/reveal; the row is hidden in magpie web, which writes no file). magpie log prints where every log is (the app's, app.old.log, the service's, the tui's background serve.log); --path the app's alone, -n N its last lines, -f follows it across a rotation. Docs: reference.md, gui-shell.md, site start (FAQ "Where is magpie's log?" and the CLI table) and privacy (files on your computer), en/zh/ja. Run: At 227ce6074 on origin/main fbb1b36d1: - mote: go test ./internal/applog ./internal/appdir ./internal/cli ok; -run TestCoreScriptBudget ./internal/gui ok; GOOS=windows go vet ./internal/... and GOOS=linux go vet -tags nogui ./internal/... ok; gofmt -l clean. GUI, chromium: about-log (5 languages x 1100/420, and no row without a log), about-website, i18n-keys: 24 of 25, the one red "a plugin's words are its own" ("Unmarked") is the same at origin/main fbb1b36d1 (#4524). - WSL (magpie-desktop), webkit: about-log and about-website 21 of 21. - Windows (win-run): applog, appdir, tui ok; cli ok but TestLibraryMCPHub's TempDir cleanup (#4140, mcp-npm, not this change). - WSL full go test -tags nogui -timeout 45m ./... at the previous base 03f609e3f: every package ok but reds that fail the same at origin/main 03f609e3f alone: TestSettingsSaveKeepsWhatItDoesNotSend (#4514), TestNoCommandBypassesProc (#4491), internal/agent's install-detection tests (#4033, #3548), and TestCoreScriptBudget, which was this change (app.js 321 over): its comment is cut to one line and both budgets are raised by the remaining 124 bytes, with no room added. - Broken by hand: with startLog left out of runGUI, TestTheAppWritesItsLog is red ("app wrote no log: open .../Library/Logs/magpie/app.log: no such file or directory"); with proc.UserPath taken out of openApp, TestGatewayStartsGetUserPath is red ("runGUI doesn't call proc.UserPath"). The guard now follows a start into a function or func var of this package, since the Wails start sits behind openApp for the test. - Real use on mote: the GUI build, magpie app in a sandbox HOME, wrote ~/Library/Logs/magpie/app.log (0600) with its "started" line; magpie log and magpie log -n 3 printed it. Not tried: the app opened from Windows Explorer or a Linux desktop launcher for real (the paths are unit-tested per OS, the writer on Windows and Linux); the full GUI suite (running on WSL after the push, reds filed if they fail at origin/main too). --- docs/reference.md | 21 ++- docs/subsystems/gui-shell.md | 3 +- internal/appdir/appdir.go | 31 ++++ internal/appdir/logs_test.go | 54 ++++++ internal/applog/applog.go | 234 ++++++++++++++++++++++++++ internal/applog/applog_test.go | 181 ++++++++++++++++++++ internal/cli/gui_log_test.go | 48 ++++++ internal/cli/gui_on.go | 31 +++- internal/cli/help_cli.go | 2 + internal/cli/log_cli.go | 187 ++++++++++++++++++++ internal/cli/log_cli_test.go | 142 ++++++++++++++++ internal/cli/main.go | 6 + internal/cli/userpath_test.go | 60 +++++-- internal/gui/api.go | 19 +++ internal/gui/assets/app.js | 6 + internal/gui/assets/i18n.js | 8 + internal/gui/core_budget_test.go | 4 +- internal/gui/tests/about-log.test.cjs | 66 ++++++++ internal/tui/keep.go | 6 +- site/public/docs/ja/privacy.html | 1 + site/public/docs/ja/start.html | 4 + site/public/docs/privacy.html | 1 + site/public/docs/start.html | 4 + site/public/docs/zh/privacy.html | 1 + site/public/docs/zh/start.html | 4 + 25 files changed, 1101 insertions(+), 23 deletions(-) create mode 100644 internal/appdir/logs_test.go create mode 100644 internal/applog/applog.go create mode 100644 internal/applog/applog_test.go create mode 100644 internal/cli/gui_log_test.go create mode 100644 internal/cli/log_cli.go create mode 100644 internal/cli/log_cli_test.go create mode 100644 internal/gui/tests/about-log.test.cjs diff --git a/docs/reference.md b/docs/reference.md index 4b17c0755..8ed7dfe10 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -2251,6 +2251,24 @@ a `data` folder beside it) records no path, and a copy moved since its last start leaves the old one: run the program where it is, such as `& "$HOME\Downloads\magpie-windows-amd64.exe" goroutines | Out-Host`. +`magpie log [--path] [-n N] [-f]` says where magpie's logs are. The app +(its window, the menu bar or tray icon and the panel, opened from the +Finder, the Dock, the Start menu or a terminal) writes what it logs to +`app.log` as well as to stderr: `~/Library/Logs/magpie/app.log` on macOS, +`%LOCALAPPDATA%\magpie\logs\app.log` on Windows, +`$XDG_STATE_HOME/magpie/app.log` (`~/.local/state/magpie/app.log`) on Linux +and the BSDs, and `logs/app.log` in a portable magpie's data folder. A +panic's trace goes there too. At 5 MiB it becomes `app.old.log`, over the +one before, so two files are kept at most. The file is readable by your +user only, and what looks like a key or token is masked in it, though +nothing magpie logs is meant to carry one. Settings › About › Log has its +path and an Open that shows its folder. `magpie log` prints its path, the +older file when there is one, the service's log when `magpie daemon` is +installed and the log of a gateway `magpie tui` left running; `--path` +prints the app's alone, `-n N` its last N lines and `-f` follows it, +across a rotation, until Ctrl+C. `magpie serve`, `magpie web` and the TUI +write no `app.log`: their log is the terminal's, or the service's. + A gateway key held to a budget, to some models or to some accounts is told none of this magpie's accounts (#1981): `/v1/magpie/quotas`, `/v1/magpie/quotas/history`, `/v1/magpie/quotas/cards`, @@ -2675,7 +2693,8 @@ port is free. told so; run `magpie serve` under the manager it has. - **macOS:** a launch agent, `~/Library/LaunchAgents/com.yetone.magpie.serve.plist`, loaded with `launchctl bootstrap gui/$UID`. Its log: - `~/Library/Logs/magpie/serve.log`. + `~/Library/Logs/magpie/serve.log`, beside the app's own `app.log` + (`magpie log`). - **Windows:** not a service; `magpie autostart on` opens magpie, which serves the gateway, when you log in. Inside WSL, `magpie daemon` works as on Linux. diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 74c579f8f..017dd6504 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -20,12 +20,13 @@ three. | 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*. *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. One in use stays on: its switch is disabled and the row says what uses it, and the POST refuses it off. A plugins.yml that doesn't parse is said above the list and no switch moves. `boot.js` says which are off (`featuresOff`) and their settings (`pluginConfig`) before the first paint, and `settings.builtins` carries the list on every state read. The TUI doesn't follow them. See `builtins.test.cjs`, `builtins_test.go`. | [`builtins.go`](../../internal/gui/builtins.go), [`assets/plugins.js`](../../internal/gui/assets/plugins.js), [`assets/app.js`](../../internal/gui/assets/app.js) | +| The app's log | `runGUI` and `runPanel` (so `magpie`, `app`, `tray`, `panel`, a window view and a `magpie:` link) call `startLog` before `gui.Run`: `applog.Start` sends the standard logger, which the gateway, the plugin host and Wails' error handler write to, to `app.log` in `appdir.Logs` as well as stderr (`quiet`, which never fails, first, since io.MultiWriter stops at a failed writer and an app opened from Explorer has no stderr), and points `debug.SetCrashOutput` at it, so a panic is in it. Opened from the Finder, the Dock or the Start menu the app has no terminal, and wrote its log nowhere (rayem1w on X, 0.1.2330). The folder is `~/Library/Logs/magpie` on macOS (beside the launch agent's `serve.log`, which launchd writes for `magpie serve`: the two processes never share a file), `%LOCALAPPDATA%\magpie\logs` on Windows, `$XDG_STATE_HOME/magpie` (`~/.local/state/magpie`) elsewhere, and `logs` in a portable data folder. The file is 0600. At 5 MiB (`Limit`) it becomes `app.old.log`; when another magpie (an update's new process) rotated it already (`os.SameFile` of the open file and the path differs), it is only opened again, and when it can't be moved it is emptied. Each line goes through `scrub`, which masks bearer and basic credentials, key and token query parameters, and `sk-`, `AIza`, `gh?_` and JWT shapes, though nothing logged is meant to carry one. Settings › About's Log row (`#logRow`, `settingsJSON.Log` from `applog.Current`, so `magpie web`, which writes no file, shows none) has its path and an Open (`POST /api/settings/log/reveal`) that shows its folder; `magpie log` prints where every log is, `-n` the last lines, `-f` follows across a rotation (`TestTheAppWritesItsLog`, `TestLogFollows`). | [`internal/applog/applog.go`](../../internal/applog/applog.go), [`gui_on.go`](../../internal/cli/gui_on.go), [`log_cli.go`](../../internal/cli/log_cli.go) | | No GUI build | `-tags nogui` builds magpie without the GUI: `hasGUI` is false and `runGUI` says to use `magpie tui`. The files of `internal/gui` that need Wails build under `!nogui`. | [`gui_off.go`](../../internal/cli/gui_off.go) | | The terminal quitting | `magpie tui` that served the gateway with an agent connected hands the gateway on as it quits, on Linux where nothing opens magpie at login (a WSL distro, a server over SSH; zaidu259434 on X): `keepGateway` starts magpie's service when it is installed, installs it (`daemon.Install`) when the user never removed it (`daemon.Removed`, a mark `magpie daemon uninstall` leaves), and otherwise starts `magpie serve` in its own session (`serveInBackground`, log in magpie's cache). Elsewhere, with nothing connected, or where magpie opens at login, it only says the gateway stopped. | [`keep.go`](../../internal/tui/keep.go) | ## Runtime path -1. `magpie` with no arguments, `magpie app` or `magpie tray` calls `runGUI`, which calls `gui.Run`. A `nogui` build runs the TUI instead. A second launch hands over to the instance already running. On Windows, before any window is made, `webView2Check` asks Wails whether the WebView2 runtime is there (`Env.Info().PlatformInfo["WebView2"]`, "" when its lookup fails; a key Wails doesn't set counts as there). Without it Wails would exit on the first window with nothing on screen, so magpie logs it, shows a Windows message box in the reader's language naming the runtime, Microsoft's download page (`webView2Page`) and `magpie web` / `magpie tui`, opens the page on Yes, and `Run` ends (#1806, `webview2.go`, `TestWebView2MissingFromWails` on Windows). The box can't come from `ErrorHandler`, which runs on the thread Wails makes its windows on. +1. `magpie` with no arguments, `magpie app` or `magpie tray` calls `runGUI`, which starts the app's log (`startLog`, above) and calls `gui.Run`. A `nogui` build runs the TUI instead. A second launch hands over to the instance already running. On Windows, before any window is made, `webView2Check` asks Wails whether the WebView2 runtime is there (`Env.Info().PlatformInfo["WebView2"]`, "" when its lookup fails; a key Wails doesn't set counts as there). Without it Wails would exit on the first window with nothing on screen, so magpie logs it, shows a Windows message box in the reader's language naming the runtime, Microsoft's download page (`webView2Page`) and `magpie web` / `magpie tui`, opens the page on Yes, and `Run` ends (#1806, `webview2.go`, `TestWebView2MissingFromWails` on Windows). The box can't come from `ErrorHandler`, which runs on the thread Wails makes its windows on. 2. `startBackend` brings up the gateway, or finds another magpie serving it. 3. The panel and the window load `index.html` from `Handler`. `boot.js` passes the saved language, theme, colorblind mode, text size and desktop font choices before the first paint. 4. The page reads `GET /api/state` and writes through `POST` routes. Each write answers with the new state, built under `held`. diff --git a/internal/appdir/appdir.go b/internal/appdir/appdir.go index 76588e95c..452548b15 100644 --- a/internal/appdir/appdir.go +++ b/internal/appdir/appdir.go @@ -265,6 +265,37 @@ func Cache() string { return filepath.Join(mustHome(), ".cache", "magpie") } +// Logs is the folder the desktop app writes its log in, where each system +// keeps an app's logs: ~/Library/Logs/magpie on a Mac (beside the launch +// agent's serve.log, `magpie daemon install`), %LOCALAPPDATA%\magpie\logs +// on Windows, and $XDG_STATE_HOME/magpie (~/.local/state/magpie) elsewhere; +// portable, data/logs. A user asked for magpie's log finds it there +// (rayem1w on X: the app opened from the Finder had written none). +func Logs() string { + return logsOn(runtime.GOOS) +} + +// logsOn is Logs as it is on goos, for tests of every system's folder. +func logsOn(goos string) string { + if p := Portable(); p != "" { + return filepath.Join(p, "logs") + } + switch goos { + case "darwin": + return filepath.Join(mustHome(), "Library", "Logs", "magpie") + case "windows": + local := os.Getenv("LOCALAPPDATA") + if !rooted(local) { + local = filepath.Join(mustHome(), "AppData", "Local") + } + return filepath.Join(local, "magpie", "logs") + } + if x := os.Getenv("XDG_STATE_HOME"); rooted(x) { + return filepath.Join(x, "magpie") + } + return filepath.Join(mustHome(), ".local", "state", "magpie") +} + // WebView is the folder the Windows webview (WebView2) keeps its profile // in — its cache, cookies and the pages' storage — or "" for its own // default. Installed, that default is %APPDATA%\, as it always diff --git a/internal/appdir/logs_test.go b/internal/appdir/logs_test.go new file mode 100644 index 000000000..3253174e5 --- /dev/null +++ b/internal/appdir/logs_test.go @@ -0,0 +1,54 @@ +package appdir + +import ( + "path/filepath" + "testing" +) + +// Logs is where each system keeps an app's logs, and the data folder's +// logs portable: the app opened from the Finder wrote none (rayem1w on X). +func TestLogsOnEachSystem(t *testing.T) { + t.Setenv("APPIMAGE", "") + t.Cleanup(func() { UseExecutable("") }) + UseExecutable("") + r := root(t) + home, err := Home() + if err != nil { + t.Fatal(err) + } + + t.Setenv("LOCALAPPDATA", filepath.Join(r, "local")) + t.Setenv("XDG_STATE_HOME", filepath.Join(r, "state")) + for goos, want := range map[string]string{ + "darwin": filepath.Join(home, "Library", "Logs", "magpie"), + "windows": filepath.Join(r, "local", "magpie", "logs"), + "linux": filepath.Join(r, "state", "magpie"), + "freebsd": filepath.Join(r, "state", "magpie"), + } { + if got := logsOn(goos); got != want { + t.Errorf("%s: logs in %q, want %q", goos, got, want) + } + } + + // unset or relative, the system's default under the home + for _, v := range []string{"", "relative"} { + t.Setenv("LOCALAPPDATA", v) + t.Setenv("XDG_STATE_HOME", v) + if got, want := logsOn("windows"), filepath.Join(home, "AppData", "Local", "magpie", "logs"); got != want { + t.Errorf("windows, LOCALAPPDATA %q: logs in %q, want %q", v, got, want) + } + if got, want := logsOn("linux"), filepath.Join(home, ".local", "state", "magpie"); got != want { + t.Errorf("linux, XDG_STATE_HOME %q: logs in %q, want %q", v, got, want) + } + } + + exe := touch(t, filepath.Join(r, "port", "magpie")) + data := filepath.Join(r, "port", "data") + mkdir(t, data) + UseExecutable(exe) + for _, goos := range []string{"darwin", "windows", "linux"} { + if got, want := logsOn(goos), filepath.Join(data, "logs"); got != want { + t.Errorf("portable on %s: logs in %q, want %q", goos, got, want) + } + } +} diff --git a/internal/applog/applog.go b/internal/applog/applog.go new file mode 100644 index 000000000..ff0ad535f --- /dev/null +++ b/internal/applog/applog.go @@ -0,0 +1,234 @@ +// Package applog writes the desktop app's log to a file, as well as to +// stderr. The app opened from the Finder, the Dock, the Start menu or a +// desktop launcher has no terminal: what it logged went nowhere, so a user +// asked for magpie's log had none to send (rayem1w on X, a Codex "hit a +// snag" through the gateway, 0.1.2330). Only the launch agent +// (`magpie daemon install`, serve.log) and a `magpie tui` that left the +// gateway running (serve.log in magpie's cache) kept one. +// +// The file is app.log in appdir.Logs. It is the app's alone: the launch +// agent's serve.log, in the same folder on a Mac, is written by launchd for +// `magpie serve`, a process of its own. At 5 MiB app.log becomes +// app.old.log, over the one before, so two files at most are kept. A +// panic or fatal error's trace goes to the file too (debug.SetCrashOutput), +// so a crash is in it. +// +// What is logged names no key or token (the gateway logs header names, +// never values, and paths without their query); scrub masks what looks +// like one anyway, in case a vendor's error carries it. +package applog + +import ( + "errors" + "fmt" + "io" + "log" + "os" + "path/filepath" + "regexp" + "runtime" + "runtime/debug" + "sync" + "sync/atomic" + + "github.com/yetone/magpie/internal/appdir" +) + +const ( + // Name is the log's file name in appdir.Logs. + Name = "app.log" + // OldName is the log before the last rotation, kept beside it. + OldName = "app.old.log" + // Limit is the size at which the log is rotated. + Limit = 5 << 20 +) + +// Path is where the desktop app writes its log. +func Path() string { return filepath.Join(appdir.Logs(), Name) } + +// current is the log this process writes, "" when it writes none, and +// active its file. +var ( + current atomic.Pointer[string] + active atomic.Pointer[file] +) + +// Current is the log this process writes, or "" when it writes none (the +// TUI, `magpie serve`, a command). +func Current() string { + if p := current.Load(); p != nil { + return *p + } + return "" +} + +// Start sends the standard logger's output, and a crash's trace, to the +// log as well as to stderr, and logs that this magpie started. It answers +// the log's path; when the file can't be opened, the error, and the log +// goes to stderr alone as before. +func Start(version, how string) (string, error) { + path := Path() + w, err := open(path, Limit) + if err != nil { + return "", err + } + log.SetOutput(io.MultiWriter(quiet{os.Stderr}, w)) + if was := active.Swap(w); was != nil { + was.Close() + } + current.Store(&path) + log.Printf("magpie %s started (%s, pid %d, %s/%s); this log: %s", version, how, os.Getpid(), runtime.GOOS, runtime.GOARCH, path) + return path, nil +} + +// Stop sends the log to stderr alone again and closes the file: for +// tests, whose home is removed after them (Windows removes no folder with +// a file open in it). +func Stop() { + log.SetOutput(os.Stderr) + _ = debug.SetCrashOutput(nil, debug.CrashOptions{}) + current.Store(nil) + if w := active.Swap(nil); w != nil { + w.Close() + } +} + +// file is a log file rotated at limit bytes. +type file struct { + mu sync.Mutex + path string + old string + limit int64 + f *os.File + size int64 +} + +// open opens the log at path to append to, making its folder, readable by +// the user alone. +func open(path string, limit int64) (*file, error) { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return nil, err + } + w := &file{path: path, old: filepath.Join(filepath.Dir(path), OldName), limit: limit} + if err := w.reopen(false); err != nil { + return nil, err + } + return w, nil +} + +// reopen opens the file at w.path, emptied when truncate is set, and +// hands it to the runtime for a crash's trace. +func (w *file) reopen(truncate bool) error { + flag := os.O_CREATE | os.O_WRONLY | os.O_APPEND + if truncate { + flag |= os.O_TRUNC + } + f, err := os.OpenFile(w.path, flag, 0o600) + if err != nil { + return err + } + w.f, w.size = f, 0 + if fi, err := f.Stat(); err == nil { + w.size = fi.Size() + } + _ = debug.SetCrashOutput(f, debug.CrashOptions{}) + return nil +} + +// Write writes p to the log, rotating it first when p would take it past +// its limit. It answers len(p) for what it wrote, after masking, so an +// io.MultiWriter goes on to stderr. +func (w *file) Write(p []byte) (int, error) { + n := len(p) + p = scrub(p) + w.mu.Lock() + defer w.mu.Unlock() + if w.f == nil { + return 0, errors.New("applog: the log is closed") + } + if w.size > 0 && w.size+int64(len(p)) > w.limit { + w.rotate() + } + m, err := w.f.Write(p) + w.size += int64(m) + if err != nil { + return 0, err + } + return n, nil +} + +// rotate makes the log app.old.log and starts a new one. When another +// magpie rotated it already (an update's new process beside the old one), +// the log at w.path is already new and is only opened. When it can't be +// moved (Windows, while another process has it open), it is emptied, so +// it stays bounded either way. +func (w *file) rotate() { + if at, err := os.Stat(w.path); err == nil { + if mine, err := w.f.Stat(); err == nil && !os.SameFile(at, mine) { + w.f.Close() + if w.reopen(false) == nil { + return + } + } + } + // the runtime holds a copy of the file for a crash's trace, and + // Windows moves no file with a handle open + _ = debug.SetCrashOutput(nil, debug.CrashOptions{}) + w.f.Close() + moved := os.Rename(w.path, w.old) + if err := w.reopen(moved != nil); err != nil { + w.f = nil + return + } + if moved != nil { + n, _ := fmt.Fprintf(w.f, "applog: %s couldn't be kept as %s (%v): emptied instead\n", Name, OldName, moved) + w.size += int64(n) + } +} + +// Close closes the log; for tests. +func (w *file) Close() error { + w.mu.Lock() + defer w.mu.Unlock() + if w.f == nil { + return nil + } + err := w.f.Close() + w.f = nil + return err +} + +// quiet is stderr that never fails a write: the app opened from Windows +// Explorer has no stderr at all, and io.MultiWriter stops at the first +// writer that fails. +type quiet struct{ w io.Writer } + +func (q quiet) Write(p []byte) (int, error) { + _, _ = q.w.Write(p) + return len(p), nil +} + +// secrets are what a key or token looks like in a line of text: a bearer +// or basic credential, a query parameter naming one, and the shapes +// vendors' keys have (sk-…, Google's AIza…, GitHub's gh?_…, a JWT). Each +// keeps its first characters, for telling which it was, and masks the +// rest. +var secrets = []struct { + re *regexp.Regexp + keep string +}{ + {regexp.MustCompile(`(?i)\b((?:bearer|basic)\s+)[A-Za-z0-9._~+/=-]{8,}`), "${1}…"}, + {regexp.MustCompile(`(?i)([?&](?:key|api[_-]?key|apikey|access_token|refresh_token|id_token|token|auth|sig|signature|code)=)[^&\s"'<>]+`), "${1}…"}, + {regexp.MustCompile(`\b(sk-(?:ant-|proj-)?)[A-Za-z0-9_-]{12,}`), "${1}…"}, + {regexp.MustCompile(`\b(AIza)[0-9A-Za-z_-]{20,}`), "${1}…"}, + {regexp.MustCompile(`\b(gh[opsur]_)[A-Za-z0-9]{20,}`), "${1}…"}, + {regexp.MustCompile(`\b(eyJ)[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}`), "${1}…"}, +} + +// scrub is p with whatever looks like a key or token masked. +func scrub(p []byte) []byte { + for _, s := range secrets { + p = s.re.ReplaceAll(p, []byte(s.keep)) + } + return p +} diff --git a/internal/applog/applog_test.go b/internal/applog/applog_test.go new file mode 100644 index 000000000..2ba741df9 --- /dev/null +++ b/internal/applog/applog_test.go @@ -0,0 +1,181 @@ +package applog + +import ( + "bytes" + "io" + "log" + "os" + "path/filepath" + "runtime/debug" + "strings" + "testing" + + "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/testenv" +) + +func TestMain(m *testing.M) { os.Exit(testenv.RunIn(m, nil)) } + +// opened is open for a test, closed with the runtime's copy of it let go +// after the test: Windows removes no folder with a file open in it. +func opened(t *testing.T, path string, limit int64) *file { + t.Helper() + w, err := open(path, limit) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = debug.SetCrashOutput(nil, debug.CrashOptions{}) + w.Close() + }) + return w +} + +func read(t *testing.T, p string) string { + t.Helper() + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +// What the app logs goes to app.log in the system's logs folder, as well +// as to stderr: the app opened from the Finder had no terminal, and a +// user asked for its log had none (rayem1w on X). +func TestStartWritesTheLog(t *testing.T) { + t.Cleanup(Stop) + path, err := Start("0.1.test", "app") + if err != nil { + t.Fatal(err) + } + if want := filepath.Join(appdir.Logs(), Name); path != want || Current() != want { + t.Fatalf("Start wrote %q (Current %q), want %q", path, Current(), want) + } + log.Println("gateway: a line the app logged") + got := read(t, path) + for _, want := range []string{"magpie 0.1.test started (app, pid", "this log: " + path, "gateway: a line the app logged"} { + if !strings.Contains(got, want) { + t.Errorf("the log has no %q:\n%s", want, got) + } + } + if fi, err := os.Stat(path); err != nil { + t.Fatal(err) + } else if os.PathSeparator == '/' && fi.Mode().Perm() != 0o600 { + t.Errorf("the log is %v, want 0600: it is the user's alone", fi.Mode().Perm()) + } + + // a second Start (the app opened again in this process) goes on in the + // same file + if _, err := Start("0.1.test", "panel"); err != nil { + t.Fatal(err) + } + log.Println("after the second start") + if got := read(t, path); !strings.Contains(got, "gateway: a line the app logged") || !strings.Contains(got, "after the second start") { + t.Errorf("the second start lost a line:\n%s", got) + } + + Stop() + log.Println("after Stop") + if Current() != "" || strings.Contains(read(t, path), "after Stop") { + t.Errorf("after Stop the log is still written (Current %q)", Current()) + } +} + +// The log goes to stderr as well, as before; a stderr that fails (the app +// opened from Explorer has none) never keeps a line from the file. +func TestStderrToo(t *testing.T) { + dir := t.TempDir() + w := opened(t, filepath.Join(dir, Name), Limit) + var errOut bytes.Buffer + l := log.New(io.MultiWriter(quiet{&errOut}, w), "", 0) + l.Println("both") + l2 := log.New(io.MultiWriter(quiet{failing{}}, w), "", 0) + l2.Println("stderr gone") + if !strings.Contains(errOut.String(), "both") { + t.Errorf("stderr got %q", errOut.String()) + } + if got := read(t, filepath.Join(dir, Name)); !strings.Contains(got, "both") || !strings.Contains(got, "stderr gone") { + t.Errorf("the file got %q", got) + } +} + +type failing struct{} + +func (failing) Write([]byte) (int, error) { return 0, os.ErrClosed } + +// At its limit the log becomes app.old.log, over the one before, and a +// new one starts: two files at most, each about the limit. +func TestRotates(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, Name) + w := opened(t, path, 100) + line := strings.Repeat("x", 39) + "\n" // 40 bytes + for i := 0; i < 10; i++ { + if n, err := w.Write([]byte(line)); err != nil || n != len(line) { + t.Fatalf("write %d: %d, %v", i, n, err) + } + } + for _, p := range []string{path, filepath.Join(dir, OldName)} { + fi, err := os.Stat(p) + if err != nil { + t.Fatalf("%s: %v", filepath.Base(p), err) + } + if fi.Size() > 100 || fi.Size() == 0 { + t.Errorf("%s is %d bytes, want 1..100", filepath.Base(p), fi.Size()) + } + } + ents, _ := os.ReadDir(dir) + if len(ents) != 2 { + t.Errorf("the folder has %d files, want 2", len(ents)) + } +} + +// Another magpie that rotated the log already (an update's new process +// beside the old) leaves this one to open the new file, not to rotate it +// again over the old one. +func TestRotatedByAnother(t *testing.T) { + if os.PathSeparator == '\\' { + t.Skip("Windows moves no file another process has open") + } + dir := t.TempDir() + path := filepath.Join(dir, Name) + w := opened(t, path, 100) + w.Write([]byte(strings.Repeat("a", 80) + "\n")) + // the other process: closes nothing of ours, moves the file and starts + // its own + if err := os.Rename(path, filepath.Join(dir, OldName)); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("other\n"), 0o600); err != nil { + t.Fatal(err) + } + w.Write([]byte(strings.Repeat("b", 40) + "\n")) + if got := read(t, filepath.Join(dir, OldName)); strings.Contains(got, "other") || strings.Contains(got, "b") { + t.Errorf("app.old.log was rotated over: %q", got) + } + if got := read(t, path); !strings.HasPrefix(got, "other\n") || !strings.Contains(got, "bbbb") { + t.Errorf("app.log %q, want the other's line, then ours", got) + } +} + +// What looks like a key or token is masked in the log, its first +// characters kept; the rest of the line is as written. +func TestScrub(t *testing.T) { + for in, want := range map[string]string{ + "Authorization: Bearer abcdefghijklmnop1234": "Authorization: Bearer …", + "GET https://x.example/v1/models?key=AIzaSyAbc123&alt=sse": "GET https://x.example/v1/models?key=…&alt=sse", + "refresh https://auth.example/t?refresh_token=rt.abcdef done": "refresh https://auth.example/t?refresh_token=… done", + "upstream said: invalid key sk-ant-api03-abcdefghijklmnopqrstuv": "upstream said: invalid key sk-ant-…", + "key sk-proj-abcdefghijklmnopqrstuvwx refused": "key sk-proj-… refused", + "google AIzaSyA1234567890abcdefghijklmnopq": "google AIza…", + "github gho_abcdefghijklmnopqrstuvwxyz0123 expired": "github gho_… expired", + "jwt eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N": "jwt eyJ…", + "gateway: claude/claude-sonnet-4-5 200 in 1.2s (codex, 3 tries)": "gateway: claude/claude-sonnet-4-5 200 in 1.2s (codex, 3 tries)", + "provider: sk-short is not a key": "provider: sk-short is not a key", + } { + if got := string(scrub([]byte(in))); got != want { + t.Errorf("scrub(%q) = %q, want %q", in, got, want) + } + } +} diff --git a/internal/cli/gui_log_test.go b/internal/cli/gui_log_test.go new file mode 100644 index 000000000..ded54216f --- /dev/null +++ b/internal/cli/gui_log_test.go @@ -0,0 +1,48 @@ +//go:build !nogui + +package cli + +import ( + "os" + "strings" + "testing" + + "github.com/yetone/magpie/internal/applog" +) + +// The desktop app, its window and its panel each write their log to +// app.log before the app starts: opened from the Finder, the Dock or the +// Start menu it has no terminal, and a user asked for its log had none to +// send (rayem1w on X, 0.1.2330). +func TestTheAppWritesItsLog(t *testing.T) { + was, wasPanel := openApp, openPanel + t.Cleanup(func() { openApp, openPanel = was, wasPanel; applog.Stop() }) + started := 0 + openApp = func(bool, string) error { started++; return nil } + openPanel = func() error { started++; return nil } + + for name, open := range map[string]func() error{ + "app": func() error { return runGUI(false, "") }, + "window": func() error { return runWindow("usage") }, + "panel": runPanel, + } { + applog.Stop() + os.Remove(applog.Path()) + if err := open(); err != nil { + t.Fatalf("%s: %v", name, err) + } + b, err := os.ReadFile(applog.Path()) + if err != nil { + t.Fatalf("%s wrote no log: %v", name, err) + } + if !strings.Contains(string(b), "started (") { + t.Errorf("%s's log says nothing of its start:\n%s", name, b) + } + if applog.Current() != applog.Path() { + t.Errorf("%s: the log it writes is %q, want %q", name, applog.Current(), applog.Path()) + } + } + if started != 3 { + t.Errorf("the app was started %d times, want 3", started) + } +} diff --git a/internal/cli/gui_on.go b/internal/cli/gui_on.go index b10d8095f..6a02fe592 100644 --- a/internal/cli/gui_on.go +++ b/internal/cli/gui_on.go @@ -3,15 +3,25 @@ package cli import ( + "log" + + "github.com/yetone/magpie/internal/applog" "github.com/yetone/magpie/internal/gui" "github.com/yetone/magpie/internal/proc" ) const hasGUI = true -// the desktop app may have been opened from the Finder, with none of the -// PATH a terminal has +// runGUI starts the desktop app, writing its log to a file (startLog). func runGUI(showMain bool, link string) error { + startLog("app") + return openApp(showMain, link) +} + +// openApp starts the desktop app; a var so a test can stand in for it. +// The app may have been opened from the Finder, with none of the PATH a +// terminal has. +var openApp = func(showMain bool, link string) error { proc.UserPath() gui.Started = ownSignals // once Wails handles them: it quits through OnShutdown return gui.Run(version, showMain, link) @@ -27,8 +37,25 @@ func runWindow(view string) error { // runPanel starts the app with its quick panel open, or toggles the panel // of the one already running. func runPanel() error { + startLog("panel") + return openPanel() +} + +// openPanel starts the app with its panel open; a var so a test can stand +// in for it. +var openPanel = func() error { proc.UserPath() gui.OpenPanel = true gui.Started = ownSignals // once Wails handles them: it quits through OnShutdown return gui.Run(version, false, "") } + +// startLog has the app write its log to a file as well as stderr +// (applog): opened from the Finder, the Dock or the Start menu it has no +// terminal, and what it logged went nowhere (rayem1w on X). A var so a +// test can tell runGUI starts it without starting the app. +var startLog = func(how string) { + if _, err := applog.Start(version, how); err != nil { + log.Println("log:", err) + } +} diff --git a/internal/cli/help_cli.go b/internal/cli/help_cli.go index abad1f447..f815cde01 100644 --- a/internal/cli/help_cli.go +++ b/internal/cli/help_cli.go @@ -60,6 +60,8 @@ func helpFor(args []string) string { return cpuUsage case "goroutines": return goroutinesUsage + case "log", "logs": + return logUsage case "sessions": return sessionsUsage case "search": diff --git a/internal/cli/log_cli.go b/internal/cli/log_cli.go new file mode 100644 index 000000000..72e1184d2 --- /dev/null +++ b/internal/cli/log_cli.go @@ -0,0 +1,187 @@ +package cli + +// magpie log: where magpie's logs are, and the app's last lines. The app +// opened from the Finder, the Dock or the Start menu writes its log to a +// file (applog), which a user asked for it finds here or in Settings › +// About › Log (rayem1w on X had been told of serve.log, which only the +// service writes). + +import ( + "bufio" + "bytes" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/yetone/magpie/internal/applog" + "github.com/yetone/magpie/internal/daemon" + "github.com/yetone/magpie/internal/tui" +) + +const logUsage = `usage: magpie log [--path] [-n N] [-f] + where magpie's logs are on this computer: the app's own (the app, the menu bar and the + panel write it, wherever they were opened from), the one before it, and the logs of + magpie serve as a service (magpie daemon) or left running by magpie tui, when there are. + --path the app's log alone, its path only + -n N the app log's last N lines (100 with -f) + -f the app log's last lines, then each line as it is written, until Ctrl+C + Send the app's log with a report. It holds what magpie did, not your keys, prompts or replies.` + +// logCmd: magpie log [--path] [-n N] [-f] +func logCmd(args []string) error { + pathOnly, follow, lines := false, false, -1 + for i := 0; i < len(args); i++ { + switch a := args[i]; { + case a == "--path": + pathOnly = true + case a == "-f" || a == "--follow": + follow = true + case a == "-n" || a == "--lines": + if i+1 == len(args) { + return errors.New("-n takes a number of lines (magpie log -n 200)") + } + i++ + n, err := strconv.Atoi(args[i]) + if err != nil || n < 0 { + return fmt.Errorf("-n takes a number of lines, not %q (magpie log -n 200)", args[i]) + } + lines = n + default: + return fmt.Errorf("unknown argument %s (magpie log [--path] [-n N] [-f])", a) + } + } + path := applog.Path() + switch { + case pathOnly && (follow || lines >= 0): + return errors.New("--path prints the path alone: use it without -n or -f") + case pathOnly: + fmt.Println(path) + return nil + case follow || lines >= 0: + if lines < 0 { + lines = 100 + } + return tailLog(os.Stdout, path, lines, follow, nil) + } + fmt.Print(logsHere(path)) + return nil +} + +// logsHere says where each of magpie's logs is: the app's, always, and +// the others that are there. +func logsHere(path string) string { + var b strings.Builder + fmt.Fprintf(&b, "%s\n", path) + if _, err := os.Stat(path); err != nil { + fmt.Fprintf(&b, " the app's log: nothing yet; the app writes it once it is opened\n") + } else { + fmt.Fprintf(&b, " the app's log (Settings › About › Log); magpie log -f follows it\n") + } + if old := filepath.Join(filepath.Dir(path), applog.OldName); exists(old) { + fmt.Fprintf(&b, "%s\n the app's log before it, kept once it reached %d MiB\n", old, applog.Limit>>20) + } + if st, err := daemon.Get(); err == nil && st.Installed && st.Logs != "" { + fmt.Fprintf(&b, "%s\n magpie serve as a service (magpie daemon)\n", st.Logs) + } + if bg := tui.BackgroundLog(); exists(bg) { + fmt.Fprintf(&b, "%s\n magpie serve left running by magpie tui as it quit\n", bg) + } + return b.String() +} + +func exists(p string) bool { + _, err := os.Stat(p) + return err == nil +} + +// tailLog writes the last n lines of the log at path to w, then, with +// follow, what is written to it after, until stop is closed (nil: until +// magpie is ended). A log rotated meanwhile is read again from its start. +func tailLog(w io.Writer, path string, n int, follow bool, stop <-chan struct{}) error { + f, err := os.Open(path) + if err != nil { + if errors.Is(err, os.ErrNotExist) && follow { + fmt.Fprintf(os.Stderr, "magpie: %s isn't there yet: waiting for the app to write it\n", path) + } else if errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("%s isn't there yet: the app writes it once it is opened", path) + } else { + return err + } + } + var at int64 + if f != nil { + b, err := io.ReadAll(f) + if err != nil { + f.Close() + return err + } + at = int64(len(b)) + w.Write(lastLines(b, n)) + } + if !follow { + if f != nil { + f.Close() + } + return nil + } + tick := time.NewTicker(300 * time.Millisecond) + defer tick.Stop() + defer func() { + if f != nil { + f.Close() + } + }() + for { + select { + case <-stop: + return nil + case <-tick.C: + } + // a new file at path (rotated, or written for the first time): + // read it from its start + if fi, err := os.Stat(path); err == nil { + var mine os.FileInfo + if f != nil { + mine, _ = f.Stat() + } + if f == nil || mine == nil || !os.SameFile(fi, mine) || fi.Size() < at { + if nf, err := os.Open(path); err == nil { + if f != nil { + // what the old file got after the last read first + io.Copy(w, f) + f.Close() + } + f, at = nf, 0 + } + } + } + if f == nil { + continue + } + n, _ := io.Copy(w, bufio.NewReader(f)) + at += n + } +} + +// lastLines is b's last n lines. +func lastLines(b []byte, n int) []byte { + if n == 0 { + return nil + } + i := len(b) + if i > 0 && b[i-1] == '\n' { + i-- + } + for ; n > 0; n-- { + i = bytes.LastIndexByte(b[:i], '\n') + if i < 0 { + return b + } + } + return b[i+1:] +} diff --git a/internal/cli/log_cli_test.go b/internal/cli/log_cli_test.go new file mode 100644 index 000000000..a7f14b348 --- /dev/null +++ b/internal/cli/log_cli_test.go @@ -0,0 +1,142 @@ +package cli + +import ( + "bytes" + "io" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/applog" +) + +// logOut runs `magpie log` with args and returns what it printed. +func logOut(t *testing.T, args ...string) (string, error) { + t.Helper() + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + old := os.Stdout + os.Stdout = w + done := make(chan string) + go func() { b, _ := io.ReadAll(r); done <- string(b) }() + err = run(append([]string{"log"}, args...)) + w.Close() + os.Stdout = old + out := <-done + r.Close() + return out, err +} + +func writeLog(t *testing.T, s string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(applog.Path()), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(applog.Path(), []byte(s), 0o600); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.Remove(applog.Path()) }) +} + +// `magpie log` says where the app's log is, there or not yet; --path +// prints the path alone, for a script or a reply to paste it in. +func TestLogSaysWhere(t *testing.T) { + os.Remove(applog.Path()) + out, err := logOut(t) + if err != nil || !strings.HasPrefix(out, applog.Path()+"\n") || !strings.Contains(out, "nothing yet") { + t.Fatalf("magpie log, no log yet: %v\n%s", err, out) + } + writeLog(t, "one\n") + if out, err = logOut(t); err != nil || !strings.Contains(out, "Settings › About › Log") { + t.Errorf("magpie log: %v\n%s", err, out) + } + if out, err = logOut(t, "--path"); err != nil || out != applog.Path()+"\n" { + t.Errorf("magpie log --path: %v, %q, want the path alone", err, out) + } +} + +// -n prints the app log's last lines. +func TestLogLastLines(t *testing.T) { + writeLog(t, "one\ntwo\nthree\nfour\n") + for n, want := range map[string]string{"2": "three\nfour\n", "0": "", "9": "one\ntwo\nthree\nfour\n"} { + if out, err := logOut(t, "-n", n); err != nil || out != want { + t.Errorf("magpie log -n %s: %v, %q, want %q", n, err, out, want) + } + } + os.Remove(applog.Path()) + if _, err := logOut(t, "-n", "5"); err == nil || !strings.Contains(err.Error(), "isn't there yet") { + t.Errorf("magpie log -n with no log: %v", err) + } +} + +// A flag or value it doesn't know is refused, never taken for something. +func TestLogRefusesWhatItDoesntKnow(t *testing.T) { + for _, args := range [][]string{{"--bogus"}, {"-n"}, {"-n", "many"}, {"-n", "-3"}, {"--path", "-f"}, {"app.log"}} { + if out, err := logOut(t, args...); err == nil { + t.Errorf("magpie log %v: no error\n%s", args, out) + } + } + if !strings.Contains(helpFor([]string{"log", "--help"}), "usage: magpie log") { + t.Errorf("magpie log --help: %q", helpFor([]string{"log", "--help"})) + } +} + +// -f prints what is written after, and a log rotated meanwhile is read +// from its start. +func TestLogFollows(t *testing.T) { + writeLog(t, "old\n") + var mu syncBuf + stop := make(chan struct{}) + done := make(chan error) + go func() { done <- tailLog(&mu, applog.Path(), 1, true, stop) }() + until(t, &mu, "old\n") + f, err := os.OpenFile(applog.Path(), os.O_APPEND|os.O_WRONLY, 0) + if err != nil { + t.Fatal(err) + } + f.WriteString("appended\n") + f.Close() + until(t, &mu, "old\nappended\n") + os.Rename(applog.Path(), filepath.Join(filepath.Dir(applog.Path()), applog.OldName)) + t.Cleanup(func() { os.Remove(filepath.Join(filepath.Dir(applog.Path()), applog.OldName)) }) + os.WriteFile(applog.Path(), []byte("rotated\n"), 0o600) + until(t, &mu, "old\nappended\nrotated\n") + close(stop) + if err := <-done; err != nil { + t.Fatal(err) + } +} + +type syncBuf struct { + mu sync.Mutex + b bytes.Buffer +} + +func (s *syncBuf) Write(p []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.Write(p) +} + +func (s *syncBuf) String() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.String() +} + +// until waits for b to read want, the state the test is about. +func until(t *testing.T, b *syncBuf, want string) { + t.Helper() + deadline := time.Now().Add(20 * time.Second) + for b.String() != want { + if time.Now().After(deadline) { + t.Fatalf("followed %q, want %q", b.String(), want) + } + time.Sleep(20 * time.Millisecond) + } +} diff --git a/internal/cli/main.go b/internal/cli/main.go index 224bef809..b1a26f64f 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -121,6 +121,7 @@ const usage = `magpie — one place to pick every agent's model magpie heap [] a Go heap profile of the running magpie, with its memory numbers, for a report of it using too much memory magpie cpu [] [--seconds N] a Go CPU profile of the running magpie over 30s (5..120) while you use it, for a report of it using too much CPU magpie goroutines [] every goroutine of the running magpie, its stack and how long it waited, for a report of it stuck at something + magpie log [--path] [-n N] [-f] where magpie's logs are, to send with a report: the app's (app.log), the service's; -n prints the app log's last N lines, -f follows it magpie gateway-key list|add [--read-only]|rotate |remove manage the keys clients use to call a shared gateway magpie gateway-key limit [list|off|reset [n]|remove |[add] day|week|month|d|h --tokens N --cost USD --cache-reads] a key's own limits, and what it used magpie gateway-key models [all|/|/* ...] the models a key may use, every one unless it names some @@ -306,6 +307,11 @@ func run(args []string) error { // the running magpie's goroutines: asks it, and moves nothing here return goroutinesCmd(args[1:]) } + if len(args) > 0 && (args[0] == "log" || args[0] == "logs") { + // where magpie's logs are, and the app log's last lines: reads + // files, and moves nothing + return logCmd(args[1:]) + } if len(args) == 2 && args[0] == agent.DryRunArg { // an agent disconnected on a copy of its files under a temporary // home, for the Agents page to show what disconnecting changes diff --git a/internal/cli/userpath_test.go b/internal/cli/userpath_test.go index 81322bce8..14f8b89a7 100644 --- a/internal/cli/userpath_test.go +++ b/internal/cli/userpath_test.go @@ -12,11 +12,30 @@ import ( // TestGatewayStartsGetUserPath: every way magpie starts with a gateway // gives what it starts the node a version manager put on PATH only in the // shell's profile (#2685, #3803). magpie tui runs in a terminal, with its -// PATH already. +// PATH already. A start counts when it calls proc.UserPath, or calls a +// function or func var of this package that does (runGUI's openApp, which +// a test stands in for). func TestGatewayStartsGetUserPath(t *testing.T) { want := map[string]bool{"runGUI": false, "runPanel": false, "webCmd": false, "serveCmd": false} files, _ := filepath.Glob("*.go") fset := token.NewFileSet() + direct := map[string]bool{} // calls proc.UserPath itself + calls := map[string][]string{} // the package's names it calls + look := func(name string, body ast.Node) { + ast.Inspect(body, func(n ast.Node) bool { + switch n := n.(type) { + case *ast.SelectorExpr: + if id, ok := n.X.(*ast.Ident); ok && id.Name == "proc" && n.Sel.Name == "UserPath" { + direct[name] = true + } + case *ast.CallExpr: + if id, ok := n.Fun.(*ast.Ident); ok { + calls[name] = append(calls[name], id.Name) + } + } + return true + }) + } for _, f := range files { if strings.HasSuffix(f, "_test.go") { continue @@ -26,25 +45,34 @@ func TestGatewayStartsGetUserPath(t *testing.T) { t.Fatal(err) } for _, d := range file.Decls { - fn, ok := d.(*ast.FuncDecl) - if !ok || fn.Body == nil { - continue - } - if _, named := want[fn.Name.Name]; !named { - continue - } - ast.Inspect(fn.Body, func(n ast.Node) bool { - if sel, ok := n.(*ast.SelectorExpr); ok && sel.Sel.Name == "UserPath" { - if id, ok := sel.X.(*ast.Ident); ok && id.Name == "proc" { - want[fn.Name.Name] = true + switch d := d.(type) { + case *ast.FuncDecl: + if d.Body != nil && d.Recv == nil { + look(d.Name.Name, d.Body) + } + case *ast.GenDecl: + for _, sp := range d.Specs { + vs, ok := sp.(*ast.ValueSpec) + if !ok { + continue + } + for i, v := range vs.Values { + if fl, ok := v.(*ast.FuncLit); ok && i < len(vs.Names) { + look(vs.Names[i].Name, fl.Body) + } } } - return true - }) + } } } - for name, calls := range want { - if !calls { + for name := range want { + want[name] = direct[name] + for _, c := range calls[name] { + want[name] = want[name] || direct[c] + } + } + for name, ok := range want { + if !ok { t.Errorf("%s doesn't call proc.UserPath", name) } } diff --git a/internal/gui/api.go b/internal/gui/api.go index 7dbee684b..6d4753bc0 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -31,6 +31,7 @@ import ( "github.com/yetone/magpie/internal/access" "github.com/yetone/magpie/internal/agent" + "github.com/yetone/magpie/internal/applog" "github.com/yetone/magpie/internal/autostart" "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/filememo" @@ -397,6 +398,9 @@ type settingsJSON struct { OnNetwork bool `json:"onNetwork,omitempty"` // Dir is the data folder beside a portable magpie (#508) Portable bool `json:"portable,omitempty"` + // Log is the log the desktop app writes (applog), as shown; "" for a + // magpie writing none (magpie web) + Log string `json:"log,omitempty"` // WSL is whether there is WSL to look in for agents (Windows), for // Settings' Detect agents in WSL (#1264) WSL bool `json:"wsl,omitempty"` @@ -709,6 +713,7 @@ func codexWindowUnder(st settings.Settings, model string) *codexRunWindow { func settingsState() settingsJSON { s := settingsJSON{Settings: settings.Load(), Version: Version, Dir: tilde(settings.Dir()), Portable: settings.Portable() != "", Gateway: gateway.URL()} s.AddrEnv = os.Getenv("MAGPIE_ADDR") + s.Log = tilde(applog.Current()) s.Builtins = builtinsState() s.PanelKeys = panelKeysState() s.JSRoutings = middleware.Routings() @@ -2645,6 +2650,20 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { } rw.WriteHeader(http.StatusNoContent) }) + // the app's log folder (applog), from Settings › About's Log row; the + // page names no path here either + mux.HandleFunc("POST /api/settings/log/reveal", func(rw http.ResponseWriter, r *http.Request) { + path := applog.Current() + if path == "" { + fail(rw, errors.New("this magpie writes no log file")) + return + } + if err := w.OpenFolder(filepath.Dir(path)); err != nil { + fail(rw, err) + return + } + rw.WriteHeader(http.StatusNoContent) + }) // the folder of the reports saved of requests held too long before // routing (gateway.HeldDir), from such a request's row on Routing mux.HandleFunc("POST /api/gateway/held/reveal", func(rw http.ResponseWriter, r *http.Request) { diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index f177cb819..38b9456be 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -20057,6 +20057,12 @@ function renderSettings() { open.onclick = () => api("settings/reveal", {}).catch(statusErr); // portable (a data folder beside magpie, #508): everything is in there row(t("Config folder"), s.portable ? t("Portable: everything magpie keeps, in the data folder beside it") : t("providers, profiles and these settings"), s.dir, copyBtn(s.dir, t("Path")), open); + // app.log (applog); magpie web writes none + if (s.log) { + const o = el("button", "text", t("Open")); + o.onclick = () => api("settings/log/reveal", {}).catch(statusErr); + row(t("Log"), t("What magpie has logged, to send with a bug report"), s.log, copyBtn(s.log, t("Path")), o).id = "logRow"; + } renderCLI(row(t("Command line"), t("Checking your shells…"), "")); // served to other machines (magpie web), the one they reach (noahhrreion) const gw = web && s.publicURL || s.gateway; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 2860f93bb..619deafc3 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3269,6 +3269,8 @@ const I18N = { "magpie can't write to the folder it runs from ({dir}), so it can't update itself; move it to a folder you can write to and open it from there.": "magpie 无法写入它所在的文件夹({dir}),所以无法自动更新;请把它移到你有写入权限的文件夹,再从那里打开。", "magpie runs in a container, so it can't update itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "magpie 运行在容器里,无法自动更新;请拉取新镜像(docker pull ghcr.io/yetone/magpie:latest)并重新创建容器。", "Config folder": "配置目录", + "Log": "日志", + "What magpie has logged, to send with a bug report": "magpie 记下的日志,报告问题时可附上", "Command line": "命令行", "Checking your shells…": "正在检查你的 shell…", "Add to PATH": "添加到 PATH", @@ -7488,6 +7490,8 @@ const I18N = { "magpie can't write to the folder it runs from ({dir}), so it can't update itself; move it to a folder you can write to and open it from there.": "magpie 無法寫入它所在的資料夾({dir}),所以無法自動更新;請把它移到你有寫入權限的資料夾,再從那裡開啟。", "magpie runs in a container, so it can't update itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "magpie 在容器中執行,無法自動更新;請拉取新映像(docker pull ghcr.io/yetone/magpie:latest)並重新建立容器。", "Config folder": "設定目錄", + "Log": "日誌", + "What magpie has logged, to send with a bug report": "magpie 記下的日誌,回報問題時可附上", "Command line": "命令列", "Checking your shells…": "正在檢查你的 shell…", "Add to PATH": "新增到 PATH", @@ -11718,6 +11722,8 @@ const I18N = { "magpie can't write to the folder it runs from ({dir}), so it can't update itself; move it to a folder you can write to and open it from there.": "magpie は実行中のフォルダ({dir})に書き込めないため、自動アップデートできません。書き込み可能なフォルダに移動し、そこから開いてください。", "magpie runs in a container, so it can't update itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "magpie はコンテナで実行されているため、自動アップデートできません。新しいイメージを取得し(docker pull ghcr.io/yetone/magpie:latest)、コンテナを作り直してください。", "Config folder": "設定フォルダ", + "Log": "ログ", + "What magpie has logged, to send with a bug report": "magpie が記録したログ。不具合の報告に添えてください", "Command line": "コマンドライン", "Checking your shells…": "シェルを確認しています…", "Add to PATH": "PATH に追加", @@ -15959,6 +15965,8 @@ const I18N = { "magpie can't write to the folder it runs from ({dir}), so it can't update itself; move it to a folder you can write to and open it from there.": "magpie kann nicht in den Ordner schreiben, aus dem es läuft ({dir}), und kann sich daher nicht selbst aktualisieren; verschieben Sie es in einen Ordner mit Schreibrechten und öffnen Sie es von dort.", "magpie runs in a container, so it can't update itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "magpie läuft in einem Container und kann sich daher nicht selbst aktualisieren; laden Sie das neue Image (docker pull ghcr.io/yetone/magpie:latest) und erstellen Sie den Container neu.", "Config folder": "Konfigurationsordner", + "Log": "Protokoll", + "What magpie has logged, to send with a bug report": "Was magpie protokolliert hat, zum Mitschicken bei einem Fehlerbericht", "Command line": "Befehlszeile", "Checking your shells…": "Shells werden geprüft…", "Add to PATH": "Zum PATH hinzufügen", diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index 536acd3dd..7b2c11be5 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -15,8 +15,8 @@ import ( // so a page can't quietly grow back into the core; a change that needs more // raises them and says why in its commit. const ( - appScriptBudget = 1_315_479 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397); 1,269,083 with Free first's option in the provider editor's ROUTINGS, which the Routing page reads too, plus 1.5%; 1,272,726 with the Providers page drawing its last list at once (#1519), the core's page, and the Routing trace's account names read without Object.entries (#1481), plus 1.5%; a dialog growing out of the row that opened it and folding back into it, the core's own since every page's dialogs open through it (10-20); Codex's and Claude Code's own settings moved from Settings into the agent's row on the Agents page, the core's own since the tray panel and the window both draw them (10-20); 1,314,432 with Settings › Privacy's record of what was masked (its summary, the records view and the local model's controls), which belongs to Settings, the core's own, plus 1.5%; 1,336,481 with a provider's Names & levels saying Provider in model names is Settings' and opening it there (joe), and Settings' Image recognition saying where a custom provider's model is marked (nexnull), both in the core's own pages, with no room added (10-23); 1,337,633 with Settings › Models › Replies' Intent classifier timeout (#2934, reyoung), Settings' own row, drawn by waitRow, which the Image generation timeout's row now shares, with no room added; 1,337,735 with the provider editor's link naming a partner's page by its own host (siteHost) instead of usemagpie.ai's /go link, the core's own editor, with no room added (10-23); 1,338,084 with Check in now saying what the press came to (claimed +credits, already today, not available yet) where it said "refreshed" (#3326), the check-in row the tray panel draws too, the core's own, with no room added (10-23); 1,338,929 with a new partner's tile keeping a small dot until it is opened, in the add sheet, the core's own, with no room added (10-23); 1,343,324 with the sidebar's open-page row marked by one shape that moves on a spring (navTopGo), the window's own shell, which every page sits beside, with no room added (10-23); 1,343,465 with a dialog kept centred while its content comes in, until it is pressed (holdModal, every page's dialogs), the core's own, with no room added (10-24); 1,317,486 with what masking did moved out to Insights › Masking (plugins/redact), the budget lowered to it (10-24); 1,321,336 with Codex's one subagent model, its card's square saying plainly what each choice does and a row with a name in its sheet, where two squares read alike (the owner), the Agents page's, which the tray panel draws too, the core's own, with no room added (10-24); 1,321,424 with Settings › Models' Image generation MCP server row beside Image recognition's (JonahFu on X), the two drawn by one helper (mcpRow), Settings' own, with no room added (10-25); 1,321,994 with a provider of the user's set never to rest for a limit (zoecats), the provider editor's Advanced row, the core's own editor, with no room added (10-25); 1,322,289 with Settings › Privacy's Keep a key's form under Mask secrets (Charles Cao on X), Settings' own row, with no room added (10-25); 1,322,537 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,323,401 with the tray panel drawing its last allowances at once and asking for them beside the state (#3160, #3134), the tray panel's, the core's own, and the 4 bytes 84c50f032 added, with no room added (10-25); 1,326,105 with many releases' notes merged into one list by kind, each line with its version (the owner), in the update sheet and What's new, with no room added (10-25); 1,321,319 with Settings › Observability moved out to its plugin (plugins/otel/page.js) and its Langfuse setup there (an X user), the budget lowered to it (10-26); a quota card whose window is used but names no reset no longer saying "Not used yet" (windy on Discord) raised it to 1,321,347, and back to 1,321,319 with Settings' model pickers sharing one row helper (modelOpt) where six kept their own copy, no raise (10-26); 1,325,845 with every slow page's skeletons getting magpie's bird hopping bar to bar (skelBird, the owner after the Plugins page's README), one bird for the window over whatever page or dialog is loading, the core's own, with no room added (10-26); 1,310,129 with Settings › Network and sharing's gateway rows (its port, bare ids, local network, allowed addresses, web pages) moved out to the gateway plugin (plugins/gateway/settings.js), the budget lowered to it (10-27); 1,310,269 with Test models naming the first model that failed and its error in the status line, where it said only how many (ysm119 on Discord), the provider editor's, the core's own, with no room added (10-27); 1,310,460 with Settings › About's Website row linking usemagpie.ai (the owner), Settings' own row, with no room added (10-27); 1,309,669 with a pool's Stop at the caps and Check usage near a cap ticks under a provider's accounts (plugins#349), the core's own editor, its account rows' Remove and add rows each drawn by one helper (forgetOf, addRow), with no room added (10-28); 1,311,681 with Install another agent on the Agents page naming the agents Plugins has (More in Plugins) and opening Plugins at its Agents (the owner), the Agents page's, the core's own, with no room added (10-28); 1,311,735 with More in Plugins in sight while Install another agent is folded (the owner), with no room added (10-29); 1,313,704 with a window whose WebKit scrolls under wheels it never tells of (macOS 13) remembered once seen, a scroll at rest then waiting 120ms for a second the same way within 80ms before it is put back, kept for a late wheel to give back (waitsBack), and a load landing under the wheel keeping the reader's way (backAfterLoad, issennknight), the window's own scroll guard, with no room added (10-29); back to 1,311,735 with Settings › Models › Web search's rows (renderSearch, renderSearcher, the search APIs' keys) moved out to the search plugin (plugins/search/settings.js), app.js 1,292,527 after it, not lowered further since what is left plus 1.5% is over it (#4133, 10-29); 1,315,316 with the Agents row of a Claude Code or Codex not connected saying the account it is signed in to and switching it to another (Switch accounts only, the owner on X), in place of the failover line's ChatGPT accounts button, the Agents page's, the core's own, its comments cut down, with no room added (10-30); 1,317,705 with a Claude account added from a setup-token (sfss5362 on X): the sign-in's Use a setup-token instead…, its sheet, and its account row's magpie only, the provider editor's account rows, the core's own editor, its comments cut down, with no room added (10-30); back to 1,315,316 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, loaded when one is asked for (signAsk, 10-30); 1,315,479 with the provider editor lining its Advanced up with its fields (the owner: 高级这个折叠按钮为什么在一个前不着村后不着店的位置?) and a refresh on each of its accounts (在这里也要加上手动刷新用量的按钮), the core's own editor, with no room added (10-31) - coreScriptBudget = 1_538_554 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30); 1,539,423 with a Claude account added from a setup-token (sfss5362 on X), in app.js, with no room added (10-30); 1,538,975 with purposes.js written as compact JSON by genpurposes and the MCP tool purpose in it, 448 bytes less in all (ferock on Discord), lowered to it (10-30); 1,536,586 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, lowered by the 2,389 the setup-token raised it (10-30); 1,536,631 with the 45 bytes b62fa332f added to app.js (Send requests unmasked for subscriptions and plugin providers too) without a raise, with no room added (10-31); 1,537,356 with Settings › Models › Replies › Claude Code's interactive mode, a row beside Short Claude system prompt (the owner), in app.js, with no room added (10-31); Long conversations in Codex's row naming the config.toml keys Codex reads before it, with Take it out, and the window magpie tells Codex for the model it runs (zgjfjfl on Discord) raised it to 1,537,669, and it is back under 1,537,356 with the key list and the window's size written by the server (codexKeysText, tokensSize) and the row's words cut, no raise (10-31); 1,538,554 with the same two, with no room added (10-31) + appScriptBudget = 1_315_603 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397); 1,269,083 with Free first's option in the provider editor's ROUTINGS, which the Routing page reads too, plus 1.5%; 1,272,726 with the Providers page drawing its last list at once (#1519), the core's page, and the Routing trace's account names read without Object.entries (#1481), plus 1.5%; a dialog growing out of the row that opened it and folding back into it, the core's own since every page's dialogs open through it (10-20); Codex's and Claude Code's own settings moved from Settings into the agent's row on the Agents page, the core's own since the tray panel and the window both draw them (10-20); 1,314,432 with Settings › Privacy's record of what was masked (its summary, the records view and the local model's controls), which belongs to Settings, the core's own, plus 1.5%; 1,336,481 with a provider's Names & levels saying Provider in model names is Settings' and opening it there (joe), and Settings' Image recognition saying where a custom provider's model is marked (nexnull), both in the core's own pages, with no room added (10-23); 1,337,633 with Settings › Models › Replies' Intent classifier timeout (#2934, reyoung), Settings' own row, drawn by waitRow, which the Image generation timeout's row now shares, with no room added; 1,337,735 with the provider editor's link naming a partner's page by its own host (siteHost) instead of usemagpie.ai's /go link, the core's own editor, with no room added (10-23); 1,338,084 with Check in now saying what the press came to (claimed +credits, already today, not available yet) where it said "refreshed" (#3326), the check-in row the tray panel draws too, the core's own, with no room added (10-23); 1,338,929 with a new partner's tile keeping a small dot until it is opened, in the add sheet, the core's own, with no room added (10-23); 1,343,324 with the sidebar's open-page row marked by one shape that moves on a spring (navTopGo), the window's own shell, which every page sits beside, with no room added (10-23); 1,343,465 with a dialog kept centred while its content comes in, until it is pressed (holdModal, every page's dialogs), the core's own, with no room added (10-24); 1,317,486 with what masking did moved out to Insights › Masking (plugins/redact), the budget lowered to it (10-24); 1,321,336 with Codex's one subagent model, its card's square saying plainly what each choice does and a row with a name in its sheet, where two squares read alike (the owner), the Agents page's, which the tray panel draws too, the core's own, with no room added (10-24); 1,321,424 with Settings › Models' Image generation MCP server row beside Image recognition's (JonahFu on X), the two drawn by one helper (mcpRow), Settings' own, with no room added (10-25); 1,321,994 with a provider of the user's set never to rest for a limit (zoecats), the provider editor's Advanced row, the core's own editor, with no room added (10-25); 1,322,289 with Settings › Privacy's Keep a key's form under Mask secrets (Charles Cao on X), Settings' own row, with no room added (10-25); 1,322,537 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,323,401 with the tray panel drawing its last allowances at once and asking for them beside the state (#3160, #3134), the tray panel's, the core's own, and the 4 bytes 84c50f032 added, with no room added (10-25); 1,326,105 with many releases' notes merged into one list by kind, each line with its version (the owner), in the update sheet and What's new, with no room added (10-25); 1,321,319 with Settings › Observability moved out to its plugin (plugins/otel/page.js) and its Langfuse setup there (an X user), the budget lowered to it (10-26); a quota card whose window is used but names no reset no longer saying "Not used yet" (windy on Discord) raised it to 1,321,347, and back to 1,321,319 with Settings' model pickers sharing one row helper (modelOpt) where six kept their own copy, no raise (10-26); 1,325,845 with every slow page's skeletons getting magpie's bird hopping bar to bar (skelBird, the owner after the Plugins page's README), one bird for the window over whatever page or dialog is loading, the core's own, with no room added (10-26); 1,310,129 with Settings › Network and sharing's gateway rows (its port, bare ids, local network, allowed addresses, web pages) moved out to the gateway plugin (plugins/gateway/settings.js), the budget lowered to it (10-27); 1,310,269 with Test models naming the first model that failed and its error in the status line, where it said only how many (ysm119 on Discord), the provider editor's, the core's own, with no room added (10-27); 1,310,460 with Settings › About's Website row linking usemagpie.ai (the owner), Settings' own row, with no room added (10-27); 1,309,669 with a pool's Stop at the caps and Check usage near a cap ticks under a provider's accounts (plugins#349), the core's own editor, its account rows' Remove and add rows each drawn by one helper (forgetOf, addRow), with no room added (10-28); 1,311,681 with Install another agent on the Agents page naming the agents Plugins has (More in Plugins) and opening Plugins at its Agents (the owner), the Agents page's, the core's own, with no room added (10-28); 1,311,735 with More in Plugins in sight while Install another agent is folded (the owner), with no room added (10-29); 1,313,704 with a window whose WebKit scrolls under wheels it never tells of (macOS 13) remembered once seen, a scroll at rest then waiting 120ms for a second the same way within 80ms before it is put back, kept for a late wheel to give back (waitsBack), and a load landing under the wheel keeping the reader's way (backAfterLoad, issennknight), the window's own scroll guard, with no room added (10-29); back to 1,311,735 with Settings › Models › Web search's rows (renderSearch, renderSearcher, the search APIs' keys) moved out to the search plugin (plugins/search/settings.js), app.js 1,292,527 after it, not lowered further since what is left plus 1.5% is over it (#4133, 10-29); 1,315,316 with the Agents row of a Claude Code or Codex not connected saying the account it is signed in to and switching it to another (Switch accounts only, the owner on X), in place of the failover line's ChatGPT accounts button, the Agents page's, the core's own, its comments cut down, with no room added (10-30); 1,317,705 with a Claude account added from a setup-token (sfss5362 on X): the sign-in's Use a setup-token instead…, its sheet, and its account row's magpie only, the provider editor's account rows, the core's own editor, its comments cut down, with no room added (10-30); back to 1,315,316 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, loaded when one is asked for (signAsk, 10-30); 1,315,479 with the provider editor lining its Advanced up with its fields (the owner: 高级这个折叠按钮为什么在一个前不着村后不着店的位置?) and a refresh on each of its accounts (在这里也要加上手动刷新用量的按钮), the core's own editor, with no room added (10-31); 1,315,603 with About's Log row, the path of the log the app writes and an Open for its folder (rayem1w on X), in app.js, its comment cut to one line, with no room added (10-31) + coreScriptBudget = 1_538_678 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30); 1,539,423 with a Claude account added from a setup-token (sfss5362 on X), in app.js, with no room added (10-30); 1,538,975 with purposes.js written as compact JSON by genpurposes and the MCP tool purpose in it, 448 bytes less in all (ferock on Discord), lowered to it (10-30); 1,536,586 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, lowered by the 2,389 the setup-token raised it (10-30); 1,536,631 with the 45 bytes b62fa332f added to app.js (Send requests unmasked for subscriptions and plugin providers too) without a raise, with no room added (10-31); 1,537,356 with Settings › Models › Replies › Claude Code's interactive mode, a row beside Short Claude system prompt (the owner), in app.js, with no room added (10-31); Long conversations in Codex's row naming the config.toml keys Codex reads before it, with Take it out, and the window magpie tells Codex for the model it runs (zgjfjfl on Discord) raised it to 1,537,669, and it is back under 1,537,356 with the key list and the window's size written by the server (codexKeysText, tokensSize) and the row's words cut, no raise (10-31); 1,538,554 with the same two, with no room added (10-31); 1,538,678 with About's Log row (rayem1w on X), with no room added (10-31) ) func TestCoreScriptBudget(t *testing.T) { diff --git a/internal/gui/tests/about-log.test.cjs b/internal/gui/tests/about-log.test.cjs new file mode 100644 index 000000000..4cf0d8a9d --- /dev/null +++ b/internal/gui/tests/about-log.test.cjs @@ -0,0 +1,66 @@ +const assert = require("node:assert/strict"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { fixture } = require("./fixtures/caller-keys.cjs"); +const { openPart } = require("./reader.cjs"); + +// A user asked for magpie's log had none: the app opened from the Finder +// wrote it nowhere (rayem1w on X). It writes app.log now, and Settings › +// About names it with a Log row whose Open shows its folder, in every +// language and at the tray panel's width. magpie web writes none, and +// shows no row. +const words = { + en: ["Log", "Open"], zh: ["日志", "打开"], "zh-TW": ["日誌", "開啟"], ja: ["ログ", "開く"], de: ["Protokoll", "Öffnen"], +}; +const logPath = "~/Library/Logs/magpie/app.log"; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + for (const width of [1100, 420]) { + test(`${engine} ${lang} ${width}: About names the app's log`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(6000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const base = fixture(lang, "light", []); + await page.route("**/*", (route, req) => { + const url = new URL(req.url()); + if (url.pathname === "/api/settings/log/reveal") { + return route.fulfill({ json: { ok: true } }); + } + if (url.pathname !== "/api/settings") return base(route); + // the fixture's settings, with the log this app writes + return base({ request: () => req, fulfill: (o) => route.fulfill(o.json ? { ...o, json: { ...o.json, log: logPath } } : o) }); + }); + await page.goto("http://magpie.test/"); + await page.locator("#prefs").click(); + await openPart(page, "about"); + const row = page.locator("#logRow"); + await row.waitFor(); + assert.equal(await row.locator(".who").first().textContent().then((s) => s.trim().startsWith(words[lang][0])), true, "the row is named " + words[lang][0]); + assert.equal(await row.locator("code").textContent(), logPath); + const opened = page.waitForRequest((r) => r.url().includes("/api/settings/log/reveal")); + await row.locator("button.text", { hasText: words[lang][1] }).click(); + assert.equal((await opened).method(), "POST"); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "About wider than the window"); + assert.deepEqual(errors, []); + }); + } + } + test(`${engine}: magpie web writes no log, and About names none`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 1100, height: 800 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(6000); + page.setDefaultNavigationTimeout(60000); + await page.route("**/*", fixture("en", "light", [])); + await page.goto("http://magpie.test/"); + await page.locator("#prefs").click(); + await openPart(page, "about"); + await page.locator("#about .row", { has: page.locator(".who", { hasText: "Config folder" }) }).waitFor(); + assert.equal(await page.locator("#logRow").count(), 0); + }); +} diff --git a/internal/tui/keep.go b/internal/tui/keep.go index 079309d49..da7cb4c4c 100644 --- a/internal/tui/keep.go +++ b/internal/tui/keep.go @@ -83,6 +83,10 @@ func keepGateway(connected bool) string { return msg } +// BackgroundLog is the log of a magpie serve that magpie tui left +// running as it quit (serveInBackground). +func BackgroundLog() string { return filepath.Join(appdir.Cache(), "serve.log") } + // serveInBackground starts `magpie serve` on its own, outliving this // process and its terminal, its output in a log in magpie's cache. func serveInBackground() (int, string, error) { @@ -90,7 +94,7 @@ func serveInBackground() (int, string, error) { if err != nil { return 0, "", err } - log := filepath.Join(appdir.Cache(), "serve.log") + log := BackgroundLog() if err := os.MkdirAll(filepath.Dir(log), 0o700); err != nil { return 0, "", err } diff --git a/site/public/docs/ja/privacy.html b/site/public/docs/ja/privacy.html index abbc49965..875d48ffe 100644 --- a/site/public/docs/ja/privacy.html +++ b/site/public/docs/ja/privacy.html @@ -168,6 +168,7 @@

install-id と stats-sent は magpie のフォルダーにあります。macOS と Linux では ~/.config/magpie、Windows では %USERPROFILE%\.config\magpie、$XDG_CONFIG_HOME が設定されていれば $XDG_CONFIG_HOME/magpie、ポータブル版ではそのデータフォルダーです。partner-counts.json は ~/.cache/magpie($XDG_CACHE_HOME/magpie、ポータブル版ではデータフォルダーの cache)にあります。どれも削除できます。install-id を消すと次の送信で新しいランダムな ID が作られ、新しいユーザーとして数えられます。カウントをオフにすれば、どれも再び書かれません。

リクエストアーカイブ(使用量ページのリクエスト一覧の上にあるリクエストアーカイブスイッチ)は既定でオフです。同期に S3 バケットがないときにオンにすると、ゲートウェイを通る各呼び出しのヘッダーと本文を、S3 アーカイブと同じようにシークレットを伏せて、magpie のフォルダーの request-archive に 1 呼び出し 1 ファイルで保存します。読めるのはあなたのユーザーだけです。上限は 1 GiB(settings.json の requestArchiveLocalMB)で、超えると古い呼び出しから削除します。このスイッチはこのコンピューターだけのもので、同期で別のコンピューターでオンになることはありません。S3 バケットがあるときはバケットに送られ、ここには何も書かれません。フォルダーはいつでも削除できます。

+

アプリは自分のしたことをログ app.log に書きます。macOS では ~/Library/Logs/magpie、Windows では %LOCALAPPDATA%\magpie\logs、Linux では ~/.local/state/magpie です(magpie のログはどこにありますか?)。読めるのはあなたのユーザーだけです。magpie がしたことと出会ったエラーを記録し、キー、プロンプト、返答は記録しません。あなたが送らない限り、このコンピューターから出ません。上限は 5 MiB で、古いもの 1 つ(app.old.log)を残します。いつでも削除できます。

usemagpie.ai に見えるもの

magpie はプライバシー設定にかかわらず、どのアプリも自分の更新サーバーに尋ねるのと同じように、自分のサイトにいくつか尋ねます。どのリクエストにもインストール ID やアカウントは付きません。

diff --git a/site/public/docs/ja/start.html b/site/public/docs/ja/start.html index 5c015f3df..a9f7de9e7 100644 --- a/site/public/docs/ja/start.html +++ b/site/public/docs/ja/start.html @@ -267,6 +267,7 @@ magpie claude group/opus-anywhere # これを使う

magpie usage 7dエージェントとモデルごとのトークンとコスト magpie tools · magpie tool generate_image "…" -o hero.pngmagpie が MCP でエージェントに渡すツール(画像生成、画像認識、Web 検索、プラグインのツール)を一覧し、直接呼び出す。生成した画像はファイルに保存 magpie trayメニューバーのアイコンだけで起動 + magpie log · magpie log -fmagpie のログの場所。不具合の報告に添えます。-n 200 でアプリのログの末尾を表示、-f で追いかけます

よくある質問

@@ -283,6 +284,9 @@ magpie claude group/opus-anywhere # これを使う

GitHub に届かない環境で、インストールや更新をするには?

インストーラと magpie update にプロキシを渡します:curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --proxy http://127.0.0.1:7890、または magpie update --proxy socks5://127.0.0.1:1080(http・https・socks5・socks5h に対応。HTTPS_PROXY と ALL_PROXY も使われます)。--mirror <prefix> を付けると、指定した GitHub ダウンロードミラーから <prefix>https://github.com/… としてリリースファイルを取得します。magpie update mirror <prefix> でアプリ自身の更新を含め毎回使い、magpie update mirror off で解除します。指定しない限りミラーは使われず、ファイルの SHA-256 はミラーではなく常に usemagpie.ai から取得するので、ミラーが書き換えたファイルはインストールされません。アプリ自身の更新は Settings → Proxy を通ります。

+

magpie のログはどこにありますか?

+

アプリ(ウィンドウ、メニューバーやトレイのアイコン、パネル。どう開いたかによらず)は app.log を書きます。macOS では ~/Library/Logs/magpie/app.log、Windows では %LOCALAPPDATA%\magpie\logs\app.log、Linux では ~/.local/state/magpie/app.log($XDG_STATE_HOME が設定されていれば $XDG_STATE_HOME/magpie)、ポータブル版ではデータフォルダーの logs です。設定 → 情報 → ログにパスがあり、開くでそのフォルダーを表示します。magpie log はパスを表示し、magpie log -f は追いかけます。5 MiB に達すると隣の app.old.log になり、残るのは最大 2 ファイルです。記録されるのは magpie がしたことと出会ったエラー(プロバイダーがリクエストを断った、再試行した、プラグインが起動しなかった)で、キー、プロンプト、返答は含みません。キーやトークンに見えるものも伏せられます。サービスとして動く magpie serve のログは別の場所です。macOS では ~/Library/Logs/magpie/serve.log、Linux では journalctl --user -u magpie。magpie log はそれも示します。

+

magpie は何を送信しますか?

プロンプト、返答、キー、アカウントは、使っているプロバイダーにだけ送られます。間に magpie 自身のサーバーはありません。リリース版の magpie は 1 日 1 回、使われていることを知らせます。何人が使っていて、何を優先して面倒を見るべきかを知るためです。送るのは、このコンピュータで作ったランダムな ID、magpie のバージョンとシステム、そして使っているエージェント、プロバイダー、モデルを magpie 自身の ID(claude、deepseek、deepseek/deepseek-v4)で、それぞれの数とともに。自分で追加したプロバイダーとそのモデルは custom とだけ記録します。プロバイダー追加シートの先頭に載るパートナーについては、1 日に表示された回数、開かれた回数、追加された回数も送ります(回数のみ)。名前、Base URL、アカウント、キー、プロンプト、使用量は送りません。設定 → プライバシー → 使っているエージェント、プロバイダー、モデルを共有 でエージェント、プロバイダー、モデルとパートナーの回数を外せます。ユーザー数に含める、DO_NOT_TRACK=1、MAGPIE_NO_STATS=1 のどれかですべてオフになります。ソースからのビルドは送信しません。パートナーの公式サイトと「キーを取得」のリンクは usemagpie.ai/go/… を経由し、移動の前にクリックを 1 回数えます(どのパートナーか、どのリンクか、国)。usemagpie.ai はパートナー一覧が取得された回数も数えます。これはサーバー自身が見るもので、どの Web サイトのアクセス集計とも同じく、上の設定には左右されません。ID、IP アドレス、アカウントは記録しません。プラグイン、インポートリンク、ライブラリが示すアイコンは usemagpie.ai/api/icon を経由して取得するので、アイコンのあるサーバーに見えるのはあなたの IP ではなく Cloudflare のアドレスです。このサーバーは画像を中継するだけで、数えることも記録することもしません。magpie が自分から送るものすべては、毎日のカウントの例、手元に残すファイル、各スイッチとともにプライバシーのページに挙げています。

diff --git a/site/public/docs/privacy.html b/site/public/docs/privacy.html index 9be50b01d..82d6366a5 100644 --- a/site/public/docs/privacy.html +++ b/site/public/docs/privacy.html @@ -168,6 +168,7 @@

install-id and stats-sent are in magpie’s folder: ~/.config/magpie on macOS and Linux, %USERPROFILE%\.config\magpie on Windows, $XDG_CONFIG_HOME/magpie when that is set, and the data folder of a portable magpie. partner-counts.json is in ~/.cache/magpie ($XDG_CACHE_HOME/magpie, or cache in a portable magpie’s data folder). You can delete any of them: a deleted install-id is replaced by a new random one at the next send, so you are counted as a new user; with the count off, none of them is written again.

The request archive (the Request archive switch on the Usage page, above the list of requests) is off by default. Turned on while sync has no S3 bucket, it keeps each gateway call’s headers and bodies, secrets masked as for the S3 archive, in request-archive in magpie’s folder, one file per call, readable by your user only. It grows to 1 GiB (requestArchiveLocalMB in settings.json) and the oldest calls are removed past that. The switch is this computer’s own: sync never turns it on at another computer. With an S3 bucket the calls go to the bucket instead, and nothing is written here. Delete the folder whenever you like.

+

The app writes a log of what it did, app.log, in ~/Library/Logs/magpie on macOS, %LOCALAPPDATA%\magpie\logs on Windows and ~/.local/state/magpie on Linux (see Where is magpie’s log?), readable by your user only. It names what magpie did and the errors it met, never keys, prompts or replies, and stays on your computer unless you send it. It is kept to 5 MiB, with one older file, app.old.log. Delete them whenever you like.

What usemagpie.ai sees

magpie asks its own site for a few things, whatever the privacy settings say, as any app asks its update server. None of these requests carries the install id or an account.

diff --git a/site/public/docs/start.html b/site/public/docs/start.html index 5299e2c89..7f3d35aa5 100644 --- a/site/public/docs/start.html +++ b/site/public/docs/start.html @@ -267,6 +267,7 @@ magpie claude group/opus-anywhere # use it magpie usage 7dTokens and cost per agent and model magpie tools · magpie tool generate_image "…" -o hero.pngThe tools magpie gives agents over MCP (image generation, image recognition, web search, plugins’), listed and called directly; an image it makes is saved magpie trayStart with the menu bar icon only + magpie log · magpie log -fWhere magpie’s logs are, to send with a report; -n 200 prints the app log’s last lines, -f follows it

FAQ

@@ -283,6 +284,9 @@ magpie claude group/opus-anywhere # use it

Installing or updating behind a firewall, or without access to GitHub?

Give the installer and magpie update a proxy: curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --proxy http://127.0.0.1:7890, or magpie update --proxy socks5://127.0.0.1:1080 (http, https, socks5 and socks5h; HTTPS_PROXY and ALL_PROXY are honoured too). --mirror <prefix> fetches the release file from a GitHub download mirror you choose, as <prefix>https://github.com/…; magpie update mirror <prefix> keeps it for every update, the app’s too, and magpie update mirror off removes it. No mirror is used unless you give one, and the file’s SHA-256 still comes from usemagpie.ai, never from the mirror: a file the mirror changed is refused. The app’s own updates go through Settings → Proxy.

+

Where is magpie’s log?

+

The app (its window, the menu bar or tray icon and the panel, however it was opened) writes app.log: ~/Library/Logs/magpie/app.log on macOS, %LOCALAPPDATA%\magpie\logs\app.log on Windows, ~/.local/state/magpie/app.log on Linux ($XDG_STATE_HOME/magpie when that is set), and logs in a portable magpie’s data folder. Settings → About → Log has its path and an Open that shows its folder; magpie log prints it, and magpie log -f follows it. At 5 MiB it becomes app.old.log beside it, so two files at most are kept. It holds what magpie did and the errors it met (a provider refusing a request, a retry, a plugin that failed to start), not your keys, prompts or replies; what looks like a key or token is masked anyway. magpie serve run as a service logs elsewhere: ~/Library/Logs/magpie/serve.log on macOS, journalctl --user -u magpie on Linux; magpie log names it too.

+

What does magpie send about me?

Your prompts, replies, keys and accounts go only to the providers you use; magpie has no server of its own in the path. Once a day a released magpie tells us it is in use, so we know how many people use it and what to look after first: a random id made up on your computer, magpie’s version and your system, and which agents, providers and models it is used with, by magpie’s own ids (claude, deepseek, deepseek/deepseek-v4) with how many of each. A provider you added yourself, and a model on it, is only custom. For each partner listed first in the add sheet, how many times a day it was shown, opened and added from goes with them, as counts only. No names, base URLs, accounts, keys, prompts or usage are sent. Settings → Privacy → Share the agents, providers and models I use leaves out the agents, providers and models, and the partner counts; Count me as a user, DO_NOT_TRACK=1 or MAGPIE_NO_STATS=1 turns it all off. Builds from source never send it. A partner's website and key-page links go through usemagpie.ai/go/…, which counts the click (the partner, which link, and a country) before sending you on, and usemagpie.ai counts how many times the partner list is fetched. The server sees these whatever the settings say, as any website sees its visits; no id, address or account is kept with them. Icons named by a plugin, an import link or the library are fetched through usemagpie.ai/api/icon, so their hosts see Cloudflare's address, not yours; the server only passes the picture on, and counts and keeps nothing. The Privacy page lists everything magpie sends by itself, with an example of the daily count, the files it keeps and every switch.

diff --git a/site/public/docs/zh/privacy.html b/site/public/docs/zh/privacy.html index d919bf1f5..d7affa466 100644 --- a/site/public/docs/zh/privacy.html +++ b/site/public/docs/zh/privacy.html @@ -168,6 +168,7 @@

install-id 和 stats-sent 在 magpie 的文件夹里:macOS 和 Linux 上是 ~/.config/magpie,Windows 上是 %USERPROFILE%\.config\magpie,设置了 $XDG_CONFIG_HOME 时是 $XDG_CONFIG_HOME/magpie,便携版则在它的数据文件夹里。partner-counts.json 在 ~/.cache/magpie(或 $XDG_CACHE_HOME/magpie,便携版数据文件夹里的 cache)。这些文件都可以删:删掉 install-id 后,下次发送会生成新的随机 ID,你会被算作新用户;关掉计数后,它们都不会再写入。

请求存档(用量页请求列表上方的请求存档开关)默认关闭。同步没有 S3 存储桶时打开它,每次经过网关的调用的请求头和正文会存到 magpie 文件夹里的 request-archive,一次调用一个文件,只有你的用户能读,密钥按 S3 存档同样的方式遮掉。它最多占 1 GiB(settings.json 里的 requestArchiveLocalMB),超过后先删最早的调用。这个开关只属于这台电脑,同步不会在别的电脑上把它打开。有 S3 存储桶时调用存到桶里,这里不写任何东西。这个文件夹随时可以删。

+

应用会把它做了什么写进日志 app.log:macOS 上在 ~/Library/Logs/magpie,Windows 上在 %LOCALAPPDATA%\magpie\logs,Linux 上在 ~/.local/state/magpie(见 magpie 的日志在哪里?),只有你的用户能读。它记下 magpie 做了什么和遇到的错误,从不记密钥、提示词或回复,除非你发出去,否则只留在你的电脑上。它最多 5 MiB,另留一个更早的 app.old.log。随时可以删。

usemagpie.ai 能看到什么

magpie 会向自己的网站请求几样东西,不受隐私设置影响,就像任何应用访问自己的更新服务器。这些请求都不带安装 ID 或账号。

diff --git a/site/public/docs/zh/start.html b/site/public/docs/zh/start.html index 62e17d7fd..6bf5d28a9 100644 --- a/site/public/docs/zh/start.html +++ b/site/public/docs/zh/start.html @@ -267,6 +267,7 @@ magpie claude group/opus-anywhere # 使用它 magpie usage 7d按 Agent 和模型统计 token 与费用 magpie tools · magpie tool generate_image "…" -o hero.png列出并直接调用 magpie 通过 MCP 给 Agent 的工具(生图、识图、联网搜索、插件的工具);生成的图片保存到文件 magpie tray只启动菜单栏图标 + magpie log · magpie log -fmagpie 的日志在哪里,报告问题时附上;-n 200 打印应用日志的最后几行,-f 持续跟随

常见问题

@@ -283,6 +284,9 @@ magpie claude group/opus-anywhere # 使用它

没有梯子,安装或更新连不上 GitHub 怎么办?

给安装脚本和 magpie update 加代理:curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --proxy http://127.0.0.1:7890,或 magpie update --proxy socks5://127.0.0.1:1080(支持 http、https、socks5、socks5h;环境变量 HTTPS_PROXY、ALL_PROXY 同样生效)。--mirror <前缀> 从你指定的 GitHub 下载镜像取发布文件,即 <前缀>https://github.com/…;magpie update mirror <前缀> 让之后每次更新(包括应用自己的更新)都用它,magpie update mirror off 取消。不指定就不用任何镜像;文件的 SHA-256 始终来自 usemagpie.ai,而不是镜像,镜像改过的文件会被拒绝安装。应用自己的更新走 设置 → 代理。

+

magpie 的日志在哪里?

+

应用(窗口、菜单栏或托盘图标、快捷面板,不论怎样打开)写入 app.log:macOS 上是 ~/Library/Logs/magpie/app.log,Windows 上是 %LOCALAPPDATA%\magpie\logs\app.log,Linux 上是 ~/.local/state/magpie/app.log(设置了 $XDG_STATE_HOME 时是 $XDG_STATE_HOME/magpie),便携版则在数据文件夹的 logs 里。设置 → 关于 → 日志里有它的路径,打开会显示它所在的文件夹;magpie log 打印路径,magpie log -f 持续跟随。满 5 MiB 后它变成旁边的 app.old.log,最多保留两个文件。它记的是 magpie 做了什么、遇到了哪些错误(服务商拒绝请求、重试、插件没能启动),不含你的密钥、提示词或回复;看起来像密钥或令牌的内容也会被遮掉。作为服务运行的 magpie serve 日志在别处:macOS 上是 ~/Library/Logs/magpie/serve.log,Linux 上是 journalctl --user -u magpie;magpie log 也会列出它。

+

magpie 会发送我的哪些信息?

你的提示词、回复、密钥和账号只发给你用的供应商,中间没有 magpie 自己的服务器。正式发布的 magpie 每天告诉我们一次它在用,好让我们知道有多少人在用、该先照顾哪些:本机随机生成的 ID、magpie 版本和系统,以及用了哪些 agent、供应商和模型,只用 magpie 自己的 ID(claude、deepseek、deepseek/deepseek-v4)和各自的数量。你自己添加的供应商及其上的模型只记作 custom。添加供应商页里排在最前的合作伙伴,每天被展示、打开和添加的次数也一并发送,只有次数。不发送名称、Base URL、账号、密钥、提示词和用量。设置 → 隐私 → 分享我用的 agent、provider 和模型 可以去掉 agent、供应商、模型和合作伙伴次数这部分;计入用户数、DO_NOT_TRACK=1 或 MAGPIE_NO_STATS=1 全部关闭。从源码构建的版本从不发送。合作伙伴的官网和「获取 Key」链接经 usemagpie.ai/go/… 跳转,跳转前记一次点击(哪个合作伙伴、哪个链接、哪个国家),usemagpie.ai 也会统计合作伙伴列表被拉取的次数。这部分是服务器本身看到的,和任何网站统计访问一样,不受上面的设置影响;不记录 ID、IP 和账号。插件、导入链接和库里的图标经 usemagpie.ai/api/icon 获取,图标所在的服务器只看到 Cloudflare 的地址,看不到你的 IP;这台服务器只转发图片,不计数也不记录。隐私页列出了 magpie 自己发出的所有内容,附每日计数的示例、它在本机留下的文件和每个开关。