Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

agent: NewMax, magpie's models in its model picker (jwaitq on Discord)

yetonee7173958e9c5
diff --git a/README.md b/README.md
index 7744edd3e..2d210e354 100644
--- a/README.md
+++ b/README.md
@@ -78,7 +78,7 @@ magpie finds the subscriptions your agents are signed in to by reading their sig
<table>
<tr><td>
-Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · PenguinHarness · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · OpenPencil · Raycast · Kiro Crew · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy · Lody · AionUi · Ante · AstrBot
+Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · PenguinHarness · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · OpenPencil · NewMax · Raycast · Kiro Crew · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy · Lody · AionUi · Ante · AstrBot
</td></tr>
</table>
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 64f8bd9f0..896de8561 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -78,7 +78,7 @@ magpie 通过读取智能体的登录信息(Claude Code 和 Codex 的文件、
<table>
<tr><td>
-Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · PenguinHarness · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · OpenPencil · Raycast · Kiro Crew · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy · Lody · AionUi · Ante · AstrBot
+Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · PenguinHarness · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · OpenPencil · NewMax · Raycast · Kiro Crew · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy · Lody · AionUi · Ante · AstrBot
</td></tr>
</table>
diff --git a/docs/reference.md b/docs/reference.md
index 83ad36a42..7be7f82bc 100644
--- a/docs/reference.md
+++ b/docs/reference.md
@@ -144,6 +144,7 @@ line; agents connected to magpie lose it when it quits.
| Raycast | `~/.config/raycast/ai/providers.yaml` in the user's folder, on Mac and Windows | provider (a `magpie` entry in Raycast AI's Custom Providers, magpie's models in its model picker; Raycast Pro; the user's providers, `tools` and comments kept) |
| Kiro Crew | `~/.kiro/crew/config.json` (`$KIROCREW_HOME`; `config.local.json` over it is left alone) | provider, harness (`agent.acp_backend`, and `agent.member_acp_backend` for a harness that can dispatch: an agent connected to magpie, so its models are magpie's: the one Crew is set to is connected along with it when it isn't yet, and disconnected with it again; the user's value is put back on Disconnect) |
| OpenPencil | `openpencil/settings.json` in the config folder: `~/Library/Application Support` (macOS), `$XDG_CONFIG_HOME` or `~/.config` (Linux), `%APPDATA%` (Windows) | provider (a `magpie` entry in its `builtin_agents`, magpie's models in its chat's model picker; the user's entries and settings kept; refused while OpenPencil runs, as it writes the file back when it quits) |
+| NewMax | `newmax.db` (SQLite, the row `app` of its `settings` table) in `$NEWMAX_USER_DATA_DIR`, else `~/.newmax` (every OS) | provider (a `magpie-gateway` entry in its `providers` and `providerOrder`, magpie's models in its model picker; the rest of the row kept byte for byte; refused while NewMax runs, as it writes its settings back whenever one changes) |
| T3 Code | `~/.t3/userdata/settings.json` (`$T3CODE_HOME/userdata`) | provider (a `magpie` provider instance on Claude Code, magpie's models as its custom models) |
| OpenHanako | `~/.hanako/provider-catalog.json` + `agents/<id>/config.yaml` (`$HANA_HOME`; its local API while it runs) | model (the primary agent's; magpie's models as a provider) |
| AtomCode | `~/.atomcode/config.toml` (`$ATOMCODE_HOME`) | model, effort (a `magpie` provider account, one model table per catalog model as its own sign-in writes) |
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md
index 792614361..7d7363756 100644
--- a/docs/subsystems/agent-wiring.md
+++ b/docs/subsystems/agent-wiring.md
@@ -71,6 +71,7 @@ something else shows up as drift.
- Raycast AI reads Custom Providers from `~/.config/raycast/ai/providers.yaml` in the user's folder, on Mac and Windows alike (`raycast` in [`raycast.go`](../../internal/agent/raycast.go); manual.raycast.com/ai/custom-providers). magpie adds one entry to its `providers` list, `id: magpie`, at the gateway's `/v1` with an `api_keys` alias holding a key that names Raycast (its User-Agent isn't known), and one model per catalog model with `context` and all five `abilities` said, since Raycast assumes tools and vision off when one isn't. The list is edited as a node (`EditYAMLNode`), so the user's other entries, the `tools` block (anchors too) and comments stay. A key the user adds to magpie's entry or to one of its models (`include_user_email`, a `description`) is kept on a sync (`mergeYAMLKept`), and a sync with nothing to change doesn't write. Disconnect takes the entry out, the list when it was the only one, and a file left with nothing in it. Raycast watches the file, so there is no restart notice. The model is picked in Raycast, so the field is whether magpie is in its picker (`ListsModels`). Detected by `Raycast.app` on a Mac or the `~/.config/raycast` folder.
- Kiro Crew (AWS's persistent agent: KiroCrew.app, the `kirocrew` CLI, its Gateway on :5476) has no model setting of its own: it runs every session on a harness over ACP, chosen by `agent.acp_backend` in `$KIROCREW_HOME/config.json` (default `~/.kiro/crew`; `""` is kiro-cli), and dispatched members by `agent.member_acp_backend` (`kirocrew` in [`kirocrew.go`](../../internal/agent/kirocrew.go); github.com/kirodotdev/KiroCrew v0.9.0, `src/kiro_crew/` `config/paths.py`, `config/loader.py`, `config/sections.py`, `agent_sdk/backends.py`). Connecting it sets both to an agent already connected to magpie (Codex, Claude Code, OpenCode, Pi or Goose; Pi can't take dispatch, so only the first key for it), preferring the one whose ACP adapter is installed (codex-acp, claude-agent-acp, pi-acp; looked for, never installed, and named in the notice when missing). When `agent.acp_backend` already names one of those five and that agent is installed but not connected, connecting Kiro Crew connects that agent too, in the same action, and runs Crew on it (wuping9525 on Windows: Crew on Claude Code, Claude Code not connected); the stash's `kirocrew.joined` records it, and Kiro Crew's Disconnect disconnects it again, unless the user disconnected it themselves since (`kiroCrewUserLeft` in `Agent.Disconnect`), and a disconnect the user had made before stays theirs. Otherwise, with none connected it refuses and says which to connect. On Windows the app is found by `~\.kirocrew-app\.venv\Scripts\kirocrew.exe` and an adapter also by npm's `.cmd`/`.exe` shim names. `config.local.json` is merged over `config.json` and wins, so a harness set there is the user's: magpie neither writes nor reads past it, and the row says so. The previous values are stashed and put back on Disconnect, only while each key still holds what magpie wrote; a file magpie made is removed when it is left empty. The row reads as connected only while the harness it names is still wired to magpie. Open sessions keep their harness; new ones take it.
- OpenPencil (ZSeven-W/openpencil, the `openpencil-desktop` app) keeps the builtin agents its chat runs on in `settings.json` in Rust's `dirs::config_dir()` joined with `openpencil`: `~/Library/Application Support/openpencil` on a Mac, `$XDG_CONFIG_HOME` or `~/.config` on Linux, `%APPDATA%` on Windows (`openPencil` in [`openpencil.go`](../../internal/agent/openpencil.go); its `settings_io.rs` and `settings_payload.rs`). magpie adds one entry to `builtin_agents`, `id: magpie`, `kind: openai-compat` at the gateway's `/v1` with a key naming OpenPencil (its User-Agent isn't known), `preset: custom`, the picked models as OpenPencil writes a list: the first as `model`, `models` only for two or more, at most 64 (v0.8.4 reads `model` alone). The user's other entries and settings stay, and so do the `display_name` and `enabled` they give magpie's entry; a sync with nothing to change doesn't write. OpenPencil needs `"version": 1` (a file without it is set aside as corrupt and saving stops), so magpie writes it in a file it makes and leaves a file with any other version, or none, alone. Disconnect takes the entry out, and the file when only the version and an empty list are left. OpenPencil reads the file once at start and writes it back whole when it quits, so a change is refused while `openpencil-desktop` runs (Windows can't be asked, so the notice says to quit it first). The model is picked in OpenPencil's chat, so the field is whether magpie is in its picker (`ListsModels`). Detected by its settings folder, `~/.openpencil` (its CLI's), `OpenPencil.app` (`com.zseven-w.openpencil`), or `%ProgramFiles%\OpenPencil`. open-pencil/open-pencil, the other app of the name, keeps its providers in its webview's localStorage, so it is not a row: it reaches magpie through Pi or an ACP agent magpie wires.
+- NewMax (newmax.cc, an Electron app on the Claude Agent SDK) keeps its settings as JSON in the row `app` of the `settings` table of `newmax.db`, a SQLite database in WAL mode in `$NEWMAX_USER_DATA_DIR`, else `~/.newmax` on every system (`newMax` in [`newmax.go`](../../internal/agent/newmax.go); its main bundle's `configureAppDataPaths`, `loadPersistedAppSettings` and the renderer's `mergeProviders`, v1.1.22). magpie adds one entry to `providers` in the shape NewMax's own import writes, `id: magpie-gateway` (its own preset is `magpie`, its import's ids hold `%3A`), `apiFormat: anthropic` at the gateway's root (NewMax appends `/v1/messages`) with `ANTHROPIC_AUTH_TOKEN` and a key naming NewMax, at most 20 models (`MAX_MODELS`) as `models` and `enabledModels` with their context windows, and its id at the end of `providerOrder`. The row is edited in place in one immediate transaction, so every other byte stays; the user's `name` and `enabled` for magpie's entry and the fields NewMax adds to it stay through a sync, and a sync with nothing to change doesn't write. A row that isn't a JSON object, or whose `providers` or `providerOrder` isn't a list, is left alone. With no row (NewMax at its defaults), magpie writes one with its entry alone, as NewMax lays its defaults and presets under the row; with no database yet, it asks to open NewMax once. Disconnect takes the entry and the id out, sets a pick of it back to `default`, and takes the row out when only what magpie made is left. NewMax holds its settings in memory and writes the whole row back whenever one changes, so a change is refused while `NewMax` (`newmax` on Linux) runs (Windows can't be asked, so the notice says to quit it first). The model is picked in NewMax's model picker, so the field is whether magpie is in it (`ListsModels`). Detected by its data folder or `NewMax.app` (`cc.newmax.desktop`).
- DevEco Code (Huawei's OpenCode fork, #1885) is wired as OpenCode is (`deveco` in [`agents.go`](../../internal/agent/agents.go)): magpie's provider goes into the first of `deveco.jsonc`, `deveco.json` and `config.json` in `~/.config/deveco` (the one DevEco merges last, so the one that wins), or in `$DEVECO_CONFIG_DIR` when that is absolute, read after them. 0.2.3 sends `deveco/0.2.3 ai-sdk/…` to a provider of its config, but much of the OpenCode code it keeps still sends OpenCode's own User-Agent (`opencode/<version>`), so its provider's key is `magpie-deveco` (`openCodeKeyAt`), not the plain `magpie` OpenCode and MiMo Code send, and Check asks for that key. Its npm package has no Linux binary, so no install command is offered there (`cliSpec.only`).
- Grok App (RongleCat/grok-app, a desktop front end that starts Grok Build over ACP) keeps its provider channels in `agent-home/config.toml` under its data folder: `$GROK_APP_HOME`, else where its `directories` crate puts it, or its `~/.grok-app` fallback when that is the one there (`grokApp` in [`grokapp.go`](../../internal/agent/grokapp.go)). Its composer lists only Grok Build's official catalog, never the `[model."magpie/…"]` tables of Grok Build's row, so magpie adds itself as a channel, `[model.magpie]`, with the keys the App's Providers page writes: the gateway's `/v1`, a key naming Grok App, `api_backend = "chat_completions"`, `app_provider_mode = "generic"`, and `app_models`, a JSON list of magpie's models with `contextWindow`, `supportsVision` and their effort levels (no `none`; a default the user marks in the App stays, else medium). The picked model's `context_window` (a bare integer) and `supports_reasoning_effort` (a bare bool, Grok Build's gate for `--reasoning-effort`) are on the channel, as the App puts them there when a model is picked in its composer. `[models] default` is the route, and magpie does not set it: setting it to `"magpie"` makes the App drop its own sign-in (`ensure_independent_for_custom_route`). The route stays whatever the App had. Pressing Use on magpie under Accounts is what switches it. A magpie that already set the route puts the old one back once, on the next sync or connect (`grokAppReleased`); a Use after that stays. Disconnect drops only the channel, and puts the route back only when it is still `"magpie"`: the one stashed at connect, else the one `connect.was` holds. One of the App's own routes picked in magpie's model field is written as the route and takes magpie's channel out, as picking another provider does elsewhere. A sync with no channel and a route other than `"magpie"` writes nothing, magpie's stash included, and Check says so when the route is `"magpie"` with the channel gone. A model picked in the App's composer since is the user's and stays through a sync, and a sync with nothing to change doesn't write. Shared mode keeps `GROK_HOME` at `~/.grok` (Grok Build's library row). Independent mode, which Use turns on, reads agent-home: the Library writes `AGENTS.md`, `[mcp_servers]` in the same `config.toml`, and `skills/` there, and Grok App also reads `~/.agents/skills`. RTK has no Grok hook, so the Library lists Grok App with the switch off. The notice, while the App runs, says magpie is a custom provider in Settings › Account, a chat can pick its models in the model picker, and the App stays on its current route until Use.
- JSON/JSONC config edits and their previews reject malformed input rather than editing a partially parsed document. Object edits and VS Code's model-group array edits leave the original file untouched on a parse error; valid comments and trailing commas remain supported (`internal/edit`).
@@ -150,6 +151,7 @@ go test -tags nogui ./internal/agent -run '^TestJcode'
go test -tags nogui ./internal/agent -run '^TestRaycast'
go test -tags nogui ./internal/agent -run '^TestKiroCrew'
go test -tags nogui ./internal/agent -run '^TestOpenPencil'
+go test -tags nogui ./internal/agent -run '^TestNewMax'
go test -tags nogui ./internal/agent -run '^TestGrokApp'
go test -tags nogui ./internal/agent -run 'ClaudeScience'
go test -tags nogui ./internal/gateway -run 'TestClaudeScience'
diff --git a/internal/agent/agents.go b/internal/agent/agents.go
index 9c47c7c53..2a154e980 100644
--- a/internal/agent/agents.go
+++ b/internal/agent/agents.go
@@ -151,6 +151,7 @@ func builtins(home, cfg string) []*Agent {
codebuddy(home),
pencil(home),
openPencil(home, cfg),
+ newMax(home),
raycast(home),
kiroCrew(home),
t3code(home),
diff --git a/internal/agent/gatewaykey_test.go b/internal/agent/gatewaykey_test.go
index dd00f8ab5..cd94e3d42 100644
--- a/internal/agent/gatewaykey_test.go
+++ b/internal/agent/gatewaykey_test.go
@@ -225,6 +225,7 @@ func TestPinnedGatewayKeyForEveryWriter(t *testing.T) {
"copilotjb": jbKey,
"cursor": cursorLocalEnv(gw)[cursorLocalVars[1]],
"hanako": hanakoProvider().APIKey,
+ "newmax": newMaxEntryFor(gw).APIKey,
"openpencil": openPencilEntry(gw).APIKey,
"pencil": pencilProviderJSON(gw)["apiKey"].(string),
"vscode": vscodeStable.token(),
diff --git a/internal/agent/lists_models_test.go b/internal/agent/lists_models_test.go
index b74558da5..f52e589c2 100644
--- a/internal/agent/lists_models_test.go
+++ b/internal/agent/lists_models_test.go
@@ -61,7 +61,7 @@ func TestEveryPickerOfMagpiesModelsCanBeNarrowed(t *testing.T) {
if len(bare) > 0 {
t.Errorf("magpie's models are put in these agents' pickers with no way to pick which: %v", bare)
}
- for _, id := range []string{"zcode", "pencil", "openpencil", "t3code", "workbuddy", "workbuddy-ai", copilotJBID, CursorLocalID} {
+ for _, id := range []string{"zcode", "pencil", "openpencil", "newmax", "t3code", "workbuddy", "workbuddy-ai", copilotJBID, CursorLocalID} {
if !slices.Contains(menus, id) {
t.Errorf("%s's row has no model list to pick in (ListsModels): %v", id, menus)
}
diff --git a/internal/agent/newmax.go b/internal/agent/newmax.go
new file mode 100644
index 000000000..1ff8f2f12
--- /dev/null
+++ b/internal/agent/newmax.go
@@ -0,0 +1,491 @@
+package agent
+
+// NewMax (newmax.cc, 牛马AI; jwaitq on Discord) is a desktop agent app on
+// the Claude Agent SDK. It keeps its settings in its own SQLite database,
+// newmax.db in its data folder: $NEWMAX_USER_DATA_DIR, else ~/.newmax on
+// every system (configureAppDataPaths in its main bundle, v1.1.22). The
+// row `app` of its table settings (key TEXT PRIMARY KEY, value TEXT NOT
+// NULL) is JSON.stringify of all its settings, and their providers are a
+// list in it, keys in the clear:
+//
+// {…, "providerId":"default", "model":"default",
+// "providers":[…, {"id":"magpie-gateway","name":"magpie",
+// "baseUrl":"http://127.0.0.1:3425","apiKey":"magpie-newmax",
+// "apiKeys":["magpie-newmax"],"apiKeyRotationEnabled":false,
+// "apiKeyField":"ANTHROPIC_AUTH_TOKEN","apiFormat":"anthropic",
+// "models":[…],"enabledModels":[…],"enabled":true,"canDelete":true}],
+// "providerOrder":["default","magpie-gateway"], …}
+//
+// That entry is the one NewMax's own "import from magpie" writes for a
+// provider of providers.json (mapProvider, applyCcSwitchProviderImport):
+// an Anthropic base URL without /v1 (it posts to baseUrl + /v1/messages,
+// through the Claude Code its SDK runs, as ANTHROPIC_BASE_URL and
+// ANTHROPIC_AUTH_TOKEN), at most 20 models (MAX_MODELS: a primary and 19
+// back-ups; it lists enabledModels, the first 20, in its model picker), and
+// the id added to providerOrder. A provider is listed in the model picker
+// whether or not providerOrder has it, so the model is picked there and the
+// field is whether magpie's models are in it (ListsModels). The id is
+// magpie's own: NewMax's built-in "Magpie" preset is "magpie", and the ones
+// its import makes are "magpie-<id>%3A<protocol>", so neither is touched.
+//
+// NewMax reads the row when it starts and writes it whole from what it
+// holds whenever a setting changes, so a change magpie makes while it runs
+// is lost the next time it saves: magpie refuses one then, where it can
+// tell (Running can't on Windows, where the notice says so instead). The
+// row is edited in place, in one transaction: magpie's entry and its id in
+// providerOrder go in and out, and the rest of the row stays byte for byte.
+// The user's name for magpie's entry, its on/off and the fields NewMax adds
+// to it (capabilities it tested) stay through a sync.
+
+import (
+ "bytes"
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/url"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+
+ "github.com/tidwall/gjson"
+
+ "github.com/yetone/magpie/internal/appdir"
+ "github.com/yetone/magpie/internal/gateway"
+ "github.com/yetone/magpie/internal/sessions"
+ _ "github.com/yetone/magpie/internal/sqlitedb"
+)
+
+// newMaxApp is NewMax's macOS bundle.
+var newMaxApp = desktopApp{id: "cc.newmax.desktop", names: []string{"NewMax.app"}}
+
+// newMaxID is magpie's provider in NewMax's providers.
+const newMaxID = "magpie-gateway"
+
+// newMaxMaxModels is how many models NewMax keeps in a provider's picker
+// list (MAX_MODELS).
+const newMaxMaxModels = 20
+
+// newMaxProc is NewMax's process: the .app's CFBundleExecutable NewMax, the
+// Linux build's newmax. The program itself, the first word of its command
+// line, or the .app's executable wherever the bundle is: a shell in a
+// folder named newmax ("cd ~/newmax && …") is not NewMax.
+var newMaxProc = []string{`^([^ ]*/)?(NewMax|newmax)( |$)`, `NewMax\.app/Contents/MacOS/NewMax( |$)`}
+
+var noticeNewMax = newNotice("NewMax keeps its settings in memory while it runs and writes them all back when one changes — quit NewMax before changing this, then open it and pick a magpie model in its model picker.")
+
+// errNewMaxRunning is a change refused while NewMax runs.
+var errNewMaxRunning = errors.New("NewMax writes its settings back over what magpie writes now: quit NewMax, then try again")
+
+// errNewMaxNoDB is a change asked for before NewMax made its database.
+var errNewMaxNoDB = errors.New("NewMax hasn't made its settings yet: open NewMax once, quit it, then try again")
+
+func newMax(home string) *Agent {
+ dir := newMaxDir(home)
+ path := filepath.Join(dir, "newmax.db")
+ write := func(on bool) error {
+ if !on {
+ return newMaxEdit(path, newMaxUnwire)
+ }
+ e := newMaxEntryFor(gateway.URL())
+ return newMaxEdit(path, func(app []byte, had bool) ([]byte, error) { return newMaxWire(app, had, e) })
+ }
+ return &Agent{
+ ID: "newmax", Name: "NewMax", Icon: "generic", Aliases: []string{"newmax-ai", "newmaxai"},
+ Dir: dir, Path: path,
+ detect: func() bool { return isDir(dir) || macBundle(newMaxApp) },
+ Notice: func() string {
+ if newMaxWired(path) && Running(newMaxProc...) {
+ return noticeNewMax.String()
+ }
+ return ""
+ },
+ // a sync while it runs is written as well: NewMax's next save
+ // puts back what it holds, and the next sync magpie's models
+ Sync: func() error {
+ if !newMaxWired(path) {
+ return nil
+ }
+ return write(true)
+ },
+ ListsModels: true,
+ Fields: []Field{{
+ Key: "provider", Label: "provider",
+ Get: func() string {
+ if newMaxWired(path) {
+ return magpieID
+ }
+ return ""
+ },
+ Set: func(v string) error {
+ if newMaxRunning() {
+ return errNewMaxRunning
+ }
+ return write(v != "")
+ },
+ Options: func(map[string]string) []Option {
+ return []Option{{Value: magpieID, Label: "magpie", Icon: "magpie", Note: "every magpie model in NewMax's model picker"}}
+ },
+ }},
+ }
+}
+
+// newMaxRunning says NewMax is open where magpie can tell; on Windows,
+// where Running can't, no, and the notice asks to quit it first.
+var newMaxRunning = func() bool {
+ return runtime.GOOS != "windows" && Running(newMaxProc...)
+}
+
+// newMaxDir is NewMax's data folder: $NEWMAX_USER_DATA_DIR when it names
+// one, else ~/.newmax, on every system.
+func newMaxDir(home string) string {
+ if d := appdir.Getenv("NEWMAX_USER_DATA_DIR"); d != "" && filepath.IsAbs(d) {
+ return d
+ }
+ return filepath.Join(home, ".newmax")
+}
+
+// newMaxEntry is magpie's provider, in the order NewMax's import writes
+// one.
+type newMaxEntry struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ BaseURL string `json:"baseUrl"`
+ APIKey string `json:"apiKey"`
+ APIKeys []string `json:"apiKeys"`
+ APIKeyRotationEnabled bool `json:"apiKeyRotationEnabled"`
+ APIKeyField string `json:"apiKeyField"`
+ APIFormat string `json:"apiFormat"`
+ Models []string `json:"models"`
+ EnabledModels []string `json:"enabledModels"`
+ Enabled bool `json:"enabled"`
+ CanDelete bool `json:"canDelete"`
+ ModelContextWindows map[string]int64 `json:"modelContextWindows,omitempty"`
+}
+
+// newMaxEntryFor is magpie's provider for a gateway at gw: its Anthropic
+// Messages, the key that names NewMax, and the models picked for it, each
+// once, at most 20, with the context windows magpie knows.
+func newMaxEntryFor(gw string) newMaxEntry {
+ key := agentKeyAt("newmax", gw)
+ e := newMaxEntry{ID: newMaxID, Name: "magpie", BaseURL: gw, APIKey: key, APIKeys: []string{key},
+ APIKeyField: "ANTHROPIC_AUTH_TOKEN", APIFormat: "anthropic", Models: []string{}, Enabled: true, CanDelete: true}
+ seen := map[string]bool{}
+ for _, m := range magpieModels("newmax") {
+ if m.ID == "" || seen[m.ID] {
+ continue
+ }
+ seen[m.ID] = true
+ e.Models = append(e.Models, m.ID)
+ if m.Context > 0 {
+ if e.ModelContextWindows == nil {
+ e.ModelContextWindows = map[string]int64{}
+ }
+ e.ModelContextWindows[m.ID] = int64(m.Context)
+ }
+ if len(e.Models) == newMaxMaxModels {
+ break
+ }
+ }
+ e.EnabledModels = e.Models
+ return e
+}
+
+// newMaxReadApp reads the `app` row of the database at path without writing a
+// byte beside it: the row, whether there is one, and an error for a
+// database that couldn't be read.
+func newMaxReadApp(path string) (app []byte, had bool, err error) {
+ if _, err := os.Stat(path); err != nil {
+ return nil, false, err
+ }
+ db, closeDB, err := sessions.OpenUntouched(path)
+ if err != nil {
+ return nil, false, err
+ }
+ defer closeDB()
+ var v string
+ switch err := db.QueryRow(`SELECT value FROM settings WHERE key = 'app'`).Scan(&v); {
+ case errors.Is(err, sql.ErrNoRows):
+ return nil, false, nil
+ case err != nil:
+ return nil, false, err
+ }
+ return []byte(v), true, nil
+}
+
+// newMaxWired says NewMax's settings have magpie's provider.
+func newMaxWired(path string) bool {
+ app, had, err := newMaxReadApp(path)
+ if err != nil || !had {
+ return false
+ }
+ _, i, err := newMaxProviders(app)
+ return err == nil && i >= 0
+}
+
+// newMaxProviders are the entries of the row's providers as written, and
+// the place of magpie's among them (-1 for none). A row that isn't a JSON
+// object, or whose providers aren't a list, is an error: NewMax would fall
+// back to its defaults on it, and magpie leaves it alone.
+func newMaxProviders(app []byte) (list []json.RawMessage, i int, err error) {
+ i = -1
+ if !json.Valid(app) || !gjson.ParseBytes(app).IsObject() {
+ return nil, i, errors.New("NewMax's settings aren't JSON it reads, so magpie leaves them alone")
+ }
+ raw := gjson.GetBytes(app, "providers")
+ if !raw.Exists() || raw.Type == gjson.Null {
+ return nil, i, nil
+ }
+ if !raw.IsArray() || json.Unmarshal([]byte(raw.Raw), &list) != nil {
+ return nil, i, errors.New("NewMax's providers aren't a list, so magpie leaves them alone")
+ }
+ for j, e := range list {
+ if gjson.GetBytes(e, "id").String() == newMaxID {
+ return list, j, nil
+ }
+ }
+ return list, i, nil
+}
+
+// newMaxEdit changes the `app` row of the database at path with fn, in one
+// transaction that waits on NewMax's own: fn gets the row (nil for none)
+// and gives the new one, nil to take the row out, or the same bytes to
+// leave it as it is.
+func newMaxEdit(path string, fn func(app []byte, had bool) ([]byte, error)) error {
+ if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
+ return errNewMaxNoDB
+ } else if err != nil {
+ return err
+ }
+ u := url.URL{Scheme: "file", Path: filepath.ToSlash(path), RawQuery: "_pragma=busy_timeout(5000)&_txlock=immediate"}
+ if len(u.Path) >= 2 && u.Path[1] == ':' {
+ u.Path = "/" + u.Path
+ }
+ db, err := sql.Open("sqlite", u.String())
+ if err != nil {
+ return err
+ }
+ defer db.Close()
+ db.SetMaxOpenConns(1)
+ ctx := context.Background()
+ tx, err := db.BeginTx(ctx, nil)
+ if err != nil {
+ return fmt.Errorf("NewMax's settings: %w", err)
+ }
+ defer tx.Rollback()
+ var v string
+ had := true
+ switch err := tx.QueryRowContext(ctx, `SELECT value FROM settings WHERE key = 'app'`).Scan(&v); {
+ case errors.Is(err, sql.ErrNoRows):
+ had = false
+ case err != nil:
+ return fmt.Errorf("NewMax's settings: %w", err)
+ }
+ var app []byte
+ if had {
+ app = []byte(v)
+ }
+ out, err := fn(app, had)
+ if err != nil {
+ return err
+ }
+ switch {
+ case out == nil && !had, out != nil && had && bytes.Equal(out, app):
+ return nil
+ case out == nil:
+ _, err = tx.ExecContext(ctx, `DELETE FROM settings WHERE key = 'app'`)
+ default:
+ _, err = tx.ExecContext(ctx, `INSERT INTO settings (key, value) VALUES ('app', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`, string(out))
+ }
+ if err != nil {
+ return fmt.Errorf("NewMax's settings: %w", err)
+ }
+ return tx.Commit()
+}
+
+// newMaxWire puts magpie's provider into the row app and its id into
+// providerOrder, a row made when there is none (NewMax lays its defaults
+// under what a row has, its preset providers too). An entry there already
+// keeps the name and the on/off the user gave it, and the fields NewMax
+// added to it; the row is given back as it was when nothing would change.
+func newMaxWire(app []byte, had bool, want newMaxEntry) ([]byte, error) {
+ if !had {
+ app = []byte("{}")
+ }
+ list, i, err := newMaxProviders(app)
+ if err != nil {
+ return nil, err
+ }
+ b, err := json.Marshal(want)
+ if err != nil {
+ return nil, err
+ }
+ var entry []byte
+ if i < 0 {
+ entry = b
+ } else {
+ // what magpie says, over the entry NewMax keeps
+ var set []jsonKV
+ gjson.ParseBytes(b).ForEach(func(k, v gjson.Result) bool {
+ switch k.String() {
+ case "id", "name", "enabled", "canDelete":
+ default:
+ set = append(set, jsonKV{k.String(), []byte(v.Raw)})
+ }
+ return true
+ })
+ entry = jsonSetKeys(list[i], set)
+ }
+ if i >= 0 && bytes.Equal(entry, list[i]) {
+ entry = nil
+ }
+ if entry != nil {
+ if i >= 0 {
+ list[i] = entry
+ } else {
+ list = append(list, entry)
+ }
+ app = jsonSetKeys(app, []jsonKV{{"providers", joinRaw(list)}})
+ }
+ order, err := newMaxOrder(app)
+ if err != nil {
+ return nil, err
+ }
+ if !containsString(order, newMaxID) {
+ if len(order) == 0 {
+ order = []string{"default"}
+ }
+ ob, _ := json.Marshal(append(order, newMaxID))
+ app = jsonSetKeys(app, []jsonKV{{"providerOrder", ob}})
+ }
+ return app, nil
+}
+
+// newMaxUnwire takes magpie's provider out of the row app, its id out of
+// providerOrder, and a pick of it back to NewMax's default; a row left
+// with nothing but what magpie made goes.
+func newMaxUnwire(app []byte, had bool) ([]byte, error) {
+ if !had {
+ return nil, nil
+ }
+ list, i, err := newMaxProviders(app)
+ if err != nil {
+ return nil, err
+ }
+ if i >= 0 {
+ list = append(list[:i], list[i+1:]...)
+ app = jsonSetKeys(app, []jsonKV{{"providers", joinRaw(list)}})
+ }
+ order, err := newMaxOrder(app)
+ if err != nil {
+ return nil, err
+ }
+ if containsString(order, newMaxID) {
+ var left []string
+ for _, id := range order {
+ if id != newMaxID {
+ left = append(left, id)
+ }
+ }
+ if left == nil {
+ left = []string{}
+ }
+ ob, _ := json.Marshal(left)
+ app = jsonSetKeys(app, []jsonKV{{"providerOrder", ob}})
+ }
+ if gjson.GetBytes(app, "providerId").String() == newMaxID {
+ app = jsonSetKeys(app, []jsonKV{{"providerId", []byte(`"default"`)}, {"model", []byte(`"default"`)}})
+ }
+ // the row magpie made: its empty list and NewMax's default order
+ var rest map[string]json.RawMessage
+ if json.Unmarshal(app, &rest) == nil && len(rest) == 2 && len(list) == 0 &&
+ sameJSON(string(rest["providerOrder"]), []string{"default"}) {
+ if _, ok := rest["providers"]; ok {
+ return nil, nil
+ }
+ }
+ return app, nil
+}
+
+// newMaxOrder is the row's providerOrder; none is empty.
+func newMaxOrder(app []byte) ([]string, error) {
+ raw := gjson.GetBytes(app, "providerOrder")
+ if !raw.Exists() || raw.Type == gjson.Null {
+ return nil, nil
+ }
+ var order []string
+ if !raw.IsArray() || json.Unmarshal([]byte(raw.Raw), &order) != nil {
+ return nil, errors.New("NewMax's providerOrder isn't a list of names, so magpie leaves it alone")
+ }
+ return order, nil
+}
+
+func containsString(list []string, s string) bool {
+ for _, x := range list {
+ if x == s {
+ return true
+ }
+ }
+ return false
+}
+
+// jsonKV is a key of a JSON object and its value, as JSON.
+type jsonKV struct {
+ key string
+ raw []byte
+}
+
+// jsonSetKeys is the JSON object obj with each key of set given its value:
+// one there already in its place, a new one after the rest. Every other
+// byte of obj stays as it is.
+func jsonSetKeys(obj []byte, set []jsonKV) []byte {
+ out := append([]byte(nil), obj...)
+ for _, kv := range set {
+ r := gjson.GetBytes(out, gjsonEscape(kv.key))
+ if r.Exists() && r.Index > 0 && string(out[r.Index:r.Index+len(r.Raw)]) == r.Raw {
+ out = append(append(append([]byte(nil), out[:r.Index]...), kv.raw...), out[r.Index+len(r.Raw):]...)
+ continue
+ }
+ k, _ := json.Marshal(kv.key)
+ end := bytes.LastIndexByte(out, '}')
+ head := bytes.TrimRight(out[:end], " \t\r\n")
+ sep := []byte(",")
+ if bytes.HasSuffix(head, []byte("{")) {
+ sep = nil
+ }
+ var b []byte
+ b = append(b, head...)
+ b = append(b, sep...)
+ b = append(b, k...)
+ b = append(b, ':')
+ b = append(b, kv.raw...)
+ b = append(b, out[end:]...)
+ out = b
+ }
+ return out
+}
+
+// gjsonEscape is key as a gjson path of one key.
+func gjsonEscape(key string) string {
+ var b strings.Builder
+ for _, c := range key {
+ if strings.ContainsRune(`.*?|#@\!=<>%"`, c) {
+ b.WriteByte('\\')
+ }
+ b.WriteRune(c)
+ }
+ return b.String()
+}
+
+// joinRaw is list as one JSON list, written as JSON.stringify writes it.
+func joinRaw(list []json.RawMessage) []byte {
+ return append(append([]byte("["), bytes.Join(func() [][]byte {
+ out := make([][]byte, len(list))
+ for i, e := range list {
+ out[i] = e
+ }
+ return out
+ }(), []byte(","))...), ']')
+}
diff --git a/internal/agent/newmax_test.go b/internal/agent/newmax_test.go
new file mode 100644
index 000000000..75f335f8c
--- /dev/null
+++ b/internal/agent/newmax_test.go
@@ -0,0 +1,380 @@
+package agent
+
+import (
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "regexp"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/yetone/magpie/internal/gateway"
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// newMaxUser is the `app` row as NewMax 1.1.22 saves it: JSON.stringify of
+// its settings, compact, a provider of the user's own, their order and
+// their pick.
+const newMaxUser = `{"providerId":"deepseek","model":"deepseek-chat","theme":"dark","language":"zh-CN","providers":[{"id":"deepseek","name":"DeepSeek","baseUrl":"https://api.deepseek.com/anthropic","apiKey":"sk-u","apiKeys":["sk-u"],"apiKeyRotationEnabled":false,"apiKeyField":"ANTHROPIC_AUTH_TOKEN","apiFormat":"anthropic","models":["deepseek-chat"],"enabledModels":["deepseek-chat"],"enabled":true,"canDelete":true}],"providerOrder":["default","deepseek"],"settingsConfig":{"env":{"FOO":"1"}},"autoUpdate":true}`
+
+// newMaxDB makes NewMax's database at path as it does on its first start:
+// WAL, its settings table, and the row app when one is given.
+func newMaxDB(t *testing.T, path, app string) {
+ t.Helper()
+ os.MkdirAll(filepath.Dir(path), 0o755)
+ db, err := sql.Open("sqlite", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ for _, q := range []string{`PRAGMA journal_mode = WAL`, `CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)`, `INSERT INTO settings (key, value) VALUES ('window', '{"w":1200}')`} {
+ if _, err := db.Exec(q); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if app != "" {
+ if _, err := db.Exec(`INSERT INTO settings (key, value) VALUES ('app', ?)`, app); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+// newMaxRow is the row app as it is now, and whether there is one.
+func newMaxRow(t *testing.T, path string) (string, bool) {
+ t.Helper()
+ b, had, err := newMaxReadApp(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(b), had
+}
+
+// newMaxMagpie is magpie's entry in the row app, checked as NewMax's
+// mergeProviders reads one.
+func newMaxMagpie(t *testing.T, app string) (e newMaxEntry, raw map[string]json.RawMessage) {
+ t.Helper()
+ var doc struct {
+ Providers []json.RawMessage `json:"providers"`
+ }
+ if err := json.Unmarshal([]byte(app), &doc); err != nil {
+ t.Fatalf("not JSON NewMax reads: %v\n%s", err, app)
+ }
+ for _, p := range doc.Providers {
+ var id struct{ ID string }
+ json.Unmarshal(p, &id)
+ if id.ID == newMaxID {
+ json.Unmarshal(p, &e)
+ json.Unmarshal(p, &raw)
+ return e, raw
+ }
+ }
+ t.Fatalf("no magpie entry in %s", app)
+ return
+}
+
+// NewMax (newmax.cc) lists the providers of its settings row in its model
+// picker. magpie adds itself as "magpie-gateway" on the gateway's Anthropic
+// Messages with the key naming NewMax, keeps every other byte of the row,
+// writes nothing when nothing changed, keeps the user's name, off and
+// NewMax's own fields on its entry through a sync, and off gives back the
+// row it found, byte for byte.
+func TestNewMaxProvider(t *testing.T) {
+ home := syncHome(t)
+ t.Setenv("NEWMAX_USER_DATA_DIR", "")
+ if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro", "flash"}}); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { newMaxRunning = func() bool { return false } })
+ newMaxRunning = func() bool { return false }
+
+ a := newMax(home)
+ if !slices.ContainsFunc(All(), func(x *Agent) bool { return x.ID == "newmax" && x.Name == "NewMax" }) {
+ t.Fatal("NewMax is not among the agents")
+ }
+ if a.Path != filepath.Join(home, ".newmax", "newmax.db") {
+ t.Fatalf("path %s", a.Path)
+ }
+ newMaxDB(t, a.Path, newMaxUser)
+ if !a.Detected() {
+ t.Fatal("not found with its data folder")
+ }
+ f := a.Field("provider")
+ if f.Get() != "" {
+ t.Fatalf("get: %q", f.Get())
+ }
+ if err := f.Set(magpieID); err != nil {
+ t.Fatal(err)
+ }
+ if f.Get() != magpieID {
+ t.Fatalf("get after set: %q", f.Get())
+ }
+
+ gw := gateway.URL()
+ app, _ := newMaxRow(t, a.Path)
+ e, _ := newMaxMagpie(t, app)
+ key := agentKeyAt("newmax", gw)
+ if e.BaseURL != gw || strings.HasSuffix(e.BaseURL, "/v1") || e.APIKey != key || !slices.Equal(e.APIKeys, []string{key}) ||
+ e.APIFormat != "anthropic" || e.APIKeyField != "ANTHROPIC_AUTH_TOKEN" || !e.Enabled || e.Name != "magpie" {
+ t.Errorf("entry: %+v", e)
+ }
+ var want []string
+ for _, m := range magpieModels("newmax") {
+ want = append(want, m.ID)
+ }
+ if len(want) < 2 || !slices.Equal(e.Models, want) || !slices.Equal(e.EnabledModels, want) {
+ t.Errorf("models %v enabled %v, want %v", e.Models, e.EnabledModels, want)
+ }
+ // the rest of the row as it was, magpie's entry after the user's and
+ // its id after theirs
+ if !strings.HasPrefix(app, newMaxUser[:strings.Index(newMaxUser, `}],"providerOrder"`)+1]+`,{"id":"magpie-gateway",`) ||
+ !strings.HasSuffix(app, `],"providerOrder":["default","deepseek","magpie-gateway"],"settingsConfig":{"env":{"FOO":"1"}},"autoUpdate":true}`) {
+ t.Errorf("the row around magpie's entry changed:\n%s\n%s", newMaxUser, app)
+ }
+
+ // nothing changed: nothing written
+ if err := a.Sync(); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.Set(magpieID); err != nil {
+ t.Fatal(err)
+ }
+ if again, _ := newMaxRow(t, a.Path); again != app {
+ t.Errorf("rewritten with nothing changed:\n%s\n%s", app, again)
+ }
+
+ // renamed, turned off and tested in NewMax, a model gone from the
+ // list: a sync keeps the user's and NewMax's, and puts the model back
+ at := strings.Index(app, `{"id":"magpie-gateway",`)
+ mine := strings.Replace(app[at:], `{"id":"magpie-gateway","name":"magpie",`, `{"id":"magpie-gateway","name":"My magpie","modelCapabilities":{"x":{"vision":true}},`, 1)
+ mine = strings.Replace(mine, `"enabled":true,"canDelete":true`, `"enabled":false,"canDelete":true`, 1)
+ mine = strings.Replace(mine, `"models":["`+want[0]+`",`, `"models":[`, 1)
+ edited := app[:at] + mine
+ if edited == app || strings.Count(edited, "My magpie") != 1 {
+ t.Fatalf("fixture: %s", edited)
+ }
+ newMaxSetRow(t, a.Path, edited)
+ if err := a.Sync(); err != nil {
+ t.Fatal(err)
+ }
+ app, _ = newMaxRow(t, a.Path)
+ e, raw := newMaxMagpie(t, app)
+ if e.Name != "My magpie" || e.Enabled || string(raw["modelCapabilities"]) != `{"x":{"vision":true}}` {
+ t.Errorf("the user's name, off and NewMax's fields not kept: %s", app)
+ }
+ if !slices.Equal(e.Models, want) {
+ t.Errorf("models after sync %v, want %v", e.Models, want)
+ }
+
+ // picked in NewMax, then off: magpie's entry and id go, the pick goes
+ // back to NewMax's default, and the rest is the row it found
+ newMaxSetRow(t, a.Path, strings.Replace(app, `{"providerId":"deepseek","model":"deepseek-chat",`, `{"providerId":"magpie-gateway","model":"`+want[1]+`",`, 1))
+ if err := f.Set(""); err != nil {
+ t.Fatal(err)
+ }
+ if f.Get() != "" {
+ t.Fatalf("get after off: %q", f.Get())
+ }
+ got, _ := newMaxRow(t, a.Path)
+ if wantOff := strings.Replace(newMaxUser, `{"providerId":"deepseek","model":"deepseek-chat",`, `{"providerId":"default","model":"default",`, 1); got != wantOff {
+ t.Errorf("after off:\n%s\nwant\n%s", got, wantOff)
+ }
+ // and on then off, untouched since, is the row byte for byte
+ newMaxSetRow(t, a.Path, newMaxUser)
+ if err := f.Set(magpieID); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.Set(""); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := newMaxRow(t, a.Path); got != newMaxUser {
+ t.Errorf("on then off:\n%s\nwant\n%s", got, newMaxUser)
+ }
+ // a sync of an entry that isn't there writes none
+ if err := a.Sync(); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := newMaxRow(t, a.Path); got != newMaxUser {
+ t.Errorf("a sync off wrote:\n%s", got)
+ }
+}
+
+func newMaxSetRow(t *testing.T, path, app string) {
+ t.Helper()
+ if err := newMaxEdit(path, func([]byte, bool) ([]byte, error) { return []byte(app), nil }); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// NewMax started once and left at its defaults has no row app: magpie
+// makes one with its entry alone (NewMax lays its defaults and presets
+// under it), and off takes the row out again. Before NewMax has made its
+// database at all, magpie says to open it once.
+func TestNewMaxMakesItsRow(t *testing.T) {
+ home := syncHome(t)
+ t.Setenv("NEWMAX_USER_DATA_DIR", "")
+ t.Cleanup(func() { newMaxRunning = func() bool { return false } })
+ newMaxRunning = func() bool { return false }
+ a := newMax(home)
+ f := a.Field("provider")
+
+ if err := f.Set(magpieID); !errors.Is(err, errNewMaxNoDB) {
+ t.Fatalf("no database: %v", err)
+ }
+ if _, err := os.Stat(a.Path); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("a database made: %v", err)
+ }
+
+ newMaxDB(t, a.Path, "")
+ if err := f.Set(magpieID); err != nil {
+ t.Fatal(err)
+ }
+ app, had := newMaxRow(t, a.Path)
+ if !had || !strings.HasPrefix(app, `{"providers":[{"id":"magpie-gateway",`) || !strings.HasSuffix(app, `}],"providerOrder":["default","magpie-gateway"]}`) {
+ t.Fatalf("row made: %s", app)
+ }
+ newMaxMagpie(t, app)
+ if err := f.Set(""); err != nil {
+ t.Fatal(err)
+ }
+ if app, had := newMaxRow(t, a.Path); had {
+ t.Errorf("row left after off: %s", app)
+ }
+ // NewMax's other rows stay
+ db, closeDB, err := openNewMaxForTest(a.Path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer closeDB()
+ var w string
+ if err := db.QueryRow(`SELECT value FROM settings WHERE key = 'window'`).Scan(&w); err != nil || w != `{"w":1200}` {
+ t.Errorf("window row: %q %v", w, err)
+ }
+}
+
+func openNewMaxForTest(path string) (*sql.DB, func(), error) {
+ db, err := sql.Open("sqlite", path)
+ if err != nil {
+ return nil, nil, err
+ }
+ return db, func() { db.Close() }, nil
+}
+
+// A row NewMax wouldn't read as its settings — not JSON, providers that
+// aren't a list — is left alone, and nothing is changed while NewMax runs,
+// as it writes its settings back over magpie's when one changes.
+func TestNewMaxLeavesAlone(t *testing.T) {
+ home := syncHome(t)
+ t.Setenv("NEWMAX_USER_DATA_DIR", "")
+ t.Cleanup(func() { newMaxRunning = func() bool { return false } })
+ newMaxRunning = func() bool { return false }
+ a := newMax(home)
+ f := a.Field("provider")
+ newMaxDB(t, a.Path, "")
+ for _, bad := range []string{`{"providers":`, `[]`, `{"providers":{"id":"x"}}`, `{"providers":[],"providerOrder":"default"}`} {
+ newMaxSetRow(t, a.Path, bad)
+ if err := f.Set(magpieID); err == nil {
+ t.Errorf("%s: no error", bad)
+ }
+ if got, _ := newMaxRow(t, a.Path); got != bad {
+ t.Errorf("%s: written %s", bad, got)
+ }
+ if f.Get() != "" {
+ t.Errorf("%s: read as on", bad)
+ }
+ }
+
+ newMaxSetRow(t, a.Path, newMaxUser)
+ newMaxRunning = func() bool { return true }
+ if err := f.Set(magpieID); err != errNewMaxRunning {
+ t.Fatalf("set while running: %v", err)
+ }
+ if got, _ := newMaxRow(t, a.Path); got != newMaxUser {
+ t.Errorf("written while running: %s", got)
+ }
+ newMaxRunning = func() bool { return false }
+ if err := f.Set(magpieID); err != nil {
+ t.Fatal(err)
+ }
+ on, _ := newMaxRow(t, a.Path)
+ newMaxRunning = func() bool { return true }
+ if err := f.Set(""); err != errNewMaxRunning {
+ t.Fatalf("off while running: %v", err)
+ }
+ if got, _ := newMaxRow(t, a.Path); got != on {
+ t.Errorf("written while running: %s", got)
+ }
+}
+
+// NewMax's data folder is $NEWMAX_USER_DATA_DIR when it names one, else
+// ~/.newmax, on every system.
+func TestNewMaxDir(t *testing.T) {
+ home := syncHome(t)
+ t.Setenv("NEWMAX_USER_DATA_DIR", "")
+ if got := newMax(home).Dir; got != filepath.Join(home, ".newmax") {
+ t.Errorf("default: %s", got)
+ }
+ d := filepath.Join(home, "nm-data")
+ t.Setenv("NEWMAX_USER_DATA_DIR", d)
+ if a := newMax(home); a.Dir != d || a.Path != filepath.Join(d, "newmax.db") {
+ t.Errorf("set: %s %s", a.Dir, a.Path)
+ }
+ t.Setenv("NEWMAX_USER_DATA_DIR", "rel")
+ if got := newMax(home).Dir; got != filepath.Join(home, ".newmax") {
+ t.Errorf("relative: %s", got)
+ }
+}
+
+// NewMax keeps 20 models of a provider (a primary and 19 back-ups); magpie
+// writes the first 20, so what it wrote and what NewMax saves back agree.
+func TestNewMaxModelCap(t *testing.T) {
+ syncHome(t)
+ var ms []string
+ for i := range 30 {
+ ms = append(ms, fmt.Sprintf("m%02d", i))
+ }
+ if err := provider.Save(provider.Provider{ID: "many", Name: "Many", Chat: "https://api.example/v1", Key: "k", Models: ms}); err != nil {
+ t.Fatal(err)
+ }
+ if n := len(magpieModels("newmax")); n <= newMaxMaxModels {
+ t.Fatalf("fixture: %d models", n)
+ }
+ e := newMaxEntryFor(gateway.URL())
+ if len(e.Models) != newMaxMaxModels || !slices.Equal(e.EnabledModels, e.Models) {
+ t.Errorf("%d models, %d enabled", len(e.Models), len(e.EnabledModels))
+ }
+}
+
+// NewMax runs, for the refusal, when its program does: the Mac app's
+// executable wherever the bundle is (a dmg's volume name has spaces), its
+// helpers, the Linux build's newmax; a shell working in a folder named
+// newmax, or a file of that name in an editor, is not NewMax.
+func TestNewMaxProcess(t *testing.T) {
+ match := func(cmd string) bool {
+ for _, p := range newMaxProc {
+ if regexp.MustCompile(p).MatchString(cmd) {
+ return true
+ }
+ }
+ return false
+ }
+ for _, c := range []struct {
+ cmd string
+ want bool
+ }{
+ {"/Applications/NewMax.app/Contents/MacOS/NewMax", true},
+ {"/Volumes/NewMax 1.1.22-arm64/NewMax.app/Contents/MacOS/NewMax --remote-debugging-port=1", true},
+ {"/Applications/NewMax.app/Contents/Frameworks/NewMax Helper (Renderer).app/Contents/MacOS/NewMax Helper (Renderer) --type=renderer", true},
+ {"/opt/NewMax/newmax --no-sandbox", true},
+ {"/bin/zsh -c cd /Users/me/projects/newmax && go test ./...", false},
+ {"vim /home/me/newmax notes.txt", false},
+ {"/usr/bin/newmaxd", false},
+ } {
+ if got := match(c.cmd); got != c.want {
+ t.Errorf("%q: running %v, want %v", c.cmd, got, c.want)
+ }
+ }
+}
diff --git a/internal/agentenv/agentenv.go b/internal/agentenv/agentenv.go
index 88cc892a2..99e50bb7d 100644
--- a/internal/agentenv/agentenv.go
+++ b/internal/agentenv/agentenv.go
@@ -65,6 +65,8 @@ var Vars = []string{
"QWEN_HOME",
// Ante
"ANTE_HOME",
+ // NewMax's data folder (its newmax.db), ~/.newmax without it
+ "NEWMAX_USER_DATA_DIR",
// AstrBot's root, the folder holding its data/ (else ~/.astrbot, the desktop app's)
"ASTRBOT_ROOT",
// jcode's folder, ~/.jcode without it
diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js
index 6dbc11d8a..26db7be58 100644
--- a/internal/gui/assets/i18n.js
+++ b/internal/gui/assets/i18n.js
@@ -3818,6 +3818,7 @@ const I18N = {
"harness": "harness",
"OpenChamber's project {project} has a default model of its own ({model}), which it uses there instead.": "OpenChamber 的项目 {project} 有自己的默认模型({model}),在该项目里会改用它。",
"OpenPencil reads its settings when it starts and writes them all back when it quits — quit OpenPencil before changing this, then open it and pick a magpie model in its chat's model picker.": "OpenPencil 启动时读取设置、退出时把设置全部写回 —— 请先退出 OpenPencil 再更改这里,然后打开它,在聊天的模型选择器中选一个 magpie 的模型。",
+ "NewMax keeps its settings in memory while it runs and writes them all back when one changes — quit NewMax before changing this, then open it and pick a magpie model in its model picker.": "NewMax 运行时把设置放在内存里,任一设置变化时会全部写回 —— 请先退出 NewMax 再更改这里,然后打开它,在模型选择器中选一个 magpie 的模型。",
"Pencil reads its custom models at start-up — restart Pencil to see magpie's models in its model picker.": "Pencil 启动时读取自定义模型,需重启 Pencil 才能在它的模型选择器中看到 magpie 的模型。",
"Qwen Code reads a session's model at start-up — start a new session, or /model anew, to use this.": "Qwen Code 在会话启动时读取模型,需开启新会话或重新执行 /model 才会生效。",
"Reasonix Studio 2.x and the native 1.39.x/2.x CLI read global settings at startup. Start a new process to load changes. Project/session models can override Executor and Plan.": "Reasonix Studio 2.x 和原生 1.39.x/2.x CLI 在启动时读取全局设置,需启动新进程才会加载改动。项目或会话的模型可以覆盖 Executor 和 Plan。",
@@ -7807,6 +7808,7 @@ const I18N = {
"harness": "harness",
"OpenChamber's project {project} has a default model of its own ({model}), which it uses there instead.": "OpenChamber 的專案 {project} 有自己的預設模型({model}),在該專案裡會改用它。",
"OpenPencil reads its settings when it starts and writes them all back when it quits — quit OpenPencil before changing this, then open it and pick a magpie model in its chat's model picker.": "OpenPencil 啟動時讀取設定、結束時把設定全部寫回 —— 請先結束 OpenPencil 再變更這裡,然後開啟它,在聊天的模型選擇器中選一個 magpie 的模型。",
+ "NewMax keeps its settings in memory while it runs and writes them all back when one changes — quit NewMax before changing this, then open it and pick a magpie model in its model picker.": "NewMax 執行時把設定放在記憶體中,任一設定變更時會全部寫回 —— 請先結束 NewMax 再變更這裡,然後開啟它,在模型選擇器中選一個 magpie 的模型。",
"Pencil reads its custom models at start-up — restart Pencil to see magpie's models in its model picker.": "Pencil 啟動時讀取自訂模型,需重啟 Pencil 才能在它的模型選擇器中看到 magpie 的模型。",
"Qwen Code reads a session's model at start-up — start a new session, or /model anew, to use this.": "Qwen Code 在會話啟動時讀取模型,需開啟新會話或重新執行 /model 才會生效。",
"Reasonix Studio 2.x and the native 1.39.x/2.x CLI read global settings at startup. Start a new process to load changes. Project/session models can override Executor and Plan.": "Reasonix Studio 2.x 和原生 1.39.x/2.x CLI 在啟動時讀取全域設定,需啟動新行程才會載入改動。專案或會話的模型可以覆蓋 Executor 和 Plan。",
@@ -11798,6 +11800,7 @@ const I18N = {
"harness": "ハーネス",
"OpenChamber's project {project} has a default model of its own ({model}), which it uses there instead.": "OpenChamber のプロジェクト {project} には独自のデフォルトモデル({model})があり、そこではそちらが使われます。",
"OpenPencil reads its settings when it starts and writes them all back when it quits — quit OpenPencil before changing this, then open it and pick a magpie model in its chat's model picker.": "OpenPencil は起動時に設定を読み込み、終了時に設定をすべて書き戻します。ここを変更する前に OpenPencil を終了し、その後開いてチャットのモデル選択で magpie のモデルを選んでください。",
+ "NewMax keeps its settings in memory while it runs and writes them all back when one changes — quit NewMax before changing this, then open it and pick a magpie model in its model picker.": "NewMax は実行中に設定をメモリに保持し、設定が変わるたびにすべて書き戻します。ここを変更する前に NewMax を終了し、その後開いてモデル選択で magpie のモデルを選んでください。",
"Pencil reads its custom models at start-up — restart Pencil to see magpie's models in its model picker.": "Pencil は起動時にカスタムモデルを読み込みます。モデル選択に magpie のモデルを表示するには Pencil を再起動してください。",
"Qwen Code reads a session's model at start-up — start a new session, or /model anew, to use this.": "Qwen Code はセッション開始時にモデルを読み込みます。反映するには新しいセッションを始めるか、もう一度 /model を実行してください。",
"Reasonix Studio 2.x and the native 1.39.x/2.x CLI read global settings at startup. Start a new process to load changes. Project/session models can override Executor and Plan.": "Reasonix Studio 2.x とネイティブの 1.39.x/2.x CLI は起動時にグローバル設定を読み込みます。変更を読み込むには新しいプロセスを起動してください。プロジェクトやセッションのモデルが Executor と Plan を上書きすることがあります。",
@@ -15789,6 +15792,7 @@ const I18N = {
"harness": "Harness",
"OpenChamber's project {project} has a default model of its own ({model}), which it uses there instead.": "Das OpenChamber-Projekt {project} hat ein eigenes Standardmodell ({model}), das dort stattdessen genutzt wird.",
"OpenPencil reads its settings when it starts and writes them all back when it quits — quit OpenPencil before changing this, then open it and pick a magpie model in its chat's model picker.": "OpenPencil liest seine Einstellungen beim Start und schreibt sie beim Beenden alle zurück – OpenPencil vor dieser Änderung beenden, dann öffnen und in der Modellauswahl seines Chats ein magpie-Modell wählen.",
+ "NewMax keeps its settings in memory while it runs and writes them all back when one changes — quit NewMax before changing this, then open it and pick a magpie model in its model picker.": "NewMax hält seine Einstellungen während der Ausführung im Speicher und schreibt sie bei jeder Änderung alle zurück – NewMax vor dieser Änderung beenden, dann öffnen und in seiner Modellauswahl ein magpie-Modell wählen.",
"Pencil reads its custom models at start-up — restart Pencil to see magpie's models in its model picker.": "Pencil liest seine eigenen Modelle beim Start – Pencil neu starten, um magpies Modelle in seiner Modellauswahl zu sehen.",
"Qwen Code reads a session's model at start-up — start a new session, or /model anew, to use this.": "Qwen Code liest das Modell einer Sitzung beim Start – eine neue Sitzung beginnen oder /model erneut ausführen, damit es gilt.",
"Reasonix Studio 2.x and the native 1.39.x/2.x CLI read global settings at startup. Start a new process to load changes. Project/session models can override Executor and Plan.": "Reasonix Studio 2.x und die native 1.39.x/2.x-CLI lesen globale Einstellungen beim Start. Einen neuen Prozess starten, um Änderungen zu laden. Projekt- oder Sitzungsmodelle können Executor und Plan überschreiben.",
@@ -16026,6 +16030,7 @@ const NOTICES = [
"Kiro Crew's config.local.json sets its harness (agent.acp_backend), and that wins over config.json, so magpie leaves it alone: set it there to a harness connected to magpie.",
"OpenChamber's project {project} has a default model of its own ({model}), which it uses there instead.",
"OpenPencil reads its settings when it starts and writes them all back when it quits — quit OpenPencil before changing this, then open it and pick a magpie model in its chat's model picker.",
+ "NewMax keeps its settings in memory while it runs and writes them all back when one changes — quit NewMax before changing this, then open it and pick a magpie model in its model picker.",
"Pencil reads its custom models at start-up — restart Pencil to see magpie's models in its model picker.",
"Qwen Code reads a session's model at start-up — start a new session, or /model anew, to use this.",
"Reasonix Studio 2.x and the native 1.39.x/2.x CLI read global settings at startup. Start a new process to load changes. Project/session models can override Executor and Plan.",