Commit Graph
12 Commits
Author SHA1 Message Date
yetone 4d1ec346aa edit: a JSON file is made plain JSON once a read, not on every look
GetJSON, GetJSONRaw and GetJSONItem copied the file and ran jsonc.ToJSON
over it on every look. The window's polls look up agent settings many
times a round, so twenty polls allocated 80 MB in that conversion alone
(heap profile of a real-account sandbox).

jsonHeld keeps the plain-JSON bytes in filememo, keyed by the file's
mod time and size, so a look reads them shared. gjson.GetBytes copies
what it returns, so nothing a caller gets aliases the held bytes. A
write (SetJSON and the rest) changes the file, and the next look reads
it again.

TestGetJSONConvertsTheFileOnce: a 290 KB JSONC file with a BOM, 20
looks must each allocate under a tenth of the file, and a value set
afterwards is seen. Red on the old code: 296 KB a look.

Run at this head:
- mote: go vet (darwin, GOOS=windows, GOOS=linux) ok; go test
  ./internal/edit ok, and ok under -race.
- WSL (magpie-desktop): internal/edit ok, internal/provider ok;
  internal/agent red only in TestInstalledVersion, TestHowInstalled,
  TestGrokInstalled, TestCursorFolderFromTheEditorIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI and
  TestOmpDetectedWithPiDir, the install-detection reds of #4033.
2026-11-01 04:04:50 +08:00
yetone f02390544d edit: a JSONC delete takes the last member's trailing comma, so the MCP hub never leaves OpenCode's mcp as {,}
chenxiang0010 (Discord #general, Windows): turning the Library's MCP hub on
for OpenCode and off again left a comma at the end of opencode.jsonc's
"mcp", and OpenCode said "opencode.jsonc: invalid"; deleting the comma by
hand fixed it, and a second try didn't reproduce.

Cause: delJSONBytes looked for the deleted member's trailing comma in the
tidwall/jsonc copy, which blanks every comma before a closing bracket.
So when the member was the last one and had a trailing comma (as OpenCode,
editors and users allow), the comma was left behind; when it was the only
member, it was left with nothing before it: "mcp": {\n,\n}. The hub sync
then inserted the magpie entry in front of it ("magpie": {...},\n,) — a
double comma. OpenCode parses with jsonc-parser allowTrailingComma
(packages/opencode/src/config/parse.ts at v1.19.5, packages/core/src/config.ts
on dev): a trailing comma after a value is fine, a lone one is an error.
magpie's own validity check went through the same tidwall copy, so it
passed the broken file. Once the comma was deleted by hand there was no
trailing comma left, which is why it didn't happen again.

- delJSONBytes takes the last member's own trailing comma (nextToken, as
  delItem already did for arrays), and its line with trailing blanks.
- insertKey adds no comma after the first member of an object that holds
  comments only (it used to, leaving a trailing comma only some apps read).
- edit.ValidJSONC reads JSONC as jsonc-parser with allowTrailingComma does.
  SetJSON, DelJSON, PatchJSON, SetJSONItem and DelJSONItem refuse an edit
  that would turn a file the app reads into one it can't (checkJSONC):
  nothing is written, and the error names the file.
- A lone comma an older magpie left is dropped by the next object edit of
  that file (dropLoneCommas), so users already hit are mended by the next
  sync that writes it. A file nothing writes again keeps it until then.

Every JSON/JSONC object writer goes through SetJSON/DelJSON/PatchJSON
(library MCP for OpenCode, Zed, VS Code, Claude, etc., agent wiring for
DevEco, MiMo Code, OpenCode, ...), so all of them get it.

Tests (red on the old json.go/jsonarray.go, put back by hand, green now):
- TestHubToggleLeavesValidJSONC: 12 file shapes (LF, CRLF, tabs, compact,
  trailing commas, comment-only, comment after, comma after a comment) x 7
  add/delete orders; old code: invalid in the trailing-comma and
  comment-only shapes.
- TestDelOnlyMemberTakesItsTrailingComma, TestInsertIntoCommentOnly-
  ObjectNoTrailingComma, TestLoneCommaMendedOnNextEdit: red on old code.
- TestValidJSONC, TestInvalidEditNotWritten.
- internal/library TestHubToggleKeepsOpenCodeJSONCValid: the real
  SetMCPHub on/off twice for OpenCode, LF and CRLF; old code: invalid at
  the first "hub on" ("magpie": {...},\n,\n}).
2026-10-29 09:33:11 +08:00
yetone 5160809d2e agent: a catalog sync's round looks at each file once; a write reads the disk (#1665)
A catalog sync asked about each agent's files many times a round
(GetJSON, GetTOMLTop, settings.load from each agent's Sync): on Windows
an empty sandbox's start stat'ed settings.json 1065 times and
config.toml 569 in 25s, almost all from SyncCatalog. Each round now
holds what was read (filememo.Hold), as the GUI's read-only requests and
the gateway already do.

What a hold serves may be up to a second old, so nothing is written from
it any more:
- edit.Read, which every Set*/Del* helper and the agents' own
  read-modify-write code start from, looks at the disk even under a
  hold (filememo.ReadNow). The getters (GetJSON, GetJSONRaw,
  GetJSONItem, GetEnvFile, GetYAMLTop, the YAML getters, GetTOMLTop's
  line reader) read through the hold.
- settings: a write's load under fileMu (lockFile) reads the disk too.
Before this, a GUI request's hold could already hand a Set* stale
bytes; that is closed as well.

WriteAtomic forgot every held file even when it left the file as it
was, and a sync writes each agent's files each round, almost always
unchanged: it now forgets only after a real write.

Measured on xiaomi-gpu (Windows 11), as in the steady commit before
this one (second start, 27s, stats counted by an uncommitted build):
  before          2307 stats, sync 1318 of them, round 1308ms
  this alone      1787 stats, sync  864,          round 1273ms
  with steady's    988 stats, sync   96,          round   96ms
First start of an empty sandbox: 2448 stats before, 1041 after.

Run:
- TestHeldReadIsNotWhatAWriteIsMadeFrom (json, toml, yaml),
  TestUnchangedWriteKeepsWhatIsHeld, TestHeldSettingsAreNotWhatAWriteIsMadeFrom:
  with edit.Read and the settings write load put back on the held read
  and WriteAtomic's Forget removed by hand, json and yaml lost the other
  app's key, the settings case wrote "light" over "dark", and the
  forget case went red; green with the change, on mote.
- mote, at the pushed head: gofmt -l internal clean; GOOS=linux/windows/
  darwin go vet of steady, edit, filememo, settings and agent clean;
  go test -count=1 of steady, edit, filememo, settings, agent, provider,
  catalog and library ok; internal/gui red only on TestMainWindowCorners
  (#3949, macOS 27, red on main before this).
- xiaomi-gpu: go test of edit, filememo and settings ok.
2026-10-28 13:43:37 +08:00
yetone 79fec406c6 agent, gui: a Claude Code provider switch (CLAUDE_CODE_USE_BEDROCK, …) steps aside while magpie is wired in and comes back after; one magpie can't take out is said (jw1dev on X)
jw1dev's ~/.claude/settings.json had CLAUDE_CODE_USE_BEDROCK=1. magpie wrote
ANTHROPIC_BASE_URL and its model ids beside it. Bedrock ignores the base URL,
so Claude Code went to AWS, Bedrock refused magpie's model, and magpie still
showed Claude Code as connected.

Claude Code 2.1.300's six switches (agentenv.ClaudeProviders: BEDROCK,
VERTEX, FOUNDRY, ANTHROPIC_AWS, ANTHROPIC_GOOGLE_CLOUD, MANTLE; on = 1, true,
yes or on, any case, trimmed):
- In a settings file magpie writes (user settings, WSL twins), a switch
  that is on is taken out on every route that writes the wiring: connect,
  model pick and Rewire/Reapply through writeTiers, and Sync. Its raw JSON
  value is stashed (claude.cloud.<var>, under the distro id for WSL). It is
  put back as written when magpie steps out (Disconnect, or the model set
  back to default), unless the user set it again since. AWS_*/GCP
  variables and a switch that is off stay.
- Where magpie doesn't write it (managed settings, ~/.claude.json's env,
  the login shell's env), Check names the variable, the cloud and the
  file. It reads them in Claude Code's own order: managed wins, then the
  user's settings, then ~/.claude.json, then the shell. Two notice
  templates, translated in zh, zh-TW, ja and de. The row's line and its
  Reconnect pill now show a drift detail through tNotice.
- proc.LoginEnv reads the switches but never sets them in magpie's env,
  and testenv unsets them.
- T3 Code: a switch is never carried onto magpie's instance. Its Check
  says when the user's ~/.claude settings have one on. That Check first
  checks the instance's ANTHROPIC_BASE_URL against the gateway (t3EnvOf),
  as every agent's Check must for TestDriftUnwiredEveryAgent,
  TestPortMovesEveryAgent and TestReverseProxyIsStillMagpie.
- Claude Desktop's Code tab runs with CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST,
  under which Claude Code ignores these switches in settings, so nothing
  changes there.

Run:
- gofmt -l: clean.
- go vet: native ./..., GOOS=linux -tags nogui, GOOS=windows: clean.
- go test -tags nogui ./...: every package ok except internal/agent, where
  t3code's first Check (cloud only) failed the three every-agent tests
  above. Fixed with the wiring check, then the whole internal/agent package
  was rerun: ok (368s).
- GUI, Chromium and WebKit, 102/102 each: new claude-cloud-drift (5
  languages, 1100 and 420px, file and shell notices), gui-de, gui-ja,
  gui-zh-tw, i18n-keys, agent-notice-lang, agent-proxied,
  agent-unreachable, cli-behind, menu-scroll, agent-connect,
  agent-disconnect.
- Sandbox HOME (scratchpad dir, live ~/.claude untouched):
  - Setup: real claude 2.1.300 with settings.json
    {CLAUDE_CODE_USE_BEDROCK:"1", AWS_REGION, AWS_PROFILE}, a magpie-cloud
    binary from this tree serving on 127.0.0.1:3487, a fake OpenAI
    upstream on 3486.
  - `magpie claude fake/fake-model` took the switch out and stashed "1".
  - `claude -p "say hi"` printed PONG-FROM-FAKE-UPSTREAM, and the fake
    logged POST /v1/chat/completions model=fake-model.
  - `magpie claude default` left settings.json byte-for-byte the same as
    before connect (cmp).
  - Control: the switch put back by hand beside the wiring (the reported
    state). Claude Code never reached magpie: the fake logged nothing.

Broken by hand, each went red:
- no dropClouds in writeTiers, then in Sync;
- putClouds returning at once, and putClouds writing over the user's own;
- no claudeCloud in Check;
- the T3 filter and the T3 Check;
- shellVars without ClaudeProviders;
- the tNotice calls taken out of the line and pill: claude-cloud-drift
  went 17 red.

Not tried:
- A project's .claude/settings.json(.local) isn't read, because magpie
  doesn't know where Claude Code runs.
- WSL and Windows were not run for real; tests only.
- Real Vertex, Foundry and AWS accounts.
- T3 Code and Claude Desktop with a switch, run for real.
- The drift shown in the real app window. The CLI has no drift output.
- The user's own ANTHROPIC_MODEL being lost across connect/disconnect is a
  separate gap, fixed in its own commit.
2026-10-15 07:41:30 +08:00
yetone 6536982756 edit: an agent's config saved with a UTF-8 BOM is edited through it and keeps it — magpie claude <model> no longer says "invalid JSON/JSONC" (#1534, AnxForever)
On Windows, PowerShell 5.1's `Set-Content -Encoding UTF8`, Notepad and
Claude Code channel switchers save ~/.claude/settings.json with a UTF-8
BOM in front. Claude Code reads such a file; magpie's JSON layer handed
the BOM to json.Valid and gjson, so `magpie claude <model>` failed with
"<path>: invalid JSON/JSONC" and the agent couldn't be wired at all. TOML
refused the same with "UTF-8 BOM is not supported", though Codex's own
parser (toml_parser's lexer) skips a BOM, and env/YAML files glued the BOM
to their first key's name.

The fix is at the package's two choke points, so every format and every
caller of edit.Read gets it:
- edit.Read returns the file without a leading BOM (the agent package's
  own readers, Claude Desktop, Ante, Empryo, Snow, Pi MCP etc. go through
  it).
- WriteAtomic puts the BOM back when the file it replaces starts with one
  and the new bytes don't (keepBOM). The user's file keeps the encoding it
  was saved in: the tools that wrote it may expect it, and the agent read
  it with the mark before, so keeping it is the user's own bytes, not a
  guess. A file without a BOM never gets one; an emptied file stays empty.
  This is what astrbot.go already did for AstrBot's cmd_config.json.
- PatchJSON (bytes in, bytes out) reads through and keeps a BOM too.
- The TOML "BOM is not supported" error is gone with the case it named.
- Siblings read outside edit.Read: Claude Code's settings.json and CC
  Switch's legacy config.json in the importer, and Crush's provider list,
  trim it with the new edit.TrimBOM.
- Prime Agent's Disconnect (beforeMagpie.restore, on main since this
  work began) compares the file with its copy from before through the
  BOM, so a BOM'd settings.json is put back byte for byte and the copy
  removed; it used to stay as magpie left it, the copy beside it.

The reporter's fork commit (AnxForever/magpie 0bb750c1) was reviewed: it
trimmed the BOM in the seven JSON entry points and wrote the file back
without it; this change keeps the BOM instead and covers TOML, YAML, env
and the readers outside the JSON layer.

Run:
- New tests built on a Windows-shaped settings.json (BOM + CRLF + the
  user's env and permissions): TestJSONSettingsWithBOM, TestPatchJSONKeepsBOM,
  TestJSONItemWithBOM, TestTOMLConfigWithBOM, TestEnvAndYAMLWithBOM fail on
  the old code ("invalid JSON/JSONC", nothing found) and pass; with keepBOM
  disabled by hand four of them go red. TestWriteAtomicAddsNoBOM.
  TestPrimeAgentRoundTripWithBOM fails on main (not put back) and passes.
  TestClaudeConfigDirImport (BOM case) and TestImportCCSwitchConfigWithBOM
  fail on the old importer ("invalid character 'ï'") and pass.
- Full chain in a sandbox HOME: old binary `magpie claude
  deepseek/deepseek-flash` on a BOM'd settings.json -> "invalid
  JSON/JSONC"; new binary -> "✓ Claude Code model", BOM and CRLF kept, the
  user's env untouched; `magpie claude model default` after it leaves no
  blank line. Old `magpie codex gpt-5.5` on a BOM'd config.toml -> "UTF-8
  BOM is not supported"; new -> set, BOM kept.
- Windows box: the edit package's test binary passes whole; magpie.exe
  `claude deepseek/deepseek-flash` on a settings.json written by
  PowerShell 5.1 Set-Content -Encoding UTF8 (sandboxed USERPROFILE/APPDATA)
  sets the model and keeps ef bb bf.
- go test -tags nogui ./internal/edit ./internal/agent ./internal/provider
  ./internal/library; gofmt -l; go vet (darwin, GOOS=linux, GOOS=windows)
  on the touched packages; the full suite.
2026-10-11 05:43:45 +08:00
yetone 947dc24aa3 edit: a key or array element taken out of a CRLF JSON file takes its whole line, no blank line left behind (found on #1534)
DelJSON, PatchJSON's deletes and DelJSONItem cut a member that sits on a
line of its own together with that line's end, but only looked for a bare
\n after it. In a file with \r\n line ends (a Windows settings.json,
VS Code's chatLanguageModels.json) the \r stopped the line end from going,
so each set-then-delete left one more blank \r\n line, e.g. magpie
connecting and disconnecting Claude Code. pastLineEnd now takes \r\n or \n.

Found while writing #1534's round-trip test on a CRLF settings.json.

Run: TestDelJSONTakesCRLFLine and TestDelJSONItemTakesCRLFLine fail on the
old code (a "\r\n\r\n" left where the key was) and pass now;
go test -tags nogui ./internal/edit/ passes.
2026-10-11 05:41:46 +08:00
Alex 2d9db1b60d edit: malformed JSON configs stay untouched when agents connect (#1242)
Validate the complete comment-stripped document before object and array edits, including previews. Regression tests fail on the old implementation because edits and VS Code Connect succeed and alter malformed files. Targeted edit and VS Code tests pass in an isolated HOME.
2026-10-08 11:52:20 +08:00
Junjie Zhou 4a97acf12a refactor(agent): separate Aside provider connection from model settings (#827)
* refactor(agent): connect Aside as a native provider with verified settings

* fix(agent): offer explicit offline Aside model and disconnect actions

Offer Save for next start after an initial runtime read failure, using a
structured API error instead of saved runtime state. Keep refusals and
failed readbacks on the live error path.

Add a separate offline disconnect confirmation that restores the checked
file plan, clears restore records and removes the provider last. Bind the
confirmation to its preview revision and roll back ordinary write failures.

Cover offline API and browser flows, cancellation, stale plans, missing
CLI, restore metadata and native provider spelling. Keep state file-only.
2026-10-05 14:37:44 +08:00
Charan Rathore 6b0a44ea7d edit: keep a CRLF file's line endings when JSON members are added or replaced (#830)
SetJSON splices new lines into the file with \n. In a JSON or JSONC file saved with \r\n (VS Code on Windows does that), a member added to an object or a nested value came back with a bare \n among the \r\n lines. SetJSON of "b" on "{\r\n  \"a\": 1\r\n}\r\n" gave "{\n  \"b\": 2,\r\n  \"a\": 1\r\n}\r\n".

The result is written back through keepCRLF, which turns every line break into \r\n when the original used \r\n for all of them. Untouched lines already carry their \r, so only the added lines change; a file that mixed endings is written as before.

TestSetJSONKeepsCRLF fails on the old code; TestSetJSONKeepsMixedEndings pins that a mixed file is left alone. go vet and go test ./internal/edit pass here and on current main with this merged.
2026-10-05 04:29:55 +08:00
yetoneandClaude Opus 5.5 a370877ca4 agents: VS Code's built-in chat (Copilot Chat) — switched on, magpie's models join Chat's model picker as a Custom Endpoint group in chatLanguageModels.json, with no key to enter and no Copilot sign-in needed (wani on Discord: 可以添加vscode自带的agent的配置吗)
VS Code Stable takes other vendors' models through its Custom Endpoint provider since 1.122 (customoai, the older OpenAI Compatible one, is Insiders only), signed in to GitHub or not. The provider groups live in chatLanguageModels.json beside settings.json in the default profile's User folder (~/Library/Application Support/Code/User, ~/.config/Code/User, %APPDATA%\Code\User), a JSONC array VS Code watches. magpie adds {"vendor":"customendpoint","name":"magpie","apiType":"chat-completions","models":[...]} with each catalog model at the gateway's /v1/chat/completions, toolCalling true (agent mode lists only tool-calling models), vision, contextWindow and maxOutputTokens (capped at a quarter of the window, as VS Code keeps the output budget out of the prompt's), and the model's efforts as supportsReasoningEffort. A group's apiKey is a secret property that VS Code reads from its secret storage only (languageModels.ts _resolveConfiguration), so it can't be written to the file; each model instead sends Authorization: Bearer magpie in requestHeaders, which CustomEndpointOAIEndpoint lets through and which stops it sending its own key header. The model a new chat starts on is chat.defaultModel in settings.json (matched by model id, so the catalog id); its old value is stashed and put back. The group is the agent's Joined: picking one of VS Code's own (auto) keeps magpie's models listed, and switching off (Unwire) takes the group out and puts chat.defaultModel back. Sync rewrites the group as the catalog changes, Check says when its url or header no longer reach the gateway, the Notice says where the models are and to reload the window if they don't show, and requests are credited to it by GitHubCopilotChat/<version>, a User-Agent a model's headers can't change.

internal/edit: SetJSONItem/GetJSONItem/DelJSONItem edit one element of a JSONC file's top-level array, found by its members, keeping comments, trailing commas and the other elements; SetJSON/DelJSON take a backslash-escaped dot as part of a key, as gjson does, for VS Code's flat "chat.defaultModel".

TestVSCode (connect keeps the user's settings and groups with their comments, the group's url/header/toolCalling/window and no apiKey or discovery url, Sync, Check, an own model keeping the group, disconnect back to the user's last own model), TestVSCodeRoundTrip (on and off leaves both files byte for byte; no files at all) and TestVSCodeUA; TestJSONItem, TestDelJSONItemAmongOthers and TestJSONEscapedDot. go vet ./internal/..., go build -tags nogui ./..., GOOS=windows and GOOS=linux builds pass; go test of internal/agent, edit, usage and gateway (each sandboxes HOME in TestMain) and internal/gui's page and agent connect tests pass; the full go test under a temp HOME was not run (the sandbox refused the HOME override). No GUI code changed (the generic connected wording fits), so no webkit test. VS Code itself is not installed here: not tried against a real VS Code.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 08:23:38 +08:00
TryWorld f24e41178d fix(edit): keep JSONC inserts out of leading comments (#639) 2026-10-03 13:32:58 +08:00
yetoneandClaude 0a234ce41d dial: one dial for every coding agent's model
Wails v3 tray panel and window, TUI and CLI. Switches model, effort and
provider for Claude Code, Codex, Gemini CLI, OpenCode, Pi, Goose, Cursor,
Copilot CLI and Crush with format-preserving config edits. Providers page
and registry, stored keys, live vendor model lists, profiles.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-09-22 21:47:29 +08:00