From 5dfbca6274eda60bbcc7209b83ffdd76ea9a10e4 Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 1 Nov 2026 15:52:45 +0800 Subject: [PATCH] cli: magpie settings list|get|set|reset, through the window's own save (#4745) Stage 1 of #4745 (StringKe): every setting POST /api/settings saves can be read and set from the terminal. - internal/settingsapi holds the save the handler made: Merge (the carry of keys a page leaves out, moved verbatim from api.go, plus upstream's RouterNote line), the vision/imageGen/searcher checks, settings.Save's own checks, catalog.Touched. POST /api/settings and `magpie settings` both call settingsapi.Apply, so a value is checked and saved one way. It sits outside internal/gui so the nogui build has it. - `magpie settings` (list, the default, with value, default and choices; get; set; reset to settings.Defaults()), --json on list and get. Body sends the whole file with one key changed, so a key the save keeps when absent (noBird, refusalRetries, ...) is set even to off. A flag where a key or value goes, an unknown key (with near matches named) or a refused value writes nothing and exits 1; --help prints usage. - Parity guards: TestKeysAreWhatTheSaveWrites (each Settings field sent changed on its own; what the save takes must equal Keys), TestSettingsCLISetsWhatTheWindowSaves (every key the page's prefsKeep and savePrefs send is a key), TestEveryRouteHasACommandOrIsNamed (each /api route has a command or a reason in notYet, which later stages shrink; 36 have one now). - Item 3 of the stage (per-provider CLI-only fields in the window) is left for stage 2. - The open app's in-process follow-ups (fonts, Dock, tray menu, alerts, language, update re-check) run only from the window's save: #4752. Run (mote, at the pushed head 1c3591b5d + this): - gofmt -l; go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...; GOOS=linux go build -tags nogui; GOOS=windows go build: clean (before rebase, the vets again after). - go test internal/settingsapi, internal/settings, internal/cli: ok. internal/gui -run Settings|Prefs|Keep after the rebase: ok. The full internal/gui run before the rebase had three reds: TestSettingsSaveKeepsWhatItDoesNotSend (BusyLoad, fixed on main in b646a9127), TestColdTurnsTaken (fixed on main in 647323409) and TestMainWindowCorners/macOS_26_SDK (#3949, mote is macOS 27). - Real run in a sandbox HOME on mote with a magpie built from this: settings --help / help, list, get, set theme dark, noBird on, redactWords "acme, globex", usageAlert 85; refused theme neon, `them` (names theme), usageAlert lots, trayUsageEvery 4, vision nobody/nothing, each exit 1 with settings.json unchanged; set usageAlert --help printed usage and wrote nothing. Then `magpie web` with MAGPIE_WEB_KEY: GET /api/settings read back each value the CLI set; POST /api/settings lang ja, then `settings get lang` said ja; reset theme gave system. Broken by hand, each red, then put back: noBird dropped from Keys (TestKeys, TestBodySetsOneKeyOnly, the CLI set test and the GUI parity test red); Body dropping false values (TestBodySetsOneKeyOnly and the CLI "noBird off" check red); a route taken out of notYet and another renamed (TestEveryRouteHasACommandOrIsNamed red, 3 errors). On the old code the new tests don't compile (no settingsapi, no command). Not tried: a real run on Windows or Linux; the live app reacting to a CLI write while open (#4752); the GUI node suite (no page file changed). --- README.md | 1 + README.zh-CN.md | 1 + docs/reference.md | 6 + docs/subsystems/gui-shell.md | 1 + internal/cli/help_cli.go | 2 + internal/cli/main.go | 4 + internal/cli/settings_cli.go | 343 +++++++++++++++++ internal/cli/settings_cli_test.go | 149 ++++++++ internal/cli/settings_parity_test.go | 446 +++++++++++++++++++++++ internal/gui/api.go | 222 +---------- internal/settings/settings.go | 7 + internal/settingsapi/settingsapi.go | 360 ++++++++++++++++++ internal/settingsapi/settingsapi_test.go | 215 +++++++++++ 13 files changed, 1540 insertions(+), 217 deletions(-) create mode 100644 internal/cli/settings_cli.go create mode 100644 internal/cli/settings_cli_test.go create mode 100644 internal/cli/settings_parity_test.go create mode 100644 internal/settingsapi/settingsapi.go create mode 100644 internal/settingsapi/settingsapi_test.go diff --git a/README.md b/README.md index 070e78dbc..68a49af2d 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ magpie group add "Opus anywhere" models=claude/claude-opus-5-5,copilot/claude-op magpie claude group/opus-anywhere # fails over between subscriptions magpie save work && magpie use work # profiles magpie quota # what's left on every plan +magpie settings set theme dark # every Settings switch, from the terminal magpie tool generate_image "a magpie, watercolour" -o hero.png # magpie's image, vision and search tools, called directly magpie tui # the whole thing, in a terminal ``` diff --git a/README.zh-CN.md b/README.zh-CN.md index b83dc24fb..3a034b5ea 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -68,6 +68,7 @@ magpie group add "Opus anywhere" models=claude/claude-opus-5-5,copilot/claude-op magpie claude group/opus-anywhere # 在多个订阅间自动切换 magpie save work && magpie use work # 方案 magpie quota # 每个套餐还剩多少 +magpie settings set theme dark # 设置里的每一项,也能在终端改 magpie tool generate_image "一只喜鹊,水彩" -o hero.png # 直接调用 magpie 的生图、识图、搜索工具 magpie tui # 全部功能,在终端里 ``` diff --git a/docs/reference.md b/docs/reference.md index 0551d31fc..1d55be2b1 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -2979,6 +2979,12 @@ magpie rm work magpie sync # refresh the models.dev catalog and every live model list +magpie settings # every setting the window's Settings saves, its value and default (--json too) +magpie settings get usageAlert +magpie settings set noBird on # checked and saved as the window saves it +magpie settings set redactWords acme,globex +magpie settings reset theme # back to its default + magpie quota # what is left of every subscription, plan and key balance magpie quota refresh codex # read Codex's cards again now (once per 30s) magpie quota wait codex # block until a Codex account has allowance again diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 348b23a00..6549fe359 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -14,6 +14,7 @@ three. | Native host | `Run` starts the Wails v3 app: the tray icon, the panel, the main window, single-instance handover, `magpie://` import links and open at login. `host` implements `Windows` for the API: show and hide, open URLs and folders, copy to the clipboard, fit and tint the panel, and set the text size. A copy on Linux sets PRIMARY before CLIPBOARD, since GTK 3 serves CLIPBOARD empty when PRIMARY is set after it on a compositor with no primary selection (KDE Plasma with middle-click paste off, #1881); on Wayland the copy is read back through the compositor, and one that doesn't read back whole answers `/api/copy` with 501, so the page tries its clipboard API, then the copy command, then says the copy failed with the text to copy by hand (`copy-fallback.test.cjs`). | [`app.go`](../../internal/gui/app.go), [`clipboard_gtk3.go`](../../internal/gui/clipboard_gtk3.go), [`clipboard_gtk3.h`](../../internal/gui/clipboard_gtk3.h), [`mainwindow.go`](../../internal/gui/mainwindow.go), [`traymenu.go`](../../internal/gui/traymenu.go) | | Backend | `startBackend` starts the gateway this process serves, unless another magpie already serves it. In that case this process only shows the other one's status (`gw` is nil), and `watchGateway` looks at it again every 15 s (`gatewayWatch`). A magpie of another version there (`otherServes` in `gateway_older.go`) is told the page as `gatewayOther` in `/api/state` and said over the Agents list (`gatewaySkewLine` in `plugins/gateway/client.js`), in the panel and the window: pi got 404 for a model the newer app had written it while an older copy of the app kept the gateway, and only the Gateway page said so (matrix0487 on Discord). An older released copy of the app (`serves` app or tray, with a pid) is this app's own predecessor: once its `/v1/magpie/concurrency` says nothing is in flight (`gateway.ServedBusy`; unknown is never idle) the app quits it as the Gateway page's button does (`quitMagpieOnPort`, a magpie only) and serves the gateway, so no stream is cut; at most three times a run (`replaceMost`), and a quit that fails is left to the button. Any other (magpie serve or the service, `magpie web`, a TUI, a newer magpie, a build of its own) is left running, with what to do; a dev build of this magpie says nothing. A request that starts between the idle read and the quit gets the older app's short drain. See `TestAppReplacesItsOlderGatewayOnceIdle`, `TestGatewaySkewOfAnotherIsSaidNotQuit` and `gateway-skew.test.cjs`. `stopServing` drains requests in flight. A restart to update can hand the listening socket to the new version instead (see [A restart to update hands the gateway over](#a-restart-to-update-hands-the-gateway-over)). | [`backend.go`](../../internal/gui/backend.go), [`gateway_older.go`](../../internal/gui/gateway_older.go) | | API and assets | `Handler` serves `assets/` (embedded with `//go:embed assets`) and the `/api/*` routes, such as `/api/state`, `/api/set`, `/api/agents/{action}/{id}` and `/api/agents/restart/{id}` (a desktop app's Restart, after the row's confirm). `held` lets one API request's reads share one catalog build (`provider.Hold`), and drops it after any write. `revalidated` and `versionedPage` name each script by its content hash, so a cache never serves an old `app.js` under a new page; a file asked for under its current hash (`?v=`) is cached for good (`immutable`), anything else is revalidated by its ETag. | [`api.go`](../../internal/gui/api.go) | +| Settings from the terminal | `POST /api/settings` saves through `settingsapi.Apply` (`internal/settingsapi`, outside the GUI so the `nogui` build has it): the carry of keys a page leaves out (`Merge`), the vision, image and searcher checks, `settings.Save`'s own checks, and `catalog.Touched`. `magpie settings list\|get\|set\|reset` (#4745) builds the same body with `settingsapi.Body` (the whole file with one key changed, so a key the save keeps when it isn't sent is set even to off) and calls the same `Apply`; a refused value writes nothing. `settingsapi.Keys` names what the save writes; `TestKeysAreWhatTheSaveWrites` fails when a field of `settings.Settings` is saved without it, `TestSettingsCLISetsWhatTheWindowSaves` when a key the page's `savePrefs` sends isn't one, and `TestEveryRouteHasACommandOrIsNamed` when an `/api` route has neither a command nor a reason in `notYet` (`internal/cli/settings_parity_test.go`). The running app's in-process follow-ups (fonts, Dock, tray menu, alerts, language, update check) run only from the window's save; a change from the terminal is read from the file. | [`internal/settingsapi/settingsapi.go`](../../internal/settingsapi/settingsapi.go), [`settings_cli.go`](../../internal/cli/settings_cli.go) | | Browser mode | `StartWeb` serves the page and the gateway for `magpie web`. The browser signs in with a run key in a link. Added to a phone's home screen the page opens as an app of its own, with no browser bars (ninja_s6114 on Discord): `index.html` names `manifest.json` (display standalone), an apple-touch-icon and the iOS meta tags, the status bar keeps its own ground (`default`), and its theme colours match only `(display-mode: standalone)`, so a browser's tab and the app's windows take none. `webGuard` serves those three files (`webAppFiles`: the manifest, `icons/apple-touch-icon.png`, `icons/icon-512.png`) without the key, to GET and HEAD at those exact paths alone, as a home screen may ask without the cookie; see `TestWebAppAddsToHomeScreen` and `web-app-standalone.test.cjs`. Gateway mode shows Providers, Gateway, Routing, Usage, Sessions, Plugins and Settings on a machine that is only a gateway. `webHandler` gzips the page's text files and the API's JSON for a browser that takes gzip (`webCompressed`, with a `-gzip` ETag that still answers 304; never an event stream, which gzip would hold back until its buffer fills); the app's own windows read the page in-process and get it uncompressed. The page's port answers the gateway's client routes too (`onePort`, `gateway.ClientPath`: `/v1/…`, `/v1beta/…`, `/mcp/…`, the Codex backend path and the routes without `/v1`; never `/api/*` or `/_magpie/*`, never a path that isn't clean), so one reverse-proxy location serves the page and the agents (zgcwkj on Discord). They skip the page's key and gzip and go to the gateway's own guards, always as a request from another machine (`gateway.FromPagePort`, the `X-Magpie-Page-Port` mark: `local` is false for it, from loopback too and under `MAGPIE_TRUST_PROXY`, so magpie must be shared and the request carry an enabled gateway key), since a raw TCP forward or a proxy that adds no forwarding header reaches this port from loopback looking like an agent here (reported privately by Coffemon); agents here use the gateway's own port. `Server.Front` (lanGuard over Handler) serves them in process when this process serves the gateway, or `toGateway`, a reverse proxy to `gateway.URL()`, when another magpie does; it keeps the Host, the forwarding headers and the mark, adds X-Forwarded-For for a peer that isn't loopback, and the peer's loopback address as X-Forwarded-For when none came, so a gateway of an older magpie that doesn't know the mark still asks for a key. `lanGuard` moves the mark into the request's context and takes the header off, so it never goes upstream. The page itself calls no client route. See `TestWebOnePortServedHere`, `TestWebOnePortServedElsewhere`, `TestWebOnePortAgentsHereUseTheGatewayPort`, `TestPagePortMarkIsNeverLocal` and `TestClientPathCoversHandler`. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go), [`oneport.go`](../../internal/gateway/oneport.go) | | The app's page in a browser | Settings › Network and sharing › Browser access (`renderWebPage` in `plugins/gateway/settings.js`, drawn with the Web pages rows) has the app serve its own page to a browser while it runs, so a tunnel (Cloudflare Tunnel, SSH) or a computer on the network can reach it without `magpie web` kept running in a terminal (jiakun_zhao on X). Off, This computer (`127.0.0.1`, which a tunnel's service points at) or Local network (every address; a "Not encrypted" row without `--tls-cert`). It is `magpie web`'s page and guard, not a second kind: `startAppPage` (from `Run`, after `startBackend`) serves `webServed` over a `Handler` of its own, whose `Windows` is `appWebHost` (a browser tab for `isWeb`, but not `ownWeb`, so the app's windows aren't taken for `magpie web`'s: `webPage` and gateway mode stay the app's; quitting quits the app, and a restart to update from it brings back the windows the app has up, `restartFrom`). The key is always asked for: no mode serves without it. It lives with the mode and port in `web-page.json` beside settings.json (0600, never in settings.json, so sync and backup don't carry it), is made the first time the page is turned on, kept across restarts (a browser's cookie stays good), and replaced by New key, which turns away every browser signed in with the old one (the guard is swapped atomically, `appPage.cur`). A file that can't be read, or names no known mode, is off and says why; Settings rewrites it only given a whole choice. A port another program holds (`magpie web`; the magpie before a restart to update) is said and tried again every 4 s (`appPageRetry`); the port must be 1024 up and not the gateway's. `GET/POST /api/web-page` are on the app's own windows' API only, never a browser's, so a browser on the page can neither read the key it came in without nor turn the page off under itself. `magpie web` on the port the app serves prints the app's link and opens it rather than starting a second (`gui.AppPage`, `samePort`). Sessions are warmed once a process however many `Handler`s there are (`warmOnce`). See `TestAppPageServesOnlyWithItsKey`, `TestAppPageWaitsForABusyPort`, `TestAppPageUnreadFileServesNothing`, `TestAppPageTurnsDownBadChoices`, `TestAppPageBrowserIsATab` and `browser-access.test.cjs`. | [`apppage.go`](../../internal/gui/apppage.go), [`web_cli.go`](../../internal/cli/web_cli.go) | | The page | `app.js` keeps one state object per view and renders it into a list, with no framework. The views have their own files: `plugins.js` and `context.js`, and those a plugin adds under `assets/plugins//` (the Gateway, Sessions, Library, Routing and Usage pages, see [plugin runtime](plugin-runtime.md)) (Usage's Context tab, and the context window card the Routing page draws under a request's story, fed by `/api/context` in `context.go`, which scores and tags each agent; a client whose User-Agent names only an HTTP library, a runtime or an API SDK (`usage.IsLibrary`: curl, Bun, python-httpx, Go-http-client, OpenAI/Python), or nothing (`other`), is no agent and goes on one card, `scripts`, named Scripts with its libraries listed, read from each route's kept agent so older history folds too, while the Usage page's Agents list keeps each by its own name (theforeveriris on X, `context_scripts_test.go`, `context-scripts.test.cjs`); clicking a part, a cell or an item opens its text from `/api/context/text`, the last 10 requests' masked bodies in memory (`openCtxText`), rendered 100 items and 20000 characters at a time; its "Tuned for you" cards are fed by `/api/tune` in `tune.go`, see [agent wiring](agent-wiring.md)). Strings go through `t()` with translations in `i18n.js`, and a plugin's own in its `i18n.js` (zh, zh-TW, ja and de; the English text is the key and the fallback). zh-TW is Traditional Chinese with Taiwan's words; a system language of zh-TW, zh-HK, zh-MO or any zh-Hant picks it, and the tray menu and notifications follow (`trayLang`). Dropdowns use `openProtoMenu`. Every app menu (`openProtoMenu`, `openRowMenu`, `openSessCombo`) is placed by `placeMenu`: under its anchor, or over it when the window runs out below; one that fits neither way takes the larger room, its height held to it, and scrolls inside itself, and a scroll inside a menu doesn't close it (#1437, `removed-groups-menu-scroll.test.cjs`). The highest any popover goes is `popTop`: 8px under `header.top` on a Mac window, where the traffic lights are drawn over the page, and 8px from the top elsewhere; `placeMenu`, the field picker's `placePop` (which also holds `#pop`'s height to that room) and an agent's model list (`openAgentModels`) all use it (#1573, `popover-mac-chrome.test.cjs`). Scrolling is done only by `scrollOnPurpose(e)` with the reader's event. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/i18n.js`](../../internal/gui/assets/i18n.js) | diff --git a/internal/cli/help_cli.go b/internal/cli/help_cli.go index f815cde01..59a6463cf 100644 --- a/internal/cli/help_cli.go +++ b/internal/cli/help_cli.go @@ -78,6 +78,8 @@ func helpFor(args []string) string { return githubUsage case "claude-code": return claudeCodeUsage + case "settings": + return settingsUsage case "list": cmd = "ls" case "account": diff --git a/internal/cli/main.go b/internal/cli/main.go index 6b2698c6f..31abae908 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -153,6 +153,8 @@ const usage = `magpie — one place to pick every agent's model magpie statusline [] one line for Claude Code's status line: the session's model and each account's windows magpie sync refresh the model catalog and vendor model lists magpie agents list every supported agent + magpie settings [list|get |set |reset ] [--json] + every setting the window's Settings page saves, read and set as it saves them (magpie settings help) magpie update [check] [--proxy ] [--mirror ] install the newest release (check: only say if there is one); --proxy: an http(s):// or socks5:// proxy for it; --mirror: a GitHub download mirror put @@ -539,6 +541,8 @@ func run(args []string) error { return githubCmd(args[1:]) case "claude-code": return claudeCodeCmd(args[1:]) + case "settings": + return settingsCmd(args[1:]) } // the agent of a plugin that is gone (deleted on disk) is no agent diff --git a/internal/cli/settings_cli.go b/internal/cli/settings_cli.go new file mode 100644 index 000000000..60526cc1a --- /dev/null +++ b/internal/cli/settings_cli.go @@ -0,0 +1,343 @@ +package cli + +import ( + "bytes" + "encoding/json" + "fmt" + "os" + "reflect" + "strconv" + "strings" + + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/settingsapi" +) + +const settingsUsage = ` magpie settings [list] [--json] every setting the window's Settings saves: its value now and its default + magpie settings get [--json] one setting's value + magpie settings set set one, checked and saved as the window saves it + magpie settings reset one back to its default + + a value is on|off (or true|false) for a switch, a number, words, a list as a,b,c + (or a JSON array), and JSON for an object; a key with a closed set lists its choices. + Set while the app is open, a setting is read from the file as the app reads it; the + app's Dock, fonts and tray menu follow a change made here when it starts next. +` + +// settingsCmd is `magpie settings …` (#4745): the settings POST +// /api/settings saves, read and written through settingsapi, the same +// save the window's Settings makes. +func settingsCmd(args []string) error { + asJSON := false + var rest []string + for _, a := range args { + switch { + case a == "--json" || a == "-j": + asJSON = true + case strings.HasPrefix(a, "-") && !isNumber(a): + // a flag is never taken for a key or a value to write (#1457) + return fmt.Errorf("unknown flag %s: nothing was changed\n\n%s", a, settingsUsage) + default: + rest = append(rest, a) + } + } + if len(rest) == 0 { + rest = []string{"list"} + } + switch rest[0] { + case "list", "ls": + if len(rest) != 1 { + return fmt.Errorf("usage: magpie settings list [--json]") + } + return settingsList(asJSON) + case "get": + if len(rest) != 2 { + return fmt.Errorf("usage: magpie settings get [--json]") + } + return settingsGet(rest[1], asJSON) + case "set": + if len(rest) != 3 { + return fmt.Errorf("usage: magpie settings set : nothing was changed") + } + return settingsSet(rest[1], rest[2], false) + case "reset": + if len(rest) != 2 { + return fmt.Errorf("usage: magpie settings reset : nothing was changed") + } + return settingsSet(rest[1], "", true) + } + return fmt.Errorf("unknown settings command %q\n\n%s", rest[0], settingsUsage) +} + +func isNumber(s string) bool { + _, err := strconv.ParseFloat(s, 64) + return err == nil +} + +// settingRow is one setting as `magpie settings list --json` gives it. +type settingRow struct { + Key string `json:"key"` + Type string `json:"type"` + Value any `json:"value"` + Default any `json:"default"` + Choices []string `json:"choices,omitempty"` +} + +func settingRows() ([]settingRow, error) { + cur, err := settings.LoadChecked() + if err != nil { + return nil, err + } + def := settings.Defaults() + var rows []settingRow + for _, k := range settingsapi.Keys { + f, _ := settingsapi.Field(k) + v, _ := settingsapi.Value(cur, k) + d, _ := settingsapi.Value(def, k) + rows = append(rows, settingRow{Key: k, Type: typeWord(f.Type), Value: v, Default: d, Choices: settingsapi.Choices[k]}) + } + return rows, nil +} + +func settingsList(asJSON bool) error { + rows, err := settingRows() + if err != nil { + return err + } + if asJSON { + return printJSON(rows) + } + w := 0 + for _, r := range rows { + w = max(w, len(r.Key)) + } + for _, r := range rows { + v, d := shown(r.Value), shown(r.Default) + line := fmt.Sprintf("%-*s %s", w, r.Key, v) + note := r.Type + if len(r.Choices) > 0 { + note = strings.Join(r.Choices, "|") + } + if v != d { + note += ", default " + d + } + fmt.Println(line, muted.Render("("+note+")")) + } + return nil +} + +func settingsGet(key string, asJSON bool) error { + if err := knownSetting(key); err != nil { + return err + } + cur, err := settings.LoadChecked() + if err != nil { + return err + } + v, _ := settingsapi.Value(cur, key) + if asJSON { + return printJSON(v) + } + fmt.Println(shown(v)) + return nil +} + +// settingsSet saves key as text says, or as its default when reset, +// through settingsapi.Apply: every other setting stays as it is, and a +// value that doesn't check out writes nothing. +func settingsSet(key, text string, reset bool) error { + if err := knownSetting(key); err != nil { + return err + } + f, _ := settingsapi.Field(key) + var value json.RawMessage + if reset { + // the default as a new install has it; a list's as an empty one, + // which a list the save keeps when it is not sent (searcherThen) + // needs to be cleared + d, _ := settingsapi.Value(settings.Defaults(), key) + b, err := json.Marshal(d) + if err != nil { + return err + } + if string(b) == "null" && f.Type.Kind() == reflect.Slice { + b = []byte("[]") + } + value = b + } else { + v, err := settingValue(key, f.Type, text) + if err != nil { + return fmt.Errorf("%w: nothing was changed", err) + } + value = v + } + cur, err := settings.LoadChecked() + if err != nil { + return err + } + body, err := settingsapi.Body(cur, key, value) + if err != nil { + return err + } + if _, _, err := settingsapi.Apply(body, false); err != nil { + return fmt.Errorf("%w: nothing was changed", err) + } + // as saved, which the save may have put in its own form (06:00) + v, _ := settingsapi.Value(settings.Load(), key) + fmt.Println(green.Render("✓"), bold.Render(key), shown(v)) + return nil +} + +func knownSetting(key string) error { + if settingsapi.Known(key) { + return nil + } + var near []string + for _, k := range settingsapi.Keys { + if strings.Contains(strings.ToLower(k), strings.ToLower(key)) || strings.Contains(strings.ToLower(key), strings.ToLower(k)) { + near = append(near, k) + } + } + msg := fmt.Sprintf("no setting %q", key) + if len(near) > 0 { + msg += ": did you mean " + strings.Join(near, ", ") + "?" + } + return fmt.Errorf("%s (magpie settings list names them all): nothing was changed", msg) +} + +// settingValue is text as the JSON a setting of type t is saved as. +func settingValue(key string, t reflect.Type, text string) (json.RawMessage, error) { + text = strings.TrimSpace(text) + base := t + if base.Kind() == reflect.Pointer { + base = base.Elem() + } + var out any + switch base.Kind() { + case reflect.Bool: + switch strings.ToLower(text) { + case "on", "true", "yes", "1": + out = true + case "off", "false", "no", "0": + out = false + default: + return nil, fmt.Errorf("%s is on or off, not %q", key, text) + } + case reflect.Int, reflect.Int64, reflect.Int32: + n, err := strconv.Atoi(text) + if err != nil { + return nil, fmt.Errorf("%s is a whole number, not %q", key, text) + } + out = n + case reflect.Float64, reflect.Float32: + n, err := strconv.ParseFloat(text, 64) + if err != nil { + return nil, fmt.Errorf("%s is a number, not %q", key, text) + } + out = n + case reflect.String: + out = text + case reflect.Slice: + if base.Elem().Kind() == reflect.String && !strings.HasPrefix(text, "[") { + list := []string{} + for v := range strings.SplitSeq(text, ",") { + if v = strings.TrimSpace(v); v != "" { + list = append(list, v) + } + } + out = list + break + } + fallthrough + default: + // an object or a list of them: JSON, every field one it has + v := reflect.New(t) + dec := json.NewDecoder(strings.NewReader(text)) + dec.DisallowUnknownFields() + if err := dec.Decode(v.Interface()); err != nil { + return nil, fmt.Errorf("%s is JSON (%s): %v", key, typeWord(t), err) + } + if dec.More() { + return nil, fmt.Errorf("%s is one JSON value", key) + } + return json.RawMessage(text), nil + } + b, err := json.Marshal(out) + if err != nil { + return nil, err + } + // what it is decoded into checks it once more (an int's range) + if err := json.Unmarshal(b, reflect.New(t).Interface()); err != nil { + return nil, fmt.Errorf("%s: %v", key, err) + } + return b, nil +} + +// typeWord names t for the list: on|off, number, text, list or JSON. +func typeWord(t reflect.Type) string { + if t.Kind() == reflect.Pointer { + t = t.Elem() + } + switch t.Kind() { + case reflect.Bool: + return "on|off" + case reflect.Int, reflect.Int64, reflect.Int32, reflect.Float64, reflect.Float32: + return "number" + case reflect.String: + return "text" + case reflect.Slice: + if t.Elem().Kind() == reflect.String { + return "list" + } + } + return "JSON" +} + +// shown is a value as list and get print it: a switch on or off, words +// as they are, anything else as JSON. +func shown(v any) string { + rv := reflect.ValueOf(v) + if rv.Kind() == reflect.Pointer { + if rv.IsNil() { + return "-" + } + rv = rv.Elem() + } + switch rv.Kind() { + case reflect.Bool: + if rv.Bool() { + return "on" + } + return "off" + case reflect.String: + if rv.String() == "" { + return `""` + } + return rv.String() + case reflect.Slice: + if rv.Type().Elem().Kind() == reflect.String { + if rv.Len() == 0 { + return "[]" + } + return strings.Join(rv.Interface().([]string), ",") + } + case reflect.Map: + if rv.Len() == 0 { + return "{}" + } + } + var b bytes.Buffer + enc := json.NewEncoder(&b) + enc.SetEscapeHTML(false) + if err := enc.Encode(rv.Interface()); err != nil { + return fmt.Sprint(v) + } + return strings.TrimSpace(b.String()) +} + +func printJSON(v any) error { + enc := json.NewEncoder(os.Stdout) + enc.SetEscapeHTML(false) + enc.SetIndent("", " ") + return enc.Encode(v) +} diff --git a/internal/cli/settings_cli_test.go b/internal/cli/settings_cli_test.go new file mode 100644 index 000000000..053e99a7d --- /dev/null +++ b/internal/cli/settings_cli_test.go @@ -0,0 +1,149 @@ +package cli + +import ( + "encoding/json" + "os" + "strings" + "testing" + + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/settingsapi" +) + +// settingsHome is a home of its own whose settings.json has the user's +// own choices in it, and gives that file's bytes. +func settingsHome(t *testing.T) []byte { + t.Helper() + helpHome(t) + s := settings.Defaults() + s.Theme, s.NoBird, s.Currency, s.Proxy = "dark", true, "cny", "http://127.0.0.1:7890" + s.RedactWords = []string{"acme"} + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + b, err := os.ReadFile(settings.Path()) + if err != nil { + t.Fatal(err) + } + return b +} + +func TestSettingsSetGetReset(t *testing.T) { + settingsHome(t) + if _, err := runOut(t, "settings", "set", "lang", "ja"); err != nil { + t.Fatal(err) + } + if out, err := runOut(t, "settings", "get", "lang"); err != nil || strings.TrimSpace(out) != "ja" { + t.Fatalf("get lang = %q, %v", out, err) + } + s := settings.Load() + if s.Lang != "ja" || s.Theme != "dark" || !s.NoBird || s.Currency != "cny" || s.Proxy != "http://127.0.0.1:7890" || len(s.RedactWords) != 1 { + t.Fatalf("setting lang changed what the user set: %+v", s) + } + // a switch to off is sent, not left out as a zero value + if _, err := runOut(t, "settings", "set", "noBird", "off"); err != nil { + t.Fatal(err) + } + if settings.Load().NoBird { + t.Error("noBird off stayed on") + } + // numbers, lists, and a value the save puts in its own form + for _, c := range []struct{ key, value, want string }{ + {"usageAlert", "80", "80"}, + {"trayUsageEvery", "10", "10"}, + {"redactWords", "acme, globex", "acme,globex"}, + {"redactWords", `["a","b"]`, "a,b"}, + {"redactWords", "", "[]"}, + {"codexWarmup", "off", `""`}, + {"refusalRetries", "2", "2"}, + {"otel", `{"enabled":true,"endpoint":"http://127.0.0.1:4318"}`, ""}, + } { + if _, err := runOut(t, "settings", "set", c.key, c.value); err != nil { + t.Fatalf("set %s %q: %v", c.key, c.value, err) + } + out, _ := runOut(t, "settings", "get", c.key) + if c.want != "" && strings.TrimSpace(out) != c.want { + t.Errorf("set %s %q, then get = %q, want %q", c.key, c.value, out, c.want) + } + } + if _, err := runOut(t, "settings", "reset", "theme"); err != nil { + t.Fatal(err) + } + if s := settings.Load(); s.Theme != "system" || s.Currency != "cny" { + t.Errorf("reset theme: theme %q currency %q", s.Theme, s.Currency) + } + if _, err := runOut(t, "settings", "reset", "refusalRetries"); err != nil { + t.Fatal(err) + } + if s := settings.Load(); s.RefusalRetries != nil { + t.Errorf("reset refusalRetries left %d", *s.RefusalRetries) + } +} + +// A key or value that isn't one, and a flag where a value goes, write +// nothing and say why. +func TestSettingsRefusesAndWritesNothing(t *testing.T) { + before := settingsHome(t) + for _, args := range [][]string{ + {"settings", "set", "nope", "1"}, + {"settings", "set", "port", "9999"}, // a route of its own + {"settings", "set", "theme", "neon"}, // not one of its choices + {"settings", "set", "noBird", "maybe"}, + {"settings", "set", "usageAlert", "lots"}, + {"settings", "set", "usageAlert", "200"}, // the save's own range + {"settings", "set", "trayUsageEvery", "4"}, + {"settings", "set", "vision", "nobody/nothing"}, + {"settings", "set", "otel", `{"bogus":1}`}, + {"settings", "set", "theme", "--help-me"}, + {"settings", "set", "theme"}, + {"settings", "reset", "nope"}, + {"settings", "get", "nope"}, + {"settings", "frob"}, + } { + out, err := runOut(t, args...) + if err == nil { + t.Errorf("magpie %s: no error (%q)", strings.Join(args, " "), out) + } + after, _ := os.ReadFile(settings.Path()) + if string(after) != string(before) { + t.Fatalf("magpie %s changed settings.json", strings.Join(args, " ")) + } + } + _, err := runOut(t, "settings", "set", "them", "dark") + if err == nil || !strings.Contains(err.Error(), "theme") { + t.Errorf("a near miss doesn't name the key: %v", err) + } + // a negative number is a value, not a flag + _, err = runOut(t, "settings", "set", "usageAlert", "-1") + if err == nil || strings.Contains(err.Error(), "flag") { + t.Errorf("-1 read as a flag or saved: %v", err) + } +} + +func TestSettingsListAndJSON(t *testing.T) { + settingsHome(t) + out, err := runOut(t, "settings", "list", "--json") + if err != nil { + t.Fatal(err) + } + var rows []settingRow + if err := json.Unmarshal([]byte(out), &rows); err != nil { + t.Fatalf("list --json: %v\n%s", err, out) + } + if len(rows) != len(settingsapi.Keys) { + t.Fatalf("list --json has %d rows, Keys %d", len(rows), len(settingsapi.Keys)) + } + for _, r := range rows { + if r.Key == "theme" && (r.Value != "dark" || r.Default != "system") { + t.Errorf("theme row: %+v", r) + } + } + out, err = runOut(t, "settings") + if err != nil || !strings.Contains(out, "theme") || !strings.Contains(out, "default system") { + t.Errorf("settings list: %v\n%s", err, out) + } + out, err = runOut(t, "settings", "get", "redactWords", "--json") + if err != nil || strings.TrimSpace(strings.Join(strings.Fields(out), "")) != `["acme"]` { + t.Errorf("get redactWords --json = %q, %v", out, err) + } +} diff --git a/internal/cli/settings_parity_test.go b/internal/cli/settings_parity_test.go new file mode 100644 index 000000000..948c7765c --- /dev/null +++ b/internal/cli/settings_parity_test.go @@ -0,0 +1,446 @@ +package cli + +import ( + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "testing" + + "github.com/yetone/magpie/internal/settingsapi" +) + +// The window and the CLI do the same things (#4745). These tests hold the +// two together: every setting the Settings page saves is one `magpie +// settings` sets, and every /api route the window's pages call has a +// command, or is named below as not having one yet, with why. A route or a +// setting added on one side only fails here. + +// guiSettingsKeys are the keys the window's pages send POST /api/settings: +// prefsKeep's (what every save sends) and each savePrefs({ ...keep, k: … }) +// call's own, in app.js and the built-in plugins' pages. +func guiSettingsKeys(t *testing.T) []string { + t.Helper() + assets := filepath.Join("..", "gui", "assets") + key := regexp.MustCompile(`[{,]\s*([A-Za-z_]\w*)\s*[:,}]`) + var keys []string + add := func(src string) { + for _, m := range key.FindAllStringSubmatch(src, -1) { + keys = append(keys, m[1]) + } + } + err := filepath.WalkDir(assets, func(p string, d os.DirEntry, err error) error { + if err != nil || d.IsDir() || !strings.HasSuffix(p, ".js") || strings.Contains(p, "vendor") { + return err + } + b, err := os.ReadFile(p) + if err != nil { + return err + } + src := string(b) + if i := strings.Index(src, "function prefsKeep(s) {"); i >= 0 { + body := src[i:] + body = body[strings.Index(body, "return {")+len("return"):] + add(body[:balanced(body)]) + } + for rest := src; ; { + i := strings.Index(rest, "savePrefs({") + if i < 0 { + break + } + rest = rest[i+len("savePrefs("):] + add(rest[:balanced(rest)]) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + slices.Sort(keys) + keys = slices.Compact(keys) + if len(keys) < 60 { + t.Fatalf("read %d keys from the pages' saves: %v", len(keys), keys) + } + return keys +} + +// balanced is how far the {…} that src starts with goes. +func balanced(src string) int { + depth := 0 + for i, c := range src { + switch c { + case '{', '(', '[': + depth++ + case '}', ')', ']': + depth-- + if depth == 0 { + return i + 1 + } + } + } + return len(src) +} + +// Every key the pages send POST /api/settings is one `magpie settings` +// sets, and every one it sets is one the pages send. +func TestSettingsCLISetsWhatTheWindowSaves(t *testing.T) { + gui := guiSettingsKeys(t) + // spread into a save's body, not keys of it + notKeys := []string{"keep", "change"} + for _, k := range gui { + if !slices.Contains(notKeys, k) && !settingsapi.Known(k) { + t.Errorf("the window saves %q, which `magpie settings` can't set: add it to settingsapi.Keys", k) + } + } + for _, k := range settingsapi.Keys { + if !slices.Contains(gui, k) { + t.Errorf("`magpie settings` sets %q, which no page sends", k) + } + } +} + +// What a route without a command is waiting for. Later stages of #4745 +// take routes out of notYet into cliForRoute. +const ( + // W: the window's own, with nothing to do in a terminal: its size, + // icons and fonts, opening a folder, what's new, arranging a list by + // dragging, the pages' own data + W = "the window's own" + // S2: a setting with a route of its own (its own checks and + // side effects), stage 2 + S2 = "stage 2: a setting saved by its own route" + // P: providers, accounts, sign-ins and plugins past what the + // provider, accounts and plugin commands do, stage 2 + P = "stage 2: providers, accounts and sign-ins" + // L: the library past `magpie library`, stage 3 + L = "stage 3: the library" + // U: usage, sessions, masking records and traces past `magpie + // usage`, `quota` and `sessions`, stage 3 + U = "stage 3: usage, sessions and traces" + // A: connecting agents and the rest, stage 3 + A = "stage 3: agents and the rest" +) + +// cliForRoute is the command that does what a route does, as `magpie …`. +var cliForRoute = map[string]string{ + "GET /api/agent-models/{id}": "magpie models", + "GET /api/settings": "magpie settings list", + "POST /api/settings": "magpie settings set", + "POST /api/settings/account-discovery": "magpie accounts discovery", + "POST /api/settings/search-api": "magpie search", + "POST /api/settings/search-key": "magpie search", + "POST /api/settings/update-mirror": "magpie update mirror", + "POST /api/sync": "magpie sync", + "GET /api/davsync": "magpie webdav", + "POST /api/backup/export": "magpie backup", + "POST /api/backup/import": "magpie restore", + "POST /api/davsync/{action}": "magpie webdav", + "GET /api/caller-keys": "magpie gateway-key list", + "POST /api/caller-keys/{action}": "magpie gateway-key", + "GET /api/groups": "magpie groups", + "POST /api/groups/{action}": "magpie group", + "GET /api/import/{id}": "magpie import", + "GET /api/library": "magpie library", + "POST /api/library/{what}/{action}": "magpie library", + "GET /api/plugins": "magpie plugin", + "POST /api/plugins/{op}": "magpie plugin", + "GET /api/login/usage": "magpie quota", + "GET /api/providers": "magpie providers", + "POST /api/provider/{action}": "magpie provider", + "GET /api/sessions/reads": "magpie sessions read", + "POST /api/sessions/reads": "magpie sessions read", + "GET /api/sessions": "magpie sessions", + "POST /api/uninstall": "magpie uninstall", + "GET /api/usage": "magpie usage", + "GET /api/usage/quotas": "magpie quota", + "GET /api/usage/quotas/history": "magpie quota history", + "GET /api/usage/requests.csv": "magpie usage --csv", + "POST /api/usage/workbuddy-checkin": "magpie accounts checkin", + "GET /api/update": "magpie update check", + "POST /api/update/check": "magpie update check", + "POST /api/update/install": "magpie update", +} + +var notYet = map[string]string{ + "POST /api/agent-fast": A, // agent_models.go + "POST /api/agent-models/{id}": A, // agent_models.go + "GET /api/agents/cli": A, // api.go + "GET /api/agents/install": A, // api.go + "GET /api/agents/preview/{id}": A, // api.go + "GET /api/cli": A, // api.go + "GET /api/drift": A, // api.go + "GET /api/notices": W, // api.go + "GET /api/omarchy": W, // api.go + "GET /api/state": W, // api.go + "POST /api/agents/{action}/{id}": A, // api.go + "POST /api/agents/arrange": W, // api.go + "POST /api/agents/cli/{id}": A, // api.go + "POST /api/agents/disconnect-offline/{id}": A, // api.go + "POST /api/agents/rescan": A, // api.go + "POST /api/agents/restart/{id}": A, // api.go + "POST /api/agents/stage/{id}": A, // api.go + "POST /api/cli": A, // api.go + "POST /api/cli-behind/quiet": W, // api.go + "POST /api/gateway/held/reveal": W, // api.go + "POST /api/profile/{action}": A, // api.go + "POST /api/proxy/check": S2, // api.go + "POST /api/set": S2, // api.go + "POST /api/settings/allowips": S2, // api.go + "POST /api/settings/bare-ids": S2, // api.go + "POST /api/settings/busy-load": S2, // api.go + "POST /api/settings/checkin-account": S2, // api.go + "POST /api/settings/codex-agents-v1": S2, // api.go + "POST /api/settings/codex-async-compact": S2, // api.go + "POST /api/settings/codex-auto-reset": S2, // api.go + "POST /api/settings/codex-auto-review": S2, // api.go + "POST /api/settings/codex-compact-held/drop": S2, // api.go + "POST /api/settings/codex-credits": S2, // api.go + "POST /api/settings/codex-descriptions": S2, // api.go + "POST /api/settings/codex-predictions": S2, // api.go + "POST /api/settings/codex-reset-lead": S2, // api.go + "POST /api/settings/codex-titles": S2, // api.go + "POST /api/settings/codex-warm-at": S2, // api.go + "POST /api/settings/cors": S2, // api.go + "POST /api/settings/desktop-longest": S2, // api.go + "POST /api/settings/disabled-models": S2, // api.go + "POST /api/settings/full-context": S2, // api.go + "POST /api/settings/github-token": S2, // api.go + "POST /api/settings/guide": W, // api.go + "POST /api/settings/lan": S2, // api.go + "POST /api/settings/log/reveal": W, // api.go + "POST /api/settings/login": S2, // api.go + "POST /api/settings/minimax-checkin": S2, // api.go + "POST /api/settings/panel-shortcut": W, // api.go + "POST /api/settings/plain-names": S2, // api.go + "POST /api/settings/plugin-checkin": S2, // api.go + "POST /api/settings/plugin-option": S2, // api.go + "POST /api/settings/port": S2, // api.go + "POST /api/settings/qoder-checkin": S2, // api.go + "POST /api/settings/quota-left": S2, // api.go + "POST /api/settings/quota-reads": S2, // api.go + "POST /api/settings/redact-actions": S2, // api.go + "POST /api/settings/redact-allow": S2, // api.go + "POST /api/settings/redact-route": S2, // api.go + "POST /api/settings/redact-rule": S2, // api.go + "POST /api/settings/redact-rules": S2, // api.go + "POST /api/settings/reveal": W, // api.go + "POST /api/settings/search-all": S2, // api.go + "POST /api/settings/search-quota": S2, // api.go + "POST /api/settings/text-size": W, // api.go + "POST /api/settings/trae-checkin": S2, // api.go + "POST /api/settings/update-skip": S2, // api.go + "POST /api/settings/workbuddy-checkin": S2, // api.go + "POST /api/usage/arrange": W, // api.go + "POST /api/warm-now": A, // api.go + "POST /api/window/{action}": W, // api.go + "GET /api/archive": S2, // archive.go + "GET /api/archive/file": S2, // archive.go + "POST /api/archive/export": S2, // archive.go + "POST /api/settings/archive": S2, // archive.go + "GET /api/web-page": W, // apppage.go + "POST /api/web-page": W, // apppage.go + "GET /api/plugins/builtin": P, // builtins.go + "POST /api/plugins/builtin": P, // builtins.go + "GET /api/library/browser": L, // browser.go + "POST /api/library/browser/setup": L, // browser.go + "GET /api/caller-keys/models": P, // caller_keys.go + "POST /api/config/repair": A, // config_repair.go + "GET /api/context": U, // context.go + "GET /api/context/text": W, // context.go + "GET /api/dev/wait": W, // dev_on.go + "POST /api/dev/import": W, // dev_on.go + "GET /api/fonts": W, // fonts.go + "POST /api/settings/gateway-mode": S2, // gatewaymode.go + "POST /api/gateway/restart": A, // gateway_takeover.go + "POST /api/gateway/take-over": A, // gateway_takeover.go + "GET /api/importapps": P, // importapps.go + "GET /api/importapps/discovery": P, // importapps.go + "POST /api/importapps": P, // importapps.go + "POST /api/import/icon": W, // importlink.go + "POST /api/local-hosts": S2, // localhosts.go + "GET /api/masking/record": U, // masking.go + "GET /api/masking/records": U, // masking.go + "GET /api/masking/sent": U, // masking.go + "GET /api/masking/summary": U, // masking.go + "GET /api/masking/value": U, // masking.go + "POST /api/masking/clear": U, // masking.go + "POST /api/masking/preview": U, // masking.go + "POST /api/masking/values": U, // masking.go + "GET /api/library/icon": W, // library.go + "GET /api/library/market/servers": L, // library.go + "GET /api/library/market/skills": L, // library.go + "GET /api/library/mcp-signin/{id}": L, // library.go + "GET /api/library/rtk": L, // library.go + "GET /api/library/skill": L, // library.go + "POST /api/library/market/about": L, // library.go + "POST /api/library/mcp-signin": L, // library.go + "POST /api/library/mcp-signin/{id}/cancel": L, // library.go + "POST /api/library/mcp-signout": L, // library.go + "POST /api/library/mcp/check": L, // library.go + "POST /api/library/mcp/config": L, // library.go + "POST /api/library/projects/choose": W, // library.go + "POST /api/library/reveal": W, // library.go + "POST /api/library/rtk": L, // library.go + "POST /api/library/rtk/install": L, // library.go + "POST /api/library/rtk/path": L, // library.go + "POST /api/library/rtk/upgrade": L, // library.go + "POST /api/library/skills/check": L, // library.go + "POST /api/library/skills/probe": L, // library.go + "POST /api/library/skills/regroup": W, // library.go + "GET /api/omarchy/widget": W, // omarchy.go + "POST /api/omarchy/widget": W, // omarchy.go + "GET /api/plugin-pages": W, // pluginpage.go + "GET /api/plugin-panels": W, // pluginpage.go + "POST /api/plugin-pages/options": W, // pluginpage.go + "POST /api/plugin-pages/read": W, // pluginpage.go + "GET /api/plugins/agents": P, // plugins.go + "GET /api/plugins/git": P, // plugins.go + "GET /api/plugins/github": P, // plugins.go + "GET /api/plugins/listings": P, // plugins.go + "GET /api/plugins/market": P, // plugins.go + "GET /api/plugins/npm": P, // plugins.go + "GET /api/plugins/page": P, // plugins.go + "GET /api/plugins/search": P, // plugins.go + "GET /api/plugins/updates": P, // plugins.go + "POST /api/plugin-signin": P, // plugins.go + "POST /api/plugin-signin/prompt": P, // plugins.go + "POST /api/plugins/check": P, // plugins.go + "POST /api/plugins/choose": W, // plugins.go + "POST /api/plugins/mirror": P, // plugins.go + "POST /api/plugins/registry": P, // plugins.go + "GET /api/privacy-model": S2, // privacymodel.go + "POST /api/privacy-model": S2, // privacymodel.go + "GET /api/claude/mode": P, // providers.go + "GET /api/gateway/call": P, // providers.go + "GET /api/icons/{name}": W, // providers.go + "GET /api/lanes": P, // providers.go + "GET /api/signin/{id}": P, // providers.go + "GET /api/upstream": P, // providers.go + "POST /api/codex/app/reopen": W, // providers.go + "POST /api/codex/daemon/{action}": P, // providers.go + "POST /api/copy": W, // providers.go + "POST /api/icons": W, // providers.go + "POST /api/icons/favicon": W, // providers.go + "POST /api/icons/url": W, // providers.go + "POST /api/keys/{action}": P, // providers.go + "POST /api/login/{action}": P, // providers.go + "POST /api/open": W, // providers.go + "POST /api/partner": P, // providers.go + "POST /api/providers/arrange": W, // providers.go + "POST /api/signin": P, // providers.go + "POST /api/signin/{id}/callback": P, // providers.go + "POST /api/signin/{id}/cancel": P, // providers.go + "POST /api/signin/claude-token": P, // providers.go + "POST /api/signin/import": P, // providers.go + "POST /api/stepfun/{id}/session": P, // providers.go + "POST /api/stepfun/{id}/signout": P, // providers.go + "GET /api/sessions/manage": U, // sessions_manage.go + "GET /api/sessions/search": U, // sessions_manage.go + "POST /api/sessions/codex-provider": U, // sessions_manage.go + "POST /api/sessions/delete": U, // sessions_manage.go + "POST /api/sessions/purge": U, // sessions_manage.go + "POST /api/sessions/recording": U, // sessions_manage.go + "POST /api/sessions/relocate-claude": U, // sessions_manage.go + "POST /api/sessions/restore": U, // sessions_manage.go + "GET /api/sessions/markdown": U, // sessions.go + "GET /api/sessions/one": U, // sessions.go + "GET /api/sessions/overview": U, // sessions.go + "GET /api/sessions/progress": U, // sessions.go + "GET /api/sessions/stats": U, // sessions.go + "GET /api/sessions/transcript": U, // sessions.go + "POST /api/agents/open": W, // sessions.go + "POST /api/sessions/carry": U, // sessions.go + "POST /api/sessions/export": U, // sessions.go + "POST /api/sessions/terminal": W, // sessions.go + "GET /api/model-speeds": U, // speeds.go + "GET /api/gateway/held/{name}": U, // trace.go + "GET /api/gateway/history": U, // trace.go + "GET /api/gateway/route": U, // trace.go + "GET /api/gateway/trace": U, // trace.go + "POST /api/gateway/session-titles": U, // trace.go + "POST /api/gateway/unrest": U, // trace.go + "GET /api/tune": U, // tune.go + "POST /api/tune/apply": U, // tune.go + "POST /api/tune/undo": U, // tune.go + "POST /api/uninstall/finish": A, // uninstall.go + "GET /api/usage/deleted/into": U, // usage.go + "GET /api/usage/heatmap": U, // usage.go + "GET /api/usage/quotas/history/holds": U, // usage.go + "GET /api/usage/requests": U, // usage.go + "GET /api/usage/requests/content": U, // usage.go + "POST /api/usage/clear": U, // usage.go + "POST /api/usage/codex-reset": U, // usage.go + "POST /api/usage/deleted": U, // usage.go + "POST /api/usage/minimax-checkin": U, // usage.go + "POST /api/usage/plugin-checkin": U, // usage.go + "POST /api/usage/qoder-checkin": U, // usage.go + "POST /api/usage/quotas/refresh": U, // usage.go + "POST /api/usage/requests/export": U, // usage.go + "POST /api/usage/trae-checkin": U, // usage.go + "GET /api/update/notes": W, // update.go + "GET /api/whatsnew": W, // whatsnew.go + "POST /api/whatsnew/seen": W, // whatsnew.go + "POST /api/whatsnew/today": W, // whatsnew.go +} + +// guiRoutes are the /api routes internal/gui serves, as "METHOD /path". +func guiRoutes(t *testing.T) []string { + t.Helper() + files, err := filepath.Glob(filepath.Join("..", "gui", "*.go")) + if err != nil { + t.Fatal(err) + } + re := regexp.MustCompile(`HandleFunc\("([A-Z]+ /api/[^"]*)"`) + var routes []string + for _, f := range files { + if strings.HasSuffix(f, "_test.go") { + continue + } + b, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + for _, m := range re.FindAllStringSubmatch(string(b), -1) { + routes = append(routes, m[1]) + } + } + slices.Sort(routes) + routes = slices.Compact(routes) + if len(routes) < 200 { + t.Fatalf("read %d routes from internal/gui", len(routes)) + } + return routes +} + +// Every route the window serves has a command, or is named in notYet; +// none is in both, and neither names a route that's gone. Every command +// named is one magpie has. +func TestEveryRouteHasACommandOrIsNamed(t *testing.T) { + routes := guiRoutes(t) + cmds := runCommands(t) + for _, r := range routes { + cmd, has := cliForRoute[r] + _, later := notYet[r] + switch { + case has && later: + t.Errorf("%s has a command (%s) and is in notYet: take it out of notYet", r, cmd) + case !has && !later: + t.Errorf("%s has no command: name the one that does what it does in cliForRoute, or say why there's none yet in notYet", r) + } + } + for r, cmd := range cliForRoute { + if !slices.Contains(routes, r) { + t.Errorf("cliForRoute names %s, which internal/gui doesn't serve", r) + } + f := strings.Fields(cmd) + if len(f) < 2 || f[0] != "magpie" || !slices.Contains(cmds, f[1]) { + t.Errorf("%s: %q isn't a magpie command", r, cmd) + } + } + for r := range notYet { + if !slices.Contains(routes, r) { + t.Errorf("notYet names %s, which internal/gui doesn't serve", r) + } + } +} diff --git a/internal/gui/api.go b/internal/gui/api.go index 10bd9fae3..2373d13c8 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -53,6 +53,7 @@ import ( "github.com/yetone/magpie/internal/redact" "github.com/yetone/magpie/internal/sessions" "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/settingsapi" "github.com/yetone/magpie/internal/update" "github.com/yetone/magpie/internal/usage" ) @@ -1361,233 +1362,20 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { writeJSON(rw, settingsState()) }) mux.HandleFunc("POST /api/settings", func(rw http.ResponseWriter, r *http.Request) { - var body json.RawMessage - var in settings.Settings - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - fail(rw, err) - return - } - if err := json.Unmarshal(body, &in); err != nil { - fail(rw, err) - return - } - // the Settings page sends its own choices; how the agents are - // arranged is the Agents page's, and the window's size its own; both stay as they are. - // Unreadable settings are never carried as the defaults (an empty - // allow list, every address let in): Save would refuse them too. - cur, err := settings.LoadChecked() + // read, checked and saved as `magpie settings set` saves (#4745) + body, err := io.ReadAll(r.Body) if err != nil { fail(rw, err) return } - var fields map[string]json.RawMessage - _ = json.Unmarshal(body, &fields) - // Older pages do not send fonts. An explicit null restores the - // default, while an omitted field (or a browser save) preserves it. - if _, sent := fields["uiFont"]; !sent || isWeb(w) { - in.UIFont = cur.UIFont - } - if _, sent := fields["codeFont"]; !sent || isWeb(w) { - in.CodeFont = cur.CodeFont - } - // and pages from before it do not send how often a refusal is asked - // again, which null sets back to every one left - if _, sent := fields["refusalRetries"]; !sent { - in.RefusalRetries = cur.RefusalRetries - } - // nor whether updates download by themselves (#2296) - if _, sent := fields["noAutoDownload"]; !sent { - in.NoAutoDownload = cur.NoAutoDownload - } - // nor the update channel (ssharpcc on X) - if _, sent := fields["updateChannel"]; !sent { - in.UpdateChannel = cur.UpdateChannel - } - // nor whether the masked words match in any case - if _, sent := fields["redactWordsAnyCase"]; !sent { - in.RedactWordsAnyCase = cur.RedactWordsAnyCase - } - // nor whether they match only as whole words - if _, sent := fields["redactWordsWhole"]; !sent { - in.RedactWordsWhole = cur.RedactWordsWhole - } - // nor whether a key goes as a made-up one of its form - if _, sent := fields["redactShape"]; !sent { - in.RedactShape = cur.RedactShape - } - // nor how long an image is given to be drawn - if _, sent := fields["imageTimeout"]; !sent { - in.ImageTimeout = cur.ImageTimeout - } - // nor how long a routing group's classifier is given (#2934) - if _, sent := fields["classifyTimeout"]; !sent { - in.ClassifyTimeout = cur.ClassifyTimeout - } - // nor whether animations are stilled (#3813) - if _, sent := fields["reduceMotion"]; !sent { - in.ReduceMotion = cur.ReduceMotion - } - // nor whether the loading bird is kept off - if _, sent := fields["noBird"]; !sent { - in.NoBird = cur.NoBird - } - // nor whether a value masked for the first time is told (Must2333) - if _, sent := fields["maskAlert"]; !sent { - in.MaskAlert = cur.MaskAlert - } - in.AgentOrder, in.AgentsHidden, in.AgentsShown = cur.AgentOrder, cur.AgentsHidden, cur.AgentsShown - in.Window, in.WindowMaximised, in.WindowAt = cur.Window, cur.WindowMaximised, cur.WindowAt // the window's own, as it was last resized and moved - // and what other pages keep here: which models an agent is shown, and - // everything the user said of a model anywhere else in the app, set on - // its own. The per-model maps are carried whole rather than named one - // by one, so a map added later is not silently dropped here. - // - // HiddenModels, PickedModels and OrderedModels are the other way - // round — keyed by agent, not by "/" — so they are - // not among them, and belong to the Agents page. - in.Visible, in.HiddenModels, in.OrderedModels = cur.Visible, cur.HiddenModels, cur.OrderedModels - in.PickedModels = cur.PickedModels // "only models I pick" (#1337) - in.OwnModelsHidden = cur.OwnModelsHidden // an agent's own models left out (#1642) - in.FastPicks = cur.FastPicks // switched in the agents' pickers (#954) - in.UltraPicks = cur.UltraPicks // and sent Ultrafast (#1954) - in.AgentEfforts = cur.AgentEfforts // picked in an agent's row (#1003) - in.PluginCheckins = cur.PluginCheckins // set on its own (plugin-checkin below) - in.PluginOptions = cur.PluginOptions // set on its own (plugin-option below) - in.CheckinOff = cur.CheckinOff // set on its own (checkin-account below) - settings.CarryPerModel(&in, &cur) - in.LAN, in.LANKey = cur.LAN, cur.LANKey - in.LANKeyID = cur.LANKeyID - in.Port = cur.Port // set on its own (port below), which moves the gateway - in.CORSOrigins = cur.CORSOrigins // set on its own (cors below) - in.AllowIPs = cur.AllowIPs // set on its own (allowips below) - in.FetchPrivate = cur.FetchPrivate // in settings.json only - in.RouterNote = cur.RouterNote // set on its own (the Library's servers/hub-note) - in.GitHubToken = cur.GitHubToken // set on its own (github-token below), never sent to the page - in.ProxyCustom = cur.ProxyCustom // set by settings.Save from the proxy, never by the page - in.RequestArchive = cur.RequestArchive // the Gateway page's, set on its own - in.RequestArchiveMaxMB = cur.RequestArchiveMaxMB // in settings.json only - in.ClaudeRunsMost = cur.ClaudeRunsMost // magpie claude-code runs, or settings.json (#2956) - in.GatewayConversations = cur.GatewayConversations // Sessions' explicit recording consent - in.RedactRules = cur.RedactRules // the masking rules, set on their own - in.RedactModel = cur.RedactModel // set on its own (privacy-model) - in.RedactModelName = cur.RedactModelName // set on its own (privacy-model) - in.RedactModelScore = cur.RedactModelScore // set on its own (privacy-model) - in.RedactModelOff = cur.RedactModelOff // set on its own (privacy-model) - in.RedactModelAuto = cur.RedactModelAuto // set on its own (masking) - in.RedactActions = cur.RedactActions // set on their own (redact-actions below) - in.RedactAllow = cur.RedactAllow // set on its own (redact-allow below) - in.DisabledModels = cur.DisabledModels // set on their own (disabled-models below, #1867) - // the request archive on this computer: the archive's switch while no - // S3 bucket, and its size in settings.json only - in.RequestArchiveLocal, in.RequestArchiveLocalMB = cur.RequestArchiveLocal, cur.RequestArchiveLocalMB - // used or left is the Usage page's toggle as much as Settings', set on its own - in.QuotaLeft = cur.QuotaLeft - in.QuotaReads = cur.QuotaReads // set on its own (quota-reads below) - in.SearchAll = cur.SearchAll // set on its own (search-all below) - in.UsageOrder = cur.UsageOrder // the Usage page's, dragged there - // and what the tray panel's Allowances tab leaves out, set there - in.PanelUsageHidden = cur.PanelUsageHidden - // and the clients the Usage page's Agents list leaves out, set there - in.UsageAgentsHidden = cur.UsageAgentsHidden - // and the allowance cards the Usage page's Overview leaves out, set there - in.UsageCardsHidden = cur.UsageCardsHidden - // and the names models' usage is counted under (magpie model alias) - in.UsageAliases = cur.UsageAliases - // and the clears of usage made on the Usage page - in.UsageCleared = cur.UsageCleared - // and the clients it counts as agents, set there too (#1958) - in.ClientAgents = cur.ClientAgents - // how agents' lists name models, set on its own for the agents to be told - in.PlainNames, in.PlainOwnNames = cur.PlainNames, cur.PlainOwnNames - in.BareModelIDs = cur.BareModelIDs // set on its own (bare-ids below) - in.BusyLoad = cur.BusyLoad // and so is this (busy-load below) - in.CodexAgentsV1 = cur.CodexAgentsV1 - in.FullContext = cur.FullContext // set on its own (full-context below) - in.CompactAt = cur.CompactAt // and so is the threshold - // Codex's background compaction, set on its own (codex-async-compact below) - in.CodexAsyncCompact, in.CodexAsyncCompactPercent = cur.CodexAsyncCompact, cur.CodexAsyncCompactPercent - // Claude Desktop's list, set in its row on the Agents page - in.DesktopLongest = cur.DesktopLongest - // and the Get started card put away, from the card itself - in.GuideHidden = cur.GuideHidden - - in.CodexTitles = cur.CodexTitles // set on its own (codex-titles below) - in.CodexDescriptions = cur.CodexDescriptions // set on its own (codex-descriptions below) - in.CodexPredictions = cur.CodexPredictions // and codex-predictions - // and so is the model Codex's auto-review runs on (codex-auto-review) - in.CodexAutoReview = cur.CodexAutoReview - // and the models Codex's and Desktop's subagents are put on, set - // in their Agents rows - in.CodexSubagentModel = cur.CodexSubagentModel - in.DesktopSubagentModel = cur.DesktopSubagentModel - // and the model for requests masking would change (redact-route) - in.RedactRouteTo = cur.RedactRouteTo - in.DesktopSubagentEffort = cur.DesktopSubagentEffort - in.ChinaMirror = cur.ChinaMirror // the Plugins page's, set on its own - in.NPMRegistry = cur.NPMRegistry // and its npm registry - // which Codex accounts spend a reset by themselves, set on the Usage card - in.CodexAutoReset = cur.CodexAutoReset - in.CodexAutoResetOnly = cur.CodexAutoResetOnly // and at which of the two times - in.CodexResetLead = cur.CodexResetLead // and how early before one expires (codex-reset-lead) - // and which of them spend their credits, set there too - in.CodexNoCredits = cur.CodexNoCredits - in.CodexCreditsLast = cur.CodexCreditsLast // and which only after everything else - // and each Codex account's own daily warm-up (codex-warm-at below) - in.CodexWarmAtOf = cur.CodexWarmAtOf - // and the text size, which the keyboard changes too (text-size below) - in.TextSize = cur.TextSize - // and the quick panel's shortcut, set on its own (panel-shortcut below) - in.PanelShortcut = cur.PanelShortcut - // the Dock choice's reading, which the page never sets: the file's - // as read (settings.DockSettled), so a save from the page doesn't - // read its With window as an older file's Hide - in.DockSettled = cur.DockSettled - // the version the Update pill was hidden for, set from the pill - in.UpdateSkip = cur.UpdateSkip - // the GitHub mirror updates come through, set by magpie update mirror - in.UpdateMirror = cur.UpdateMirror - // gateway mode, set on its own (gateway-mode) - in.GatewayMode = cur.GatewayMode - in.NoAccountDiscovery = cur.NoAccountDiscovery // set on its own (account-discovery below, or the CLI) - if v := strings.TrimSpace(in.Vision); v != "" && v != "off" && v != cur.Vision { - if _, _, ok := provider.Resolve(v); !ok { - fail(rw, fmt.Errorf("no model %s to describe images", v)) - return - } - } - if v := strings.TrimSpace(in.ImageGen); v != "" && v != "off" && v != cur.ImageGen { - if _, _, ok := provider.Resolve(v); !ok { - fail(rw, fmt.Errorf("no model %s to generate images", v)) - return - } - } - // the searchers after the one named, set in their own row: a save - // that doesn't send them (prefsKeep has none) keeps them, and an - // empty list clears them - if in.SearcherThen == nil { - in.SearcherThen = cur.SearcherThen - } - for _, v := range append([]string{in.Searcher}, in.SearcherThen...) { - if v = strings.TrimSpace(v); v != "" && v != "off" && v != cur.Searcher && !slices.Contains(cur.SearcherThen, v) { - id, _, _ := strings.Cut(v, "/") - if !slices.ContainsFunc(gateway.Searchers(), func(c gateway.SearcherChoice) bool { return c.Provider.ID == id }) { - fail(rw, fmt.Errorf("%s can't search the web for other models", id)) - return - } - } - } - if err := settings.Save(in); err != nil { + in, cur, err := settingsapi.Apply(body, isWeb(w)) + if err != nil { fail(rw, err) return } if onFonts != nil && (!sameFont(in.UIFont, cur.UIFont) || !sameFont(in.CodeFont, cur.CodeFont)) { onFonts() } - // whether agents are told every model takes images follows Vision - // (provider.Described) - if strings.TrimSpace(in.Vision) != strings.TrimSpace(cur.Vision) { - catalog.Touched() - } if (in.Dock != cur.Dock || in.DockWindow != cur.DockWindow || in.DockNever != cur.DockNever) && onDock != nil { onDock(in) } diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 6c158c934..18d1241c8 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -1599,6 +1599,13 @@ func loadChecked() (Settings, error) { return parse(b) } +// Defaults are the settings of a new install, with no settings.json: +// what `magpie settings list` shows as each one's default, and what +// `magpie settings reset` puts back. +func Defaults() Settings { + return Settings{DockSettled: true}.normal() +} + // settleDock reads a Dock choice written before With window was the // default (DockSettled unset) as that magpie did: no choice is Hide. func (s Settings) settleDock() Settings { diff --git a/internal/settingsapi/settingsapi.go b/internal/settingsapi/settingsapi.go new file mode 100644 index 000000000..c96a941d9 --- /dev/null +++ b/internal/settingsapi/settingsapi.go @@ -0,0 +1,360 @@ +// Package settingsapi is what the Settings page's save writes: the fields +// POST /api/settings takes from the page, how a value is checked, and the +// save itself. The window's handler and `magpie settings` both save through +// Apply, so a value the CLI sets is checked and kept exactly as one the +// page sets (#4745). +package settingsapi + +import ( + "bytes" + "encoding/json" + "fmt" + "reflect" + "slices" + "strconv" + "strings" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// Keys are the settings POST /api/settings saves from what it is sent, by +// their JSON names, in the order `magpie settings list` shows them. Every +// other field of settings.Settings is carried from the file (Merge), set +// by a route of its own or kept by settings.Save. TestKeysAreWhatTheSaveWrites +// fails when a field the save writes is missing here, or one here isn't +// written. +var Keys = []string{ + // Appearance + "theme", "colorblind", "reduceMotion", "noBird", "lang", "uiFont", "codeFont", + // the tray, the Dock and this computer + "tray", "dock", "dockWindow", "dockNever", "lightweight", "keepAwake", "keepAwakeDisplay", + "noWSLAgents", "sessionTerminal", "signInLinkOnly", + // the menu bar's allowance cards + "trayUsages", "trayUsage", "trayUsageEvery", "trayNoLogos", "trayNoBird", "trayPace", "trayNoCost", "trayWindows", + // usage and alerts + "currency", "chineseUnits", "usageAlert", "balanceAlert", "resetReminder", "turnDoneAlert", "maskAlert", + // network + "proxy", + // privacy + "redact", "redactPersonal", "redactKinds", "redactWords", "redactWordsAnyCase", "redactWordsWhole", "redactShape", + "noStats", "noUsageStats", "otel", + // warm-ups and check-ins + "codexWarmup", "claudeWarmup", "codexWarmAt", "claudeWarmAt", "codexWarmAts", "claudeWarmAts", + "workbuddyCheckin", "traeCheckin", "minimaxCheckin", "qoderCheckin", + // models: replies, vision, images, search + "memberModel", "noLoopGuard", "claudeLeanPrompt", "claudePrintMode", "claudeTUIOnly", "refusalRetries", + "vision", "visionEffort", "imageGen", "imageTimeout", "classifyTimeout", + "searcher", "searcherThen", "searcherEffort", "searchFirst", + // updates + "noUpdatePill", "noAutoUpdate", "updateEvery", "noAutoDownload", "autoRestart", "updateChannel", +} + +// Choices are the values a setting with a closed set takes, for +// `magpie settings list` to name: settings' own lists, which settings.Save +// checks a saved value against (a value outside them is refused there, +// from the window as from the CLI). A setting's "" is its default. +var Choices = map[string][]string{ + "theme": settings.Themes, + "lang": settings.Langs, + "tray": settings.Trays, + "currency": settings.Currencies, + "codexWarmup": {"off", "week", "all"}, + "claudeWarmup": {"off", "week", "all"}, + "trayUsageEvery": ints(settings.TrayEvery), + "updateChannel": {settings.UpdateStable}, + "updateEvery": ints(settings.UpdateEveries), + "searchFirst": {settings.SearchFirstModel, settings.SearchFirstAPI}, +} + +func ints(v []int) []string { + out := make([]string, len(v)) + for i, n := range v { + out[i] = strconv.Itoa(n) + } + return out +} + +// Field is the struct field of settings.Settings saved under the JSON name +// key, and whether there is one. +func Field(key string) (reflect.StructField, bool) { + t := reflect.TypeFor[settings.Settings]() + for i := range t.NumField() { + f := t.Field(i) + if name, _, _ := strings.Cut(f.Tag.Get("json"), ","); name == key { + return f, true + } + } + return reflect.StructField{}, false +} + +// Value is key's value in s, as it is saved. +func Value(s settings.Settings, key string) (any, bool) { + f, ok := Field(key) + if !ok { + return nil, false + } + return reflect.ValueOf(s).FieldByIndex(f.Index).Interface(), true +} + +// Known says whether key is one Apply saves. +func Known(key string) bool { return slices.Contains(Keys, key) } + +// Body is what the Settings page sends to set key to value (its JSON) and +// leave everything else as cur has it: cur whole, with key sent even when +// it is a zero value, which a field omitted would not be (an omitted +// noBird is "keep", false is "show the bird"). +func Body(cur settings.Settings, key string, value json.RawMessage) ([]byte, error) { + if !Known(key) { + return nil, fmt.Errorf("unknown setting %q", key) + } + b, err := json.Marshal(cur) + if err != nil { + return nil, err + } + var m map[string]json.RawMessage + if err := json.Unmarshal(b, &m); err != nil { + return nil, err + } + m[key] = value + return json.Marshal(m) +} + +// Apply is POST /api/settings: body read over the settings saved now +// (Merge), checked and saved. It returns what was saved and what was there +// before, for the caller's reactions to a change (the window's Dock, fonts, +// tray menu and alerts). web is a page served to a browser, whose fonts are +// another computer's and never saved. +func Apply(body []byte, web bool) (in, cur settings.Settings, err error) { + // Unreadable settings are never carried as the defaults (an empty + // allow list, every address let in): Save would refuse them too. + cur, err = settings.LoadChecked() + if err != nil { + return in, cur, err + } + in, err = Merge(body, cur, web) + if err != nil { + return in, cur, err + } + if err := settings.Save(in); err != nil { + return in, cur, err + } + // whether agents are told every model takes images follows Vision + // (provider.Described) + if strings.TrimSpace(in.Vision) != strings.TrimSpace(cur.Vision) { + catalog.Touched() + } + return in, cur, nil +} + +// Merge is the settings body sets over cur: the page's own choices from +// body, and everything else as cur has it. It writes nothing. +func Merge(body []byte, cur settings.Settings, web bool) (settings.Settings, error) { + var in settings.Settings + dec := json.NewDecoder(bytes.NewReader(body)) + var raw json.RawMessage + if err := dec.Decode(&raw); err != nil { + return in, err + } + if err := json.Unmarshal(raw, &in); err != nil { + return in, err + } + var fields map[string]json.RawMessage + _ = json.Unmarshal(raw, &fields) + // the Settings page sends its own choices; how the agents are + // arranged is the Agents page's, and the window's size its own; both stay as they are. + // Older pages do not send fonts. An explicit null restores the + // default, while an omitted field (or a browser save) preserves it. + if _, sent := fields["uiFont"]; !sent || web { + in.UIFont = cur.UIFont + } + if _, sent := fields["codeFont"]; !sent || web { + in.CodeFont = cur.CodeFont + } + // and pages from before it do not send how often a refusal is asked + // again, which null sets back to every one left + if _, sent := fields["refusalRetries"]; !sent { + in.RefusalRetries = cur.RefusalRetries + } + // nor whether updates download by themselves (#2296) + if _, sent := fields["noAutoDownload"]; !sent { + in.NoAutoDownload = cur.NoAutoDownload + } + // nor the update channel (ssharpcc on X) + if _, sent := fields["updateChannel"]; !sent { + in.UpdateChannel = cur.UpdateChannel + } + // nor whether the masked words match in any case + if _, sent := fields["redactWordsAnyCase"]; !sent { + in.RedactWordsAnyCase = cur.RedactWordsAnyCase + } + // nor whether they match only as whole words + if _, sent := fields["redactWordsWhole"]; !sent { + in.RedactWordsWhole = cur.RedactWordsWhole + } + // nor whether a key goes as a made-up one of its form + if _, sent := fields["redactShape"]; !sent { + in.RedactShape = cur.RedactShape + } + // nor how long an image is given to be drawn + if _, sent := fields["imageTimeout"]; !sent { + in.ImageTimeout = cur.ImageTimeout + } + // nor how long a routing group's classifier is given (#2934) + if _, sent := fields["classifyTimeout"]; !sent { + in.ClassifyTimeout = cur.ClassifyTimeout + } + // nor whether animations are stilled (#3813) + if _, sent := fields["reduceMotion"]; !sent { + in.ReduceMotion = cur.ReduceMotion + } + // nor whether the loading bird is kept off + if _, sent := fields["noBird"]; !sent { + in.NoBird = cur.NoBird + } + // nor whether a value masked for the first time is told (Must2333) + if _, sent := fields["maskAlert"]; !sent { + in.MaskAlert = cur.MaskAlert + } + in.AgentOrder, in.AgentsHidden, in.AgentsShown = cur.AgentOrder, cur.AgentsHidden, cur.AgentsShown + in.Window, in.WindowMaximised, in.WindowAt = cur.Window, cur.WindowMaximised, cur.WindowAt // the window's own, as it was last resized and moved + // and what other pages keep here: which models an agent is shown, and + // everything the user said of a model anywhere else in the app, set on + // its own. The per-model maps are carried whole rather than named one + // by one, so a map added later is not silently dropped here. + // + // HiddenModels, PickedModels and OrderedModels are the other way + // round — keyed by agent, not by "/" — so they are + // not among them, and belong to the Agents page. + in.Visible, in.HiddenModels, in.OrderedModels = cur.Visible, cur.HiddenModels, cur.OrderedModels + in.PickedModels = cur.PickedModels // "only models I pick" (#1337) + in.OwnModelsHidden = cur.OwnModelsHidden // an agent's own models left out (#1642) + in.FastPicks = cur.FastPicks // switched in the agents' pickers (#954) + in.UltraPicks = cur.UltraPicks // and sent Ultrafast (#1954) + in.AgentEfforts = cur.AgentEfforts // picked in an agent's row (#1003) + in.PluginCheckins = cur.PluginCheckins // set on its own (plugin-checkin) + in.PluginOptions = cur.PluginOptions // set on its own (plugin-option) + in.CheckinOff = cur.CheckinOff // set on its own (checkin-account) + settings.CarryPerModel(&in, &cur) + in.LAN, in.LANKey = cur.LAN, cur.LANKey + in.LANKeyID = cur.LANKeyID + in.Port = cur.Port // set on its own (port), which moves the gateway + in.CORSOrigins = cur.CORSOrigins // set on its own (cors) + in.AllowIPs = cur.AllowIPs // set on its own (allowips) + in.FetchPrivate = cur.FetchPrivate // in settings.json only + in.RouterNote = cur.RouterNote // set on its own (the Library's servers/hub-note) + in.GitHubToken = cur.GitHubToken // set on its own (github-token), never sent to the page + in.ProxyCustom = cur.ProxyCustom // set by settings.Save from the proxy, never by the page + in.RequestArchive = cur.RequestArchive // the Gateway page's, set on its own + in.RequestArchiveMaxMB = cur.RequestArchiveMaxMB // in settings.json only + in.ClaudeRunsMost = cur.ClaudeRunsMost // magpie claude-code runs, or settings.json (#2956) + in.GatewayConversations = cur.GatewayConversations // Sessions' explicit recording consent + in.RedactRules = cur.RedactRules // the masking rules, set on their own + in.RedactModel = cur.RedactModel // set on its own (privacy-model) + in.RedactModelName = cur.RedactModelName // set on its own (privacy-model) + in.RedactModelScore = cur.RedactModelScore // set on its own (privacy-model) + in.RedactModelOff = cur.RedactModelOff // set on its own (privacy-model) + in.RedactModelAuto = cur.RedactModelAuto // set on its own (masking) + in.RedactActions = cur.RedactActions // set on their own (redact-actions) + in.RedactAllow = cur.RedactAllow // set on its own (redact-allow) + in.DisabledModels = cur.DisabledModels // set on their own (disabled-models, #1867) + // the request archive on this computer: the archive's switch while no + // S3 bucket, and its size in settings.json only + in.RequestArchiveLocal, in.RequestArchiveLocalMB = cur.RequestArchiveLocal, cur.RequestArchiveLocalMB + // used or left is the Usage page's toggle as much as Settings', set on its own + in.QuotaLeft = cur.QuotaLeft + in.QuotaReads = cur.QuotaReads // set on its own (quota-reads) + in.SearchAll = cur.SearchAll // set on its own (search-all) + in.UsageOrder = cur.UsageOrder // the Usage page's, dragged there + // and what the tray panel's Allowances tab leaves out, set there + in.PanelUsageHidden = cur.PanelUsageHidden + // and the clients the Usage page's Agents list leaves out, set there + in.UsageAgentsHidden = cur.UsageAgentsHidden + // and the allowance cards the Usage page's Overview leaves out, set there + in.UsageCardsHidden = cur.UsageCardsHidden + // and the names models' usage is counted under (magpie model alias) + in.UsageAliases = cur.UsageAliases + // and the clears of usage made on the Usage page + in.UsageCleared = cur.UsageCleared + // and the clients it counts as agents, set there too (#1958) + in.ClientAgents = cur.ClientAgents + // how agents' lists name models, set on its own for the agents to be told + in.PlainNames, in.PlainOwnNames = cur.PlainNames, cur.PlainOwnNames + in.BareModelIDs = cur.BareModelIDs // set on its own (bare-ids) + in.BusyLoad = cur.BusyLoad // and so is this (busy-load) + in.CodexAgentsV1 = cur.CodexAgentsV1 + in.FullContext = cur.FullContext // set on its own (full-context) + in.CompactAt = cur.CompactAt // and so is the threshold + // Codex's background compaction, set on its own (codex-async-compact) + in.CodexAsyncCompact, in.CodexAsyncCompactPercent = cur.CodexAsyncCompact, cur.CodexAsyncCompactPercent + // Claude Desktop's list, set in its row on the Agents page + in.DesktopLongest = cur.DesktopLongest + // and the Get started card put away, from the card itself + in.GuideHidden = cur.GuideHidden + + in.CodexTitles = cur.CodexTitles // set on its own (codex-titles) + in.CodexDescriptions = cur.CodexDescriptions // set on its own (codex-descriptions) + in.CodexPredictions = cur.CodexPredictions // and codex-predictions + // and so is the model Codex's auto-review runs on (codex-auto-review) + in.CodexAutoReview = cur.CodexAutoReview + // and the models Codex's and Desktop's subagents are put on, set + // in their Agents rows + in.CodexSubagentModel = cur.CodexSubagentModel + in.DesktopSubagentModel = cur.DesktopSubagentModel + // and the model for requests masking would change (redact-route) + in.RedactRouteTo = cur.RedactRouteTo + in.DesktopSubagentEffort = cur.DesktopSubagentEffort + in.ChinaMirror = cur.ChinaMirror // the Plugins page's, set on its own + in.NPMRegistry = cur.NPMRegistry // and its npm registry + // which Codex accounts spend a reset by themselves, set on the Usage card + in.CodexAutoReset = cur.CodexAutoReset + in.CodexAutoResetOnly = cur.CodexAutoResetOnly // and at which of the two times + in.CodexResetLead = cur.CodexResetLead // and how early before one expires (codex-reset-lead) + // and which of them spend their credits, set there too + in.CodexNoCredits = cur.CodexNoCredits + in.CodexCreditsLast = cur.CodexCreditsLast // and which only after everything else + // and each Codex account's own daily warm-up (codex-warm-at) + in.CodexWarmAtOf = cur.CodexWarmAtOf + // and the text size, which the keyboard changes too (text-size) + in.TextSize = cur.TextSize + // and the quick panel's shortcut, set on its own (panel-shortcut) + in.PanelShortcut = cur.PanelShortcut + // the Dock choice's reading, which the page never sets: the file's + // as read (settings.DockSettled), so a save from the page doesn't + // read its With window as an older file's Hide + in.DockSettled = cur.DockSettled + // the version the Update pill was hidden for, set from the pill + in.UpdateSkip = cur.UpdateSkip + // the GitHub mirror updates come through, set by magpie update mirror + in.UpdateMirror = cur.UpdateMirror + // gateway mode, set on its own (gateway-mode) + in.GatewayMode = cur.GatewayMode + in.NoAccountDiscovery = cur.NoAccountDiscovery // set on its own (account-discovery, or the CLI) + if v := strings.TrimSpace(in.Vision); v != "" && v != "off" && v != cur.Vision { + if _, _, ok := provider.Resolve(v); !ok { + return in, fmt.Errorf("no model %s to describe images", v) + } + } + if v := strings.TrimSpace(in.ImageGen); v != "" && v != "off" && v != cur.ImageGen { + if _, _, ok := provider.Resolve(v); !ok { + return in, fmt.Errorf("no model %s to generate images", v) + } + } + // the searchers after the one named, set in their own row: a save + // that doesn't send them (prefsKeep has none) keeps them, and an + // empty list clears them + if in.SearcherThen == nil { + in.SearcherThen = cur.SearcherThen + } + for _, v := range append([]string{in.Searcher}, in.SearcherThen...) { + if v = strings.TrimSpace(v); v != "" && v != "off" && v != cur.Searcher && !slices.Contains(cur.SearcherThen, v) { + id, _, _ := strings.Cut(v, "/") + if !slices.ContainsFunc(gateway.Searchers(), func(c gateway.SearcherChoice) bool { return c.Provider.ID == id }) { + return in, fmt.Errorf("%s can't search the web for other models", id) + } + } + } + return in, nil +} diff --git a/internal/settingsapi/settingsapi_test.go b/internal/settingsapi/settingsapi_test.go new file mode 100644 index 000000000..a40b6968b --- /dev/null +++ b/internal/settingsapi/settingsapi_test.go @@ -0,0 +1,215 @@ +package settingsapi + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "reflect" + "slices" + "strings" + "testing" + + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/testenv" +) + +func TestMain(m *testing.M) { testenv.Main(m) } + +// home gives the test a home of its own, with no settings.json yet. +func home(t *testing.T) { + t.Helper() + root := t.TempDir() + testenv.SetHome(t, root) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, ".config")) + t.Setenv("APPDATA", filepath.Join(root, "AppData", "Roaming")) +} + +// sample is a value of t that isn't was, as JSON carries it. +func sample(t reflect.Type, key string, was reflect.Value) reflect.Value { + v := reflect.New(t).Elem() + switch t.Kind() { + case reflect.Bool: + v.SetBool(!was.Bool()) + case reflect.String: + s := "x" + switch key { + case "vision", "imageGen", "searcher", "searcherThen": + s = "off" // a model is checked against the catalog + } + for _, c := range Choices[key] { + if c != was.String() { + s = c + break + } + } + v.SetString(s) + case reflect.Int, reflect.Int64, reflect.Int32: + v.SetInt(was.Int() + 7) + case reflect.Float64, reflect.Float32: + v.SetFloat(was.Float() + 1.5) + case reflect.Pointer: + elem := reflect.Zero(t.Elem()) + if !was.IsNil() { + elem = was.Elem() + } + v.Set(reflect.New(t.Elem())) + v.Elem().Set(sample(t.Elem(), key, elem)) + case reflect.Slice: + el := sample(t.Elem(), key, reflect.Zero(t.Elem())) + v.Set(reflect.Append(reflect.MakeSlice(t, 0, 1), el)) + case reflect.Map: + v.Set(reflect.MakeMap(t)) + v.SetMapIndex(sample(t.Key(), "", reflect.Zero(t.Key())), sample(t.Elem(), "", reflect.Zero(t.Elem()))) + case reflect.Struct: + for i := range t.NumField() { + if f := t.Field(i); f.IsExported() { + v.Field(i).Set(sample(f.Type, "", reflect.Zero(f.Type))) + } + } + } + return v +} + +// Keys are the fields POST /api/settings saves from what it's sent, no +// more and no fewer: each field of settings.Settings is sent changed, on +// its own, and the ones the save takes are compared with Keys. A field +// added to Settings that the save takes (or carries) without Keys knowing +// fails here, and so `magpie settings` can't fall behind the window +// (#4745). +func TestKeysAreWhatTheSaveWrites(t *testing.T) { + cur := settings.Defaults() + curJSON, err := json.Marshal(cur) + if err != nil { + t.Fatal(err) + } + st := reflect.TypeFor[settings.Settings]() + var written []string + for i := range st.NumField() { + f := st.Field(i) + key, _, _ := strings.Cut(f.Tag.Get("json"), ",") + if key == "" || key == "-" { + continue + } + was := reflect.ValueOf(cur).Field(i) + val := sample(f.Type, key, was) + b, err := json.Marshal(val.Interface()) + if err != nil { + t.Fatalf("%s: %v", key, err) + } + var m map[string]json.RawMessage + _ = json.Unmarshal(curJSON, &m) + m[key] = b + body, _ := json.Marshal(m) + in, err := Merge(body, cur, false) + if err != nil { + t.Fatalf("%s sent as %s: %v", key, b, err) + } + if !reflect.DeepEqual(reflect.ValueOf(in).Field(i).Interface(), was.Interface()) { + written = append(written, key) + } + } + // settings.Save keeps the file's own: the page can send it, and it + // is never written by this save (SetSessionReads writes it) + written = slices.DeleteFunc(written, func(k string) bool { return k == "sessionReads" }) + got, want := slices.Sorted(slices.Values(written)), slices.Sorted(slices.Values(Keys)) + if !slices.Equal(got, want) { + t.Errorf("the save writes keys Keys doesn't name, or Keys names keys it doesn't write:\n only saved: %v\n only in Keys: %v", + minus(got, want), minus(want, got)) + } + for _, k := range Keys { + if _, ok := Field(k); !ok { + t.Errorf("Keys names %q, which settings.Settings doesn't have", k) + } + } + if len(Keys) != len(slices.Compact(slices.Sorted(slices.Values(Keys)))) { + t.Error("Keys names a key twice") + } +} + +func minus(a, b []string) []string { + var out []string + for _, k := range a { + if !slices.Contains(b, k) { + out = append(out, k) + } + } + return out +} + +// Setting one key through Body leaves every other the user set as it +// is, and a key the save keeps when it isn't sent is set even to its +// zero value. +func TestBodySetsOneKeyOnly(t *testing.T) { + home(t) + s := settings.Defaults() + s.Theme, s.NoBird, s.RedactShape, s.Currency, s.Proxy = "dark", true, true, "cny", "http://127.0.0.1:7890" + two := 2 + s.RefusalRetries = &two + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + set := func(key, value string) settings.Settings { + t.Helper() + cur, err := settings.LoadChecked() + if err != nil { + t.Fatal(err) + } + body, err := Body(cur, key, json.RawMessage(value)) + if err != nil { + t.Fatal(err) + } + if _, _, err := Apply(body, false); err != nil { + t.Fatalf("%s=%s: %v", key, value, err) + } + return settings.Load() + } + got := set("noBird", "false") + if got.NoBird { + t.Error("noBird set to false stayed on: a zero value was read as not sent") + } + got = set("lang", `"ja"`) + if got.Lang != "ja" || got.Theme != "dark" || !got.RedactShape || got.Currency != "cny" || + got.Proxy != "http://127.0.0.1:7890" || got.RefusalRetries == nil || *got.RefusalRetries != 2 { + t.Errorf("setting lang changed what the user set: %+v", got) + } +} + +// A value the save refuses writes nothing, whichever way it came in. +func TestRefusedValueWritesNothing(t *testing.T) { + home(t) + s := settings.Defaults() + s.Theme = "dark" + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + before, err := os.ReadFile(settings.Path()) + if err != nil { + t.Fatal(err) + } + for key, value := range map[string]string{ + "theme": `"neon"`, + "lang": `"xx"`, + "trayUsageEvery": `4`, + "vision": `"nobody/nothing"`, + "searcher": `"nobody/nothing"`, + "usageAlert": `101`, + "updateChannel": `"nightly"`, + } { + cur := settings.Load() + body, err := Body(cur, key, json.RawMessage(value)) + if err != nil { + t.Fatal(err) + } + if _, _, err := Apply(body, false); err == nil { + t.Errorf("%s=%s was saved", key, value) + } + after, _ := os.ReadFile(settings.Path()) + if !bytes.Equal(before, after) { + t.Fatalf("%s=%s was refused but settings.json changed", key, value) + } + } + if _, err := Body(settings.Load(), "port", json.RawMessage(`1`)); err == nil { + t.Error("Body took port, which has a route of its own") + } +}