Commit Graph
2027 Commits
Author SHA1 Message Date
yetone fe61503e60 provider: a Remote magpie whose computer took another address is found on the network
luckymanjc (Discord) uses computer A's magpie from computer B over the
LAN. A's router hands it a new DHCP address after a boot, and B's Remote
magpie, saved at the old one, reached nothing until the address was
typed in again.

When B can't connect to a Remote magpie at all (a dial error, not an
answer), the list fetch (models.go) and the gateway's request (forward
in gateway.go) now call provider.SeekMoved (remote_moved.go). It dials
every address of the old one's /24 and of up to four of B's own private
/24s at A's port (500ms each, 128 at once). The first that lists
/v1/models 200 for the provider's key, and whose list this magpie didn't
make (magpie_via), is A: a LAN caller always needs a gateway key, so
another magpie answers 401. That address is saved as the provider's and
the request is made again there. A name or a public address is never
looked around, an address the user changed meanwhile stands, and a
provider is looked for once a minute at most, callers at once sharing
one look.

Run:
- mote-run go test -count=1 -run 'TestRemoteMagpie|TestLANNeighbours|TestDialable|TestRemoteSelf' ./internal/provider ./internal/gateway: ok
- mote-run go vet, GOOS=windows and GOOS=linux go vet of both packages: ok; gofmt -l clean
- Live: A was a real magpie on mote (10.0.0.121:3511), B a -tags nogui
  build in WSL magpie-desktop (127.0.0.1:3522), sandbox HOMEs. B's
  provider was saved at the dead 10.0.0.250:3511. B's start fetch found
  A ("found at 10.0.0.121:3511, saved there") and a chat answered 200 in
  4.2s. Then, with B running, the address was set dead again: a request
  to office/group/rot found A and answered 200 in 4.4s, saved at .121.

Broken by hand, each red: the gateway hook off (502), the fetch hook off
(fetch error), the self check off (saved at this magpie itself).

Not tried: a real Windows A; a mDNS name (.local) that changed address
(left to the name); A on a different /24 than B. On Linux a dial to a
dead LAN address took ~54s (no route to host) before the look starts;
not changed here.

Reported-by: luckymanjc. (Discord)
2026-11-06 18:11:41 +08:00
yetone 49c9491b73 update: the Windows app asks where to install, the first time
The Windows exe opened from Downloads (or the Desktop, or temp)
installed itself into %LOCALAPPDATA%\Programs\magpie without a word.
Now, the first time, with nothing installed yet, Windows' task dialog
asks "Install magpie in this folder?". It shows the folder and offers
Install, Change… and Cancel, in the tray's language (en, zh, zh-TW,
ja, de).

- Change… opens the system folder picker. A picked folder gets
  "magpie" added unless it is already named that (update.InstallDir).
- A folder other than the default is recorded at HKCU\Software\magpie
  InstallLocation. So the next exe downloaded replaces the copy there
  in place and asks nothing (installed(), forwards()).
- Cancel runs the exe where it is, as a portable copy, and nothing is
  recorded.
- Uninstall forgets the record (update.ForgetInstallDir, a new System
  step).
- The shortcut, App Paths, autostart, magpie://, the PATH entry and
  self-update already take the running exe's folder, so they follow
  the choice.

Program Files and other folders only an administrator can write to
are refused in the dialog (update.Installable test-writes and maps a
permission error to ErrNeedsAdmin). They are not elevated into.
magpie installs per user (HKCU Run, the user's PATH), and its
self-update replaces the exe without elevation (CanElevate is false on
Windows). So an admin folder would make every update fail, or would
need a UAC prompt on each one. A downloads folder is refused too.
Refusing is the simplest correct choice: it costs a user nothing they
had before, and keeps updates silent. Any folders the test-write made
are removed again.

Docs: gui-shell.md, "Where Windows installs magpie".

Run (mote, at this head on origin/main f9e6061b8):
- gofmt -l is clean.
- go build ./... and go vet of update, uninstall and gui.
- GOOS=windows go vet of gui, update and uninstall.
- GOOS=windows GOARCH=arm64 go build ./....
- GOOS=linux go vet -tags nogui of the same packages.
- go test -count=1 ./internal/update ./internal/uninstall, and
  -run TestInstallWords|TestTrayLang ./internal/gui: ok.

Run (win-run, xiaomi-gpu):
- internal/uninstall ok, and gui TestInstallWordsEveryLanguage ok.
- internal/update: one red, TestPackagedByDpkg. It is red on
  origin/main too: an NTFS stream from the fixture name
  magpie:amd64.list (#4603).

Real Windows 11 run (xiaomi-gpu, a sandbox USERPROFILE/LOCALAPPDATA
under C:\Users\yeton\magpie-idir, MAGPIE_ADDR on 3481, exe in its
Downloads, driven over UI Automation and TDM_CLICK_BUTTON):
- The dialog came up in Chinese, with the app icon and the default
  folder.
- Change… → C:\Program Files was refused with the administrator note
  and the warning icon, and no folder was left behind. C:\Windows was
  refused the same way.
- Change… → …\Tools gave …\Tools\magpie. Install put magpie.exe and
  magpie.com there, and the app ran from there.
- Afterwards InstallLocation, the user's PATH, App Paths and
  magpie:// all named …\Tools\magpie. `magpie version` from a fresh
  PATH resolved to …\Tools\magpie\magpie.com. `magpie autostart on`
  wrote Run = "…\Tools\magpie\magpie.exe" tray.
- Upgrade: a 0.1.9001 build downloaded into Downloads asked nothing.
  It replaced …\Tools\magpie\magpie.exe (FileVersion 0.1.9001) and ran
  from there.
- `magpie uninstall --yes` removed autostart, App Paths, the scheme
  and the record, and deleted the sandbox data. The next exe asked
  again.
- Cancel ran the exe from Downloads and recorded nothing.
- The registry and folders were put back as they were before the run,
  checked by a snapshot diff.

Broken by hand:
- recordedDir's lookup turned off: TestSettleInstallsWhereTheUserChose
  and TestSettleOffersTheChosenFolderAgain went red.
- AskFolder skipped: those two and TestSettleDeclinedRunsHere went red.

Not tried:
- The in-app self-update download. There is no newer release to
  download; the in-place replace path was run with a downloaded exe.
- The en, ja, de and zh-TW dialogs on screen. Their words are checked
  by TestInstallWordsEveryLanguage only.
- arm64 Windows.
- A Downloads folder moved by OneDrive.
- The Start-menu shortcut. The box's real App Paths already held
  another session's magpie, so shortcut.ensure took the shortcut as
  removed by the user. This is existing behaviour.

Not changed: uninstall still leaves the PATH entry and the exe, as
before for every install (#5500). Related to #2663, which asks for a
first-run choice of where magpie lives.

Reported-by: feng_21795_78266 (Discord)
2026-11-06 17:34:48 +08:00
yetone f9e6061b85 claude: claude-magpie runs Claude Code through magpie, a plain claude left on the user's account
baranwang on X (11-06): `claude` stays on the user's own Claude account,
`claude-magpie` goes through magpie, and nothing is switched back and
forth.

`claude-magpie` runs `magpie claude run [args…]`. That writes a settings
file of magpie's own, <config>/claude-launch/settings.json, connected as
Connect connects Claude Code (the gateway, its key, the shared LAN key when
sharing is on, the model, the tiers) and starts
`claude --settings <file> args…`. Claude Code puts a --settings file's env
and model over the user's settings.json, a claude.ai sign-in and the
shell's variables (tried on 2.1.318), so ~/.claude/settings.json is never
rewritten. ANTHROPIC_API_KEY and the cloud switches (Bedrock, Vertex…) are
blanked in the file, so neither the user's file nor the shell can take a
request past magpie. The file is the agent `claude#launch`, listed nowhere:
the Agents page, Check and Notice see only the user's file. It is set again
when the gateway moved or its key changed.

- /model in a claude-magpie session saves to the user's settings.json
  (Claude Code never writes a --settings file). After the session a magpie
  model picked there moves into the launch file, for the next claude-magpie,
  and the user's file gets its model back. A Claude alias (sonnet) stays.
- Claude Code's own one-time `opus` -> `opus[1m]` rewrite of the user's
  file (migration_opus_to_opus1m), which the launch file's 1M opus tier sets
  off, is undone the same way. Found in the end-to-end run below.
- claude runs as a child so that can happen: on Unix a stopped child stops
  magpie too (^Z, fg; proc.WaitFollowingStops reaps it with WUNTRACED, as
  cmd.Wait can't see a stop), and claude's exit code is magpie's. On Windows magpie
  ignores Ctrl+C while claude has it.
- The command: a launcher beside the `magpie` command. Settings › Command
  line (AddCLI) writes it; `magpie claude launcher [add|remove]` adds it for
  a command put there before. It is a `#!/bin/sh` exec of magpie's stable
  path, or on Windows a .cmd running "%~dp0magpie". A file by that name
  without "written by magpie" is never written over.
- Docs: agent-wiring.md, and the start page in en/zh/ja.

Run at this commit (rebased on origin/main 218b38c59):
- mote: gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build for darwin, linux (nogui), windows;
  go test ./... -timeout 45m: 85 packages ok; red only
  TestMainWindowCorners (#3949) and TestRenewLoginsKeepsClaudeReading
  (#5481), both red alone on origin/main b020ae102. The run before at
  f22a9ae61 also had proc's TestEveryStartedCommandIsWaited red on this
  change's own Wait4 loop, fixed here by moving it into proc.
- Windows (xiaomi-gpu): go test ./internal/update ./internal/cli: cli ok;
  update red only in TestPackagedByDpkg, red the same on origin/main
  f47390bf3, filed as #4603.
- Real Claude Code 2.1.318 in WSL (magpie-desktop), sandbox HOME, a built
  magpie (`serve` on its own port), a fake Anthropic upstream:
  - `magpie claude run -p "say hi"`: PONG, exit 0; upstream got
    claude-opus-4-6 with the provider's key. A user settings.json with its
    own ANTHROPIC_API_KEY and "model": "opus" kept both values.
  - Interactive in tmux under bash -i: `/model fakeco/glm-4.6` then /exit:
    the user's file is back on opus, the launch file on fakeco/glm-4.6.
    ^Z stops both magpie and claude (T), fg resumes both.
  - `magpie claude launcher add` wrote ~/bin/claude-magpie, and running it
    answered PONG.
- Real Claude Code 2.1.281 on Windows: claude-magpie.cmd beside a built
  magpie.exe, `claude-magpie --version` printed the version through
  `claude --settings <launch file>`, exit 0.

Broken by hand, each red: the blanks dropped; the launch dir override; the
stale-address check; ClaudeLaunchAfter returning early; the opus[1m]
rewrite check; WaitFollowingStops answering 0 for a signal; "$@" turned into $* in the launcher; the model mark check;
AddCLI's launcher loop; --settings dropped from the args; the restore call
dropped.

Not tried: macOS with a real Claude Code (the Unix path ran in WSL only);
Windows interactive (Ctrl+C, /model restore); a real Claude subscription or
API key upstream (a fake upstream only). Known limits: a session that ends
by a crash or kill skips the restore; managed settings (policy) outrank
--settings; magpie has to be running (claude-magpie warns when it isn't);
Claude Code itself reformats the user's settings.json when it runs its
opus migration, values kept.
2026-11-06 17:31:04 +08:00
yetone 11df525f06 gateway: only the vendors seen to hide an overflow have a bare failure told as too long (#5486)
NEKO-CwC asked, after v0.1.3141, why a custom API-key Responses relay's
400/413/422 is still turned into context_length_exceeded when the relay
never said so. It shouldn't be. tooLongUnsaid read any provider's
400/413/422 that said nothing of length, for a request 1.2 times past the
model's window, as "prompt is too long". That rule came from three
vendors' refusals in b3ab3e42e (v0.1.735, 10-03): Devin's 502 "capacity
issues", Qoder's 400 "Error in upstream response" and WorkBuddy's 400
"Invalid request parameters". #711 (v0.1.808) then kept the 413 case for
Factory's byte cap. 978284dd6 (v0.1.3141) had already scoped the 5xx to
Devin. The 4xx half still applied to every provider.

Now:
- unsaidStatus lists who gets the inference, keyed by the id of the
  plugin that serves the vendor (all of them are retired as built-ins),
  never by the provider's id, which a user's own provider can share:
  devin 500/502/503/504; qoder, qoder-cn, workbuddy, workbuddy-ai
  400/413/422; factory 413. unsaidOverflows replaces busyOverflows.
- Every other provider's failure reaches the client with its own status
  and words: custom and by-address providers, API-key relays, OpenAI,
  Anthropic, other plugins. Transport failures are never inferred
  (unchanged since 978284dd6).
- An upstream that says it overflowed (tooLongRe, overflow codes) is
  still passed on as an overflow. A 400/422 whose own words say the
  request is too long (saysLength, #4420) is still read past half the
  window for any vendor, because the vendor named the cause.
- The single call site in serve runs for every client route (Responses,
  Codex's /responses, Chat, Messages) and every upstream protocol, held
  or streamed, before anything is sent. Mid-stream SSE errors were never
  inferred.

Tests:
- TestRelayFailureKeepsItsOwnWords (new, 126 subtests): a custom relay
  speaking Responses, Chat or Messages answers 400 "Invalid request
  parameters", 400 "Error in upstream response", 413, 422 or (Responses)
  502/503 to a request past 1.2 of its window. Asked through
  /v1/responses (held and streamed), Codex's /responses, /v1/chat
  (held and streamed) and /v1/messages (held and streamed), the client
  gets that status and the relay's words, with no context_length_exceeded.
- TestUnsaidVendorsStillOverflow (new): each listed vendor and status,
  under its own id and a -plugin id, is told as too long past the
  window and left alone within it. Another vendor's plugin, and a user
  provider named like the vendor, are not. Statuses a vendor wasn't seen
  to use are not.
- TestQoderPluginUnsaidOverflow (new): through the fake plugin moved as
  qoder, end to end.
- TestOverflowTheVendorDidntSay's 400/413 rows now expect the vendor's
  status and words. TestPayloadTooLargeIsNotContextOverflow and
  TestRegionRefusalIsNotTooLong use Factory's and WorkBuddy AI's plugin.
  TestWindowNotBelowWhatWasAnswered and TestWindowNotBelowListedMax now
  use a length-words 400, the one path a generic provider still has.

Broken by hand, on mote:
- the old fallback.go (origin/main) with the new tests: 84 of
  TestRelayFailureKeepsItsOwnWords' subtests red (every 4xx one; the
  5xx ones were already fixed by 978284dd6), and
  TestUnsaidVendorsStillOverflow, TestOverflowTheVendorDidntSay and
  TestPayloadTooLargeIsNotContextOverflow red;
- unsaidOverflows returning false: TestUnsaidVendorsStillOverflow,
  TestQoderPluginUnsaidOverflow, TestDevinBusyOverflowStillTooLong,
  TestPayloadTooLargeIsNotContextOverflow and
  TestRegionRefusalIsNotTooLong red;
- keyed by p.ID instead of the plugin: TestUnsaidVendorsStillOverflow
  (user provider named like the vendor) and
  TestDevinBusyOverflowStillTooLong (devin-plugin) red.

Run (mote-run, at this tree): gofmt -l clean; go vet ./internal/gateway
for darwin, GOOS=linux and GOOS=windows ok; go test -count=1 -timeout 45m
./internal/gateway: ok (809s) at base be5e8f29f. Rebased onto e8df78f33 (two routing commits touched gateway.go and trace.go), then at the pushed tree: go vet ok and the overflow, too-long, payload, window and response-id tests ok (14s).

Not tried: a real relay, or real Devin, Qoder, WorkBuddy or Factory
accounts, against this change. A vendor not listed that hides an overflow
behind a bare 400 now hands the agent that 400 rather than compacting; it
gets added to unsaidStatus when it is seen.

Reported-by: NEKO-CwC (GitHub), ne9ko9 (Discord)
2026-11-06 17:25:04 +08:00
yetoneandFlandern1211 e8df78f33e routing: a dsh fork's requests are named by the reply its client was given (#5491)
dsh's chat and messages routes send no session id, so Routing and Context
found a dsh session by the hash of the conversation's opening. A fork
repeats its source's opening, so every request the fork made showed under
the source, and the fork's name never appeared.

Flandern1211's patch, ported:
- The gateway keeps the id of the reply it gave the client
  (Route.ResponseID). It is set from clientResponseID in the same update
  that marks the route done, so a poll that sees Done also sees the id,
  with no race against the usage ledger. When magpie translates, it is
  the id after translation, e.g. chatcmpl-…, not the upstream's msg_….
- sessions reads dsh's replayState.response.responseId into
  Session.ResponseIDs. Only main files are read, only replies served by
  the gateway, and only the fork's own replies after its session/end-seed
  (seedLength for version 1).
- Routing (pricedRoutes) and Context (joinConvs) look up a finished
  request by its reply id first, then by its opening. A request logged
  before this keeps the opening's session.

Changed from the patch:
- A reply id names a session over the opening only when the opening is
  that session's own, or a session it was forked from, or the opening is
  unknown. Vendors' ids can repeat: an encoder keeps the upstream's id,
  and Ollama's is chatcmpl-<0..999>. Without the guard, two unrelated
  conversations could swap names. Session.ForkOf comes from the fork
  header's parentSession, isSeeded and delegationDepth 0, which is how
  dsh's buildForkSeed writes it. ownerOf walks that chain, so a fork of a
  fork works too.
- Poll cost: dsh never writes down some reply ids (a title call, a
  refused turn). Under the patch, each such id made Routing list every
  session again every 2s, for as long as the route was on the page. Now
  an id is waited for only up to a minute (convsKept) after its request
  ended (looseKeys). After that the regular one-minute rebuild covers it.
- A page whose loose routes carry only a reply id still builds the map
  (looseRoute).
- The patch's synthetic fork headers gain parentSession, as dsh writes
  them.
- docs/subsystems/gateway-routing.md describes the reply-id join.

Tests:
- TestDshForkNamedByTheReplyTheGatewayGave sends dsh 0.2.0-rc.2's real
  captured completions request (testdata/dsh-gateway) through
  gateway.New() twice, to an Anthropic-only upstream, so the reply is
  translated. It writes the source's real session file with the first
  client id, and a fork shaped like dsh's buildForkSeed output with the
  second. It then checks that pricedRoutes and contextOf put each request
  under its own session, and an old route without an id under the source.
- TestDshForkOfARealSessionListsItsOwnReplies forks the real fixture
  session: the fork lists only its own reply and ForkOf, the source
  keeps [c1].
- TestDshReplyIDOfAnotherConversationNamesNoOne covers the guard.
- TestRoutingWaitsForAReplyIDOnlyAWhile covers the poll bound.
- The patch's own tests: TestDoneRouteKeepsTheClientResponseID (json and
  stream), TestDshResponseIDs*, TestRoutingTellsAForkByItsReply,
  TestContextTellsAForkByItsReply.

Run on mote (mote-run), at this tree on origin/main be5e8f29f. The vet and
go test lines below were run again after rebasing on e6b9d1199, which
changed only the README and library (ok):
- gofmt -l internal/ printed nothing.
- go vet ./internal/... . is clean.
- GOOS=linux go vet -tags nogui and GOOS=windows go vet of
  internal/{sessions,gui,gateway} are ok.
- go test ./internal/sessions ./internal/gateway ./internal/gui -run
  'Dsh|ResponseID|Fork|Routing|Context|Conv' -count=1: ok.
- GUI: routing-by-key, routing-ctx-sessions, routing-request-metrics,
  routing-sessions, routing-session-folder, sessions-empty-range,
  ctx-route, context-map and panel-routing pass in chromium (120/120)
  and webkit (120/120).

Broken by hand, each red, then restored:
- guard off: TestDshReplyIDOfAnotherConversationNamesNoOne;
- poll bound off: TestRoutingWaitsForAReplyIDOnlyAWhile;
- end-seed keeps the inherited reply ids: TestDshResponseIDsSkipTheSeed,
  TestDshResponseIDsEndSeedAcrossReads and
  TestDshForkOfARealSessionListsItsOwnReplies;
- ForkOf not set: TestDshForkOfARealSessionListsItsOwnReplies,
  TestDshForkNamedByTheReplyTheGatewayGave,
  TestRoutingTellsAForkByItsReply and TestContextTellsAForkByItsReply;
- gateway keeps no id: TestDoneRouteKeepsTheClientResponseID and
  TestDshForkNamedByTheReplyTheGatewayGave.

Not tried:
- a real dsh fork against a running magpie. The session shapes come from
  the real rc.2 fixture and dsh's fork source.
- A request still running, or a failed one, still shows under the source
  until it has a reply id. The patch says the same.
- Delegated subagent files (delegationDepth > 0) are not read for reply
  ids; they stay under their parent as before.
- Not changed: the gateway's turn clock (sessionTurnKey) also falls back
  to the opening's hash, so a fork and its source running at once share
  one. Filed as #5496.

The full suite runs after the push.

Co-authored-by: Flandern1211 <163982805+Flandern1211@users.noreply.github.com>
Reported-by: flandern1211_58540 (Discord)
2026-11-06 17:22:52 +08:00
yetone b020ae1022 agent: Claude Desktop 4.23118.0's gateway window still has no Chinese (xwoffice)
xwoffice on Discord: "Claude Desktop 接入以后界面会变成英文 取消了又恢复成中文".
Nothing changes in behaviour; this records that the cause is still
Desktop's, in the newest release too.

On magpie, Desktop runs in its 3p mode, whose window is its bundled UI.
Read from Desktop 4.23118.0 (darwin RELEASES.json currentRelease,
published 11-05, downloaded and unpacked, not run):
- Resources/ion-dist.asar's i18n has en-US de-DE fr-FR ko-KR ja-JP es-419
  es-ES it-IT hi-IN pt-BR id-ID, no zh. Its supported list in
  assets/v1/shared-99 and shared-67 is the same 11, and the window maps
  navigator.languages onto them, else en-US, then calls
  electronIntl.requestLocaleChange with that pick on mount.
- app.asar's resources/frame/shell/i18n/frame-shell has the same 11.
- app.asar's resources/i18n has zh-Hans and zh-Hant, for the signed-in
  (claude.ai) window only. So disconnecting brings Chinese back.
magpie carries the signed-in "locale" into Claude-3p/config.json
(desktopCarryLocale), but Desktop writes its own pick over it at every
start. Nothing magpie can write keeps Chinese there, and magpie doesn't
patch Anthropic's signed app. Chinese readers are told so on the
Agents row and in the switch-on notice since v0.1.2123 (4b4c4a806).

Changed: desktopCarryLocale's comment and docs/subsystems/agent-wiring.md
name 4.23118.0 among the versions read.

Run: gofmt -l internal/agent/claudedesktop.go clean. Comment and doc
only, so no build, test or tag.
Not tried: starting a real Desktop 4.23118.0 in 3p mode; the mechanism
is from its shipped code. Windows' 4.23118.0 bundle not read.

Reported-by: xwoffice (Discord)
2026-11-06 16:35:54 +08:00
yetoneandMmx233 ff415f39cb gateway: a compaction refused for an input kind it doesn't take is asked again as text (#5181, #5259)
Command Code's /responses takes messages, function calls, their outputs
and reasoning only. A Codex subagent's compaction carries agent_message,
custom_tool_call and compaction_trigger items, and Command Code answered
400 unsupported_input_item (param input). codexCompact didn't count that
as a reason to ask again with the conversation as text, so the 400 went
back to Codex three times and compactFails held the conversation for
5 minutes.

inputKindRefused now asks again as text on unsupported_input_item or
"unknown item type" (Grok's 422) in a 400, 422 or 502 (another magpie in
front wraps it), or in a stream's error / response.failed event. A 401,
403 or 429 with the same words still goes back as it came. itemText
reads an agent_message as the user's turn, so the subagent's task and
follow-ups are in the text summary and in the local one.

No plugin change: the Command Code plugin passes /responses through, and
the fallback covers it direct, through a remote magpie and in a stream.

Run (mote):
- go test -run 'TestCodexCompact|TestCodexCompacts|AgentMessage' ./internal/gateway: ok
- go test -timeout 45m -count=1 ./internal/gateway: ok (809.6s)
- gofmt -l clean; go vet ./internal/gateway native, GOOS=linux -tags
  nogui and GOOS=windows: ok
Broken by hand:
- origin/main's codex_backend.go: every AsksAgainAsText subtest red
  (400 / 502 back to Codex).
- agent_message case removed: the text lacks the subagent's task.
- status guard loosened: the 401/403/429 test red.
Not tried: a real Command Code account (the keys on this machine are
answered 401), the reporters' own sessions; why the compaction reached
/responses rather than chat is not confirmed.

Reported-by: Mmx233 <36563672+Mmx233@users.noreply.github.com>
Reported-by: Edward4226 <Edward4226@users.noreply.github.com>
Reported-by: mahiro233 (Discord)
Co-authored-by: Mmx233 <36563672+Mmx233@users.noreply.github.com>
2026-11-06 16:04:03 +08:00
yetone 0ad0f42411 gateway: Ollama's options reach no Chat upstream, so Hermes Agent's requests to Mistral are not turned away (lijiho96940561 on X)
Hermes Agent pointed at magpie (provider "custom", base URL on this
machine) probes the server as Ollama: detect_local_server_type GETs
/api/tags, which magpie answers in Ollama's shape for VS Code's Copilot,
and the body has "models", so it is "ollama". agent_init_ollama.py then
asks /api/show for the model's context and the custom profile sends it as
extra_body {"options": {"num_ctx": N}} on every chat request
(plugins/model-providers/custom/__init__.py, NousResearch/hermes-agent
90d6b98f). magpie relayed that top-level options to Mistral as it came,
and Mistral's chat API forbids extra fields: 422 extra_forbidden on
["body","options"] for every request. Mistral's own request model
(mistralai/client-python d3da3bd, ChatCompletionRequest) has no options;
it does take reasoning_effort "medium", the other field Hermes adds.

9a4eaab82 (#3097) left options out for Gemini's OpenAI-compatible API
only and kept it for every other vendor. No Chat API reads it, Ollama's
own /v1 included (openai.ChatCompletionRequest has no Options), so every
relayed Chat body now goes without its top-level options
(withoutOllamaOptions), as the Ollama route's own builder already leaves
the runner settings out (ollamaChatBody). The cut is withoutTopMember's,
every other byte as it came: the old withoutFields re-encoded the whole
body through a map, which would have reordered every tool schema of any
request whose text says "options". A body without the word is not
parsed. Groq, which Hermes' own comment names as strict too, and every
other vendor get the same body. /api/tags and /api/show are left
answering in Ollama's shape: VS Code's and Visual Studio's Copilot need
them, and a client can't be told from Hermes there.

Run (mote, at this commit): go test ./internal/gateway -timeout 45m:
ok (812.7s). go vet ./internal/gateway, GOOS=linux GOARCH=amd64
-tags nogui and GOOS=windows GOARCH=amd64 go vet ./internal/gateway
clean; gofmt -l clean.
Red without the fix: with the withoutOllamaOptions line taken out,
TestHermesOllamaOptionsNeverReachMistral fails with Mistral's fake 422
extra_forbidden on options, and TestChatRelayLeavesOutOllamaOptions with
options reaching both Gemini and Kimi. With withoutFields(body,
"options") in its place, the new test fails on the tools not going
byte for byte.
Not tried: a real Mistral key (none at hand; api.mistral.ai answers 401
before it validates the body) and a real Hermes run (it rewrites the live
~/.hermes launcher under a temp HERMES_HOME); the field and the refusal
are from Hermes' and Mistral's own source, the 422 shape from #494/#393.
2026-11-06 16:03:41 +08:00
yetone 4c8e1cfdfc providers: a Remote magpie's MCP servers go to the Library only when switched on, and follow its rename
treeman_26897 (Discord) on v0.1.3127's bridge MCP auto-discovery:

- Renamed (name and id), a Remote magpie's auto-added MCP server went:
  adoptBridges keyed it on the provider id, and after provider.Rename
  that id is gone, so the server was taken out as the provider's. Now
  RemoteHub carries the provider's Was, and adoptBridges moves the
  server's bridge, bridgesOn and bridgesOffered from an id it had to
  the id it has (one that another provider has now stays that one's).
  The server keeps its name.
- The add dialog had only the address and key. A new Remote magpie's
  editor has a Name and an ID under the key; blank, they are the
  preset's as before (provider.Add numbers them when taken), and the
  ID follows the name until one is typed.
- Adding its MCP servers is opt-in: a switch, "Add its MCP servers to
  the Library", in the add dialog (off) and in a saved one's editor.
  It lives in library.json (bridgesOn); /api/providers says it as
  libraryMCP and the save takes it (library.SetRemoteMCP). On asks the
  remote at once (provider.AskRemoteHub) when no model list is fetched
  on that save; off takes its server out. Only one switched on is
  asked (bridgeWanted). A server auto-added before this (no bridgesOn)
  is kept, and its switch shows on. A server removed in the Library
  turns its switch off; the provider gone takes its switch with it.

Run (mote, at this tree):
- go test ./internal/library ./internal/provider ./internal/gui:
  library ok; provider ok but TestRenewLoginsKeepsClaudeReading
  (#5481, red the same at the base); gui ok but TestMainWindowCorners
  (#3949). The first gui run had TestCoreScriptBudget red (app.js
  over by ~1.2KB); the new code was made compact and seven editor
  comment blocks cut to one line each. Rebased on 09812e66b the core
  was 68 bytes over again, so three more comments near the editor
  (decidesModel, modelAPIs, pickedOf) were cut: app.js is 161 bytes
  smaller than at its base, and the budget (not raised) passes there:
  go test -run 'TestCoreScriptBudget|Provider' ./internal/gui ok.
- go vet ./..., GOOS=windows go vet ./..., GOOS=linux go vet -tags
  nogui ./...: ok; gofmt -l clean.
- node --test remote-magpie (chromium + webkit, en + zh), i18n-keys,
  i18n-en-no-cjk, gui-de, gui-ja, gui-zh-tw, preset-name,
  name-suffix-remote, remote-self, provider-unmasked, key-row-chips-fit,
  ctx-head-narrow, routing-remote-windows, usage-remote-cards,
  old-webkit: all
  green except reds that are red the same at the base 1ccad582d and
  filed: remote-magpie's "asks for the other magpie's address" fails
  at its decision-model chips before reaching anything this changes
  (#5013, #4398), and i18n-keys' "a plugin's words are its own"
  (#5332, #5426, #5482). With that one chips assertion bypassed in a
  local copy, remote-magpie's new assertions are 12 of 12 green.
  name-suffix-remote went red in Chromium (zh, zh-TW, de) beside 10
  other files, its scrollends.js import failing (#5147); alone it is
  10 of 10 green. The switch's label in the editor is the existing
  "MCP servers".

Broken by hand:
- the Was mapping off: TestRemoteMagpieMCPFollowsRename red ("renamed
  home, read before a sync: switch map[]").
- bridgeWanted/adoptBridge not asking bridgesOn: TestRemoteMagpieMCPIsOptIn
  red ("switched off, asked").
- the new editor's switch defaulting on: remote-magpie red ("off when
  added") in both engines.

Not tried: a real rename against a real second magpie (the library
tests fake RemoteHubs; the provider test renames a real providers.json
in a sandbox and checks Was reaches RemoteHubs). The CLI (provider
add/set remote-magpie) and the TUI have no switch: from there a new
Remote magpie gets no MCP server until it is switched on in the GUI.

Reported-by: treeman_26897 (Discord)
2026-11-06 15:41:43 +08:00
yetone ee91d86ea0 provider: a custom provider can be held to HTTP/1.1, and a TLS record error on HTTP/2 moves its host there
kepner_53726 (Discord, magpie 0.1.2926): a custom Anthropic provider at a
company intranet gateway failed 124 turns in 3 days mid-stream with "tls:
bad record MAC" / "received record with version eaf1", each a 200 with 0
output tokens, until a restart; a plain Go 1.26.8 client to the gateway held.

Cause: none found in magpie. The bytes are read by stdlib crypto/tls, and
every conn wrapper on the path only passes them through, so a record whose
MAC fails was mangled before it reached us: by the gateway or a box between
(the system proxy route, a TLS-inspecting middlebox). HTTP/2 meets it far
more than one-off clients do: one long-lived connection carries every
stream, plus magpie's health pings (netproxy.HTTP2Health), so a gateway
that interleaves its writes racily breaks it.

- Provider.HTTP1 ("HTTP version" row, "HTTP/1.1 only" tick, under the
  editor's Advanced; shown for a provider of the user's own at an https://
  address, the same set InsecureTLS takes). Via adds netproxy.WithHTTP1 for
  its own base URLs' hosts; Dispatch sends those over its HTTP/1.1 copy.
  Another host, and a request made for another provider (With), keep HTTP/2.
  Save refuses it on a preset's; a save that leaves the key out keeps it.
- With no setting: a TLS record error read on an HTTP/2 reply (h2Watch) or
  round trip marks the host:port, and Dispatch speaks HTTP/1.1 to it for 6
  hours. Go's transport already drops the broken connection. Zero-config
  default otherwise unchanged.
- Advanced opens by itself when the tick is set. No note under the row
  (the core script budget, not raised).

Run (mote, at 1ccad582d plus this; budget and these tests again at a10ad0ec8 plus this): gofmt -l; go vet of netproxy,
provider, gui; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet
./...; go test -tags nogui -run 'HTTP1|RecordError|H2Record|InsecureTLS|
Dispatch|With|Budget|I18n' over netproxy, provider and gui, ok;
TestCoreScriptBudget ok after trimming. GUI: provider-http1 (new, 60 of 60,
chromium+webkit, 5 languages, 1100/420), provider-insecure-tls,
provider-advanced-fold, editor-advanced-align, provider-limit-rest,
i18n-en-no-cjk pass. i18n-keys "a plugin's words are its own" is red on
three plugin strings this change doesn't touch (library, routing, usage).

TestH2RecordErrorMovesHostToHTTP1 mangles a real TLS stream through a TCP
relay that flips a byte, and checks the next request goes over HTTP/1.1.

Not broken by hand yet; not tried against a real company gateway, or in
the real app window.

Reported-by: kepner_53726 (Discord)
2026-11-06 15:24:18 +08:00
yetone 1ccad582d8 library: a skill the user has in ~/.agents/skills under another folder or with other files is not given a second time
math_milian (Discord #feedback, 11-06) still saw skills twice after
d487aaab7. That commit kept the library's link out of a reader's own
folder only when ~/.agents/skills held the same files under the same
folder name. Pi, Codex, Gemini, Kimi Code and the other readers of that
folder still got a second copy when the user's entry there:
- had other files (an update through `npx skills`, a local edit), or
- sat under another folder name with the same SKILL.md name (Pi goes by
  the frontmatter name; real Pi 1.4.0 warns `name "hunk-review"
  collision` for both cases with magpie's link beside it, and loads the
  user's alone with no diagnostics once the link is gone).

readSharedOwn/sharedOwn.rival now finds the user's entry by folder
name or SKILL.md name. A same-tree one counts as the library's (as
before). A differing one gets no second copy: it raises the Own problem
("{agent} already has a skill of its own called X"), whose Use the
library's sets the shared entry aside with the backups and gives the
link, and whose Keep {agent}'s unticks it. Agents that don't read the
folder (Claude Code) keep their link. Old users' second links go on
the next sync (the GUI syncs at start), through the existing unlink.

TestKimiSweepLeavesTheUsersOwnSharedSkills and TestSkillsWhereShared
assumed a differing same-name user skill gave the library's again;
they now expect the Own problem and no second link.

Run (mote, at this tree on cd9c52c16):
- go test -tags nogui -count=1 ./internal/library ./internal/cli
  ./internal/gui: ok
- GOOS=linux/windows go vet -tags nogui ./internal/library, go vet: ok;
  gofmt -l clean
- win-run: TestSharedCopy*, TestSharedOwn*, TestSkillsWhereShared,
  TestKimiSweep*: ok
- probe in a sandbox HOME, skill ticked for claude, codex, pi, gemini,
  opencode: same tree / other files / other folder name / shared link
  elsewhere; before, the last-but-one two gave pi, codex, gemini a
  second entry; after, none (OpenCode merges ~/.claude/skills with
  ~/.agents/skills by id, so it never shows two)
- real Pi 1.4.0 loader on mote for the two cases, before and after

Broken by hand:
- rival matching same-tree only: TestSharedCopyNotGivenTwice and
  TestSharedOwnSettled red
- readSharedOwn keyed by folder name only: TestSharedCopyOtherFolderName
  red (.pi, .codex, .gemini still have a second one)

Not tried: the reporter's own tree (asked for), the real GUI's Use/Keep
buttons on this problem, WSL/Linux runs, a Pi or omp of unknown version
(still given its own, in docs' Not covered).

Reported-by: math_milian
2026-11-06 15:04:01 +08:00
yetone cd9c52c16e library: a Remote magpie's MCP router is a Library server of its own
With another magpie as a provider (preset remote-magpie), its router's
MCP servers took adding that same magpie again under Library -> MCP.
Now the gateway's info (GET /v1) says "mcp_hub": true to a caller it
serves MCP to while its router is on with a server that isn't itself
another magpie's router. A fetch of a Remote magpie's models asks that
info with the provider's key, only while the library would still give
it a server, and the library then adds one: named for the provider,
http at <root>/mcp/magpie/hub with Authorization: Bearer <key>, kept to
this computer (local), on for the agents given the hub's entry.

- Offered once (bridgesOffered in library.json): removed or switched
  off by the user, it stays so until the provider is removed and added
  again.
- A server the user already has at that magpie's router (same origin,
  the router's path) is the one; none is added beside it.
- The provider removed takes its server out (adoptBridges, at Sync and
  the View read); providers.json unreadable takes nothing out; the
  provider's address or key changed changes the server's; edited to
  another address or key it becomes the user's own (keptBridge).
- No loop: every dial to a URL under /mcp/magpie/hub carries
  X-Magpie-Router, and a request with it is given no such server,
  neither listed (library Tools, gateway hubServersOf) nor run (Call,
  hubToolNamed). A server carried in by sync is never a bridge.
- No GUI change: it is a server row as any other.

Run (mote, at base 1c45645b5):
- gofmt -l clean; go vet ./internal/{gateway,library,provider} on
  darwin, GOOS=windows, and GOOS=linux -tags nogui: ok.
- go test ./internal/gateway -run 'TestHubLeavesRemoteRouterToARouter|
  TestInfoSaysMCPHub|TestHubMCP'; ./internal/provider -run
  'TestRemoteHubNoted|TestRemoteSelf'; ./internal/library -run
  'TestRemoteMagpieRouter|TestCarriedServerIsNoBridge|TestPluginTools|
  TestHub': ok.
- Real two-magpie run on mote: a built binary, two sandbox HOMEs /
  XDG_CONFIG_HOMEs, B on 3512 with a python stub provider and a stub
  HTTP MCP server behind its router, A on 3513 with B as a Remote
  magpie. After `magpie sync` on A, A's library.json had home-magpie
  (http://127.0.0.1:3512/mcp/magpie/hub, Bearer key, bridge home) and
  bridgesOffered [home]; A's /mcp/magpie/hub listed
  home-magpie__stubmcp__echo and tools/call returned the stub's echo;
  A asked with X-Magpie-Router listed nothing (loop guard); B asked
  with it still listed its own stubmcp__echo.

Broken by hand, each red: the Tools filter, the Call filter, the router
header in remoteHeaders, the same-origin dedup, offered-once, the
unreadable-providers keep, the key refresh, keptBridge, putServers'
carried reset, hubServerOf's Bridge, the gateway's hubServersOf, the
gateway's header -> ctx, info's non-bridge check, fetch's hook, the
older-magpie check and the this-magpie check.

Not tried / not handled:
- The real run was over loopback; a LAN remote's key check is covered
  only by the existing TestHubMCPRemoteEntryNeedsKey path.
- The provider's own extra headers (a proxy's) aren't carried to the
  server; a remote with several keys is asked with p.Key.
- A remote whose router is turned off later keeps its server (it lists
  no tools).
- A server the user added by hand at another magpie's router now sends
  X-Magpie-Router too, so that router leaves out its own Remote
  magpies' servers for it.
- Windows and Linux test runs (vet only).

Reported-by: treeman_26897
2026-11-06 14:33:18 +08:00
yetoneandskygunner dd2be65656 gateway: a Responses request translated to Mistral carries its thinking as parts, not reasoning_content (#4906)
Codex on /v1/responses with a DeepSeek-named model served at Mistral
(preset mistral or api.mistral.ai, here deepseek-v4-1-flash-1017) broke
after its first tool call: the Chat build replays an earlier turn's
thinking in reasoning_content for any model whose name says DeepSeek,
wherever it is served (chatReplaysReasoning keys on the name), and
Mistral answers that field with 422 extra_forbidden. The #494 fix
converted it to Mistral's typed thinking part (mistralThinking) only on
the Chat passthrough route, so /v1/chat/completions on the same provider
answered 200 while every follow-up on /v1/responses was refused.

forwardTranslated now runs mistralThinking on the body built for a
Mistral upstream, with the same gate the relayed route uses. Other
upstreams keep the #1462 replay (a DeepSeek at DeepSeek still gets
reasoning_content), and the relayed route is unchanged.

MystryMocha's nit: a whitespace-only thinking (the " " placeholder the
replay gives a tool turn with no reasoning item) is now dropped instead
of being sent as a blank thinking part. This applies to the relayed
route too; Mistral accepts the dropped field (MystryMocha's raw table).

Ported from skygunner's 29b0ea308 (branch
fix/4906-mistral-translated-reasoning), on origin/main 1c45645b5.
Edward4226's 0b8aee26f was an independent fix of the same shape.

Run (all through mote-run, at this tree):
- gofmt -l internal/gateway docs: empty
- go test -tags nogui ./internal/gateway -count=1 -timeout 45m: ok (894.9s)
- GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...,
  go vet ./..., go build: ok
  Run at this change on 1c45645b5, then rebased onto 3f53fa1f3; the
  two commits between (763ea9438, 3f53fa1f3) touch GUI CSS, webfonts.js
  and GUI tests only, nothing Go.

Broken by hand:
- forwardTranslated's mistralThinking call taken out:
  TestTranslatedReasoningAsThinkingForMistral red with the reporter's
  422 at messages[1].assistant.reasoning_content ("I should read
  note.txt with the tool."), and the new
  TestTranslatedToolTurnWithoutReasoningForMistral red with the same
  422 on the " " placeholder.
- TrimSpace reverted to think == "": only
  TestTranslatedToolTurnWithoutReasoningForMistral red ("the call was
  given a blank thinking part").

Real use: not tried here, no Mistral key. MystryMocha ran skygunner's
29b0ea308 on main a92cc3f3 (Windows/amd64) against the real Mistral API
and in real Codex Desktop on mistral/deepseek-v4-1-flash-1017: a
12-minute session of many tool calls with no 422, and turn 2 and a tool
turn without a reasoning item 422 on main, 200 with the fix. The
TrimSpace change on top of it was not run against the real API; per the
same report, Mistral answers 200 with the field dropped.

Co-authored-by: skygunner <84759+skygunner@users.noreply.github.com>
2026-11-06 14:21:27 +08:00
yetone 1c45645b59 plan: a Mistral Studio key shows the organization's API month, not the Vibe month (dhanyqaz on Discord)
8216592a8 (v0.1.3109) read vibe_budget from api.mistral.ai/v1/billing/budget
for every key on api.mistral.ai. That budget is the organization's, not the
key's: a Vibe key and a Studio key made in the console of one organization
are told the same body, so dhanyqaz's Studio key (Student plan) showed the
Vibe month, 149.36 / 150, and "All 2 accounts" added the two into 298.72 /
300.

Which budget a key spends is its kind. Mistral's Vibe CLI asks
console.mistral.ai/api/vibe/whoami (plan_type CHAT, API or MISTRAL_CODE,
vibe/setup/auth/whoami.py at mistralai/mistral-vibe c96a6db) and reads the
Vibe budget of a CHAT key only (_account.py). magpie now asks whoami once a
key (kept by the key's hash): a Vibe key keeps vibe_budget as "Month"; a
Studio key gets the same body's api_budget (Vibe's own fixture in
tests/app_server/test_billing.py, "Producer: dashboard billing_api_public")
as "API · Month", Aside while the subscription's payg_enabled is on (Vibe's
uses vibe_payg_enabled). The names differ, so the accounts' strip never adds
a Studio month to a Vibe month. A key whoami can't place (a failed read, no
plan_type, Mistral Code) has no card read: the org's budget alone doesn't
say which of its two it spends. The unit stays the currency billing names
(dhanyqaz's USD came from the reply, as nothing in magpie writes USD for
Mistral); none when it names none. Only api.mistral.ai keys are touched;
every other plan source takes the same path as before.

Run (mote): go test ./internal/provider (whole package, ok);
go vet ./internal/provider ./internal/gui, GOOS=linux -tags nogui and
GOOS=windows vet; gofmt -l clean; usage-merge, i18n-keys, i18n-en-no-cjk,
gui-de, gui-ja, gui-zh-tw in Chromium and WebKit, all ok but
i18n-keys' "a plugin's words are its own", red the same on origin/main
0f07fbd0c (#5327, #5332, #5426; this change adds no plugin words).
Broken by hand: with readMistralBudget reading vibe_budget whatever the
kind, TestMistralStudioBudget goes red (the Studio window is 0.65 / 150
USD, Aside from the wrong flag, the same name as the Vibe month).
Not tried: a real Studio or Vibe key; none at hand. whoami's and
api_budget's shapes are Vibe's own code and fixtures, not a reply seen;
console.mistral.ai answers 401 to a bad key on any /api path, so the probe
doesn't prove the route. Two Vibe keys of one organization would still
each show the org's month and add up on the strip.

Reported-by: dhanyqaz
2026-11-06 13:52:28 +08:00
yetoneandchiperman ju 0f07fbd0c6 agents: a first Details opening reads its settings before it slides (#5360)
The first time an agent's Details opened, sheet() measured the row before
/api/settings (and, for a full-context row, agentcompact.js) had arrived,
slid to that half height, then jumped to the full one when they landed.
The click now loads what the row needs first (the button shows Loading…),
and only then measures once and slides. A later click supersedes a load
still in flight. agentcompact.js finds #fullContextSegs on the list it is
given, so it fills a row before it is in the page. This is chiperman's
patch (8886a860a) without its core budget raise: Agents-page comments in
app.js were cut instead (app.js 1,311,357 -> 1,311,024; core 1,533,459 of
1,533,802).

agent-expand-steady's slide check looked for the height animation only in
the click's own task. A first opening now waits for the settings read, so
it looks in every frame; it still fails when no frame is animated.

Run (mote, at base 8ee85c59f):
- agent-details-ready.test.cjs (new) + agent-expand-steady: 40/40.
- Every GUI file touching ag-link/ag-exp/agent-compact, click-scroll,
  i18n-keys: all green except i18n-keys "a plugin's words are its own"
  (red on origin/main 8ee85c59f too: #5332, #5426), agent-models-redraw
  chromium 560 "page closed" (4/4 alone), mobile-web "desktop matches
  origin/main" (needs .git, which mote-run's copy has none of), and
  agent-expand-steady's sync check (fixed above).
- TestCoreScriptBudget: ok.
Broken by hand: agent-details-ready on the old app.js fails with
"Details must end without a height jump: 202.984375 -> 729.6875".
Not tried: the real app with the reporter's agents; mobile-web.

Reported-by: chiperman
Co-authored-by: chiperman ju <chipermanju@gmail.com>
2026-11-06 13:43:30 +08:00
yetone d70f422043 gateway: a conversation of pictures keeps its text and pictures in Routing and Sessions (#5407)
matrix0487 on Discord: since images go to DeepSeek by file id, the
Routing card shows no pictures and the Sessions page loses the turns.

Cause: the views keep the body as the agent sent it, with every
picture inline, and they cap it. The Routing card keeps a body of up
to 32 MiB (promptBodyMax), and its archive read refuses a larger one.
A gateway-recorded turn keeps 8 MiB of input (conversationBodyMax),
and cutting it there leaves JSON that doesn't parse. Before #5407,
DeepSeek refused more than 64 MiB inline, so a conversation never got
far past these caps. With file ids it does: the reporter's turns send
about 30 MB of pictures each. The card then says the text is gone and
draws nothing, and the Sessions turn keeps only the reply.

Fix: leanImages swaps each inline picture's base64 (a data:image/...
URL, or a bare Anthropic or Gemini source that starts as a PNG, JPEG,
GIF or WebP does, 1 KiB or more, with no escapes) for a short ref
before the caps apply.
- Routing card: the kept body and the archive's copy (before its cap)
  keep their pictures in keptImages. It is memory only and bounded:
  128 MiB, least recently used first, and the same picture is kept
  once. dataImage reads a ref back to the data: URL. A ref whose
  picture has gone draws nothing.
- Sessions: the recorded input drops the base64 outright, since the
  page shows a picture as [image].
What goes upstream, what the archive stores, and the Recent calls'
body are unchanged.

Run (mote, through mote-run):
- go test ./internal/gateway -run 'Prompt|Context|Conversation|
  DeepSeek|Archive|Image|Lean|FileID': ok.
- go test ./internal/gui -run 'Context|Gateway|Sessions': ok.
- go vet: darwin gateway+gui, GOOS=linux -tags nogui, GOOS=windows.
- gofmt -l: clean.

TestFileIDConversationStillShows covers chat, responses and anthropic.
Each sends a 36 MiB turn of three 12 MiB pictures through the fake
DeepSeek, which names them by file id. It checks:
- the card draws all three, from memory and from the archive;
- the chat text is still there;
- the Sessions transcript holds the turn's text and three [image].

Broken by hand, each one red:
- wiring removed: memory, 0 pictures drawn;
- the archive's cap put back before the lean: archive not read;
- the conversation lean removed: the transcript keeps only the reply,
  cut:true (the reporter's "会话内容也看不到了");
- the ref not resolved: memory, 0 pictures drawn.

Not tried:
- the reporter's real DeepSeek account and the GUI by eye. No GUI file
  changed, so the GUI suite was not run.
- masking turned on explicitly with a lean body. The refs are plain
  text, so they are not expected to match a mask.
- Sessions read from an agent's own transcript (Claude Code, Codex)
  never pass through the gateway, so #5407 cannot touch them.

Reported-by: matrix0487
2026-11-06 13:42:40 +08:00
yetone 9e3a389e0b library: a skill whose app left its own link on a deleted version follows the version on disk
tjhhhh_84378 on Discord (11-06): ego lite updated from 0.6.2.5 to 0.6.2.7,
deleted Versions/0.6.2.5, and left its own ~/.local/share/ego/
active_version_dir naming it. The library's ego-browser, brought in since
dccfefdf7 (#2635), links to ego's ~/.local/share/ego/ego-skills ->
active_version_dir/Resources/ego-skills/ego-browser, so the whole chain led
nowhere and the skill was lost, while 0.6.2.7 had it complete.

Who owns which link: ~/.local/share/ego/ego-skills, active_version_dir and
the framework's Versions/* are ego's; magpie only reads them. magpie writes
the library's own link (library/skills/ego-browser) and the agents' links
to it. The stale pointer is ego's, but magpie lost the skill with a newer
version on disk.

557f51dbf mended a library link that points straight into Versions/<old>,
but movedVersion looked only at the link's own target: for ego-skills the
first missing part is not a version name, so nothing was found.

followMovedSkills (skill_moved.go) now, for a dangling library link whose
target isn't in a version folder, follows the links on the way as far as
they are there (linkedEnd) and asks movedVersion of where they end:
Current/current/latest when that leads to the skill, else the highest
version beside the deleted one with a SKILL.md there. The library links to
that folder, and keeps the app's steady link as the new Source.Via. Once
the steady link leads to a SKILL.md again (ego or the user mended it), the
library links through it once more and Via is cleared. ego's links are
never written. With no other version on disk the link is kept as it was
and the skill is shown missing, as before.

Old imports: a skill linked straight into Versions/<old> was already
mended by 557f51dbf; one linked through ego's link (since dccfefdf7) is
mended by this on the next read of the Library page or the next sync. No
re-import needed. Agents that read ~/.agents/skills directly still see
ego's own entry there, which is the user's/ego's and is left alone.

Tests (skill_moved_test.go), the reporter's layout: egoLite at 0.6.2.5,
brought in through ~/.agents/skills/ego-browser -> ego-skills, then 0.6.2.7
added, 0.6.2.5 deleted, active_version_dir and Versions/Current left on
0.6.2.5:
- TestSteadyLinkLeftOnDeletedVersion: Read shows it not missing, it reads
  as 0.6.2.7's, active_version_dir is unchanged, Via is ego-skills; after
  active_version_dir is pointed at 0.6.2.7, a Sync links through ego-skills
  again with no Via.
- TestSteadyLinkLeftOnDeletedVersionNoOther: no other version, shown
  missing, link left as it was.

Broken by hand:
- linkedEnd step turned off: TestSteadyLinkLeftOnDeletedVersion red
  (Missing:true), i.e. red on the old code.
- the go-back-to-Via case turned off: red, still linked to 0.6.2.7.

Run (mote via mote-run): gofmt -l clean; go vet -tags nogui
./internal/library for darwin, GOOS=linux and GOOS=windows clean; go test
-tags nogui -count=1 ./internal/library ok (91s). Windows box (win-run):
SteadyLink, OldImport and ImportedSkill tests pass (junctions). Full suite
after the push, recorded on the tag's follow-up.

Not tried: the reporter's machine or a real ego lite update; the layout is
the #2635 fixture with the paths from their message. Whether ego's
Versions/Current also stayed on 0.6.2.5 isn't known; both are covered.

Reported-by: tjhhhh_84378
2026-11-06 12:13:16 +08:00
yetone f285426ac2 library: the MCP router turns on with no agent, and in gateway mode
treeman_26897 on Discord runs magpie as an MCP entry point for remote
clients on a server with no agents. The router could only be turned on
from the Library, and the Library said "No agents to write to" with no
agent. In gateway mode (magpie web on a headless server, on by itself
with no agents) GATEWAY_HIDES left the Library out altogether. The
router's switch also showed only once a server was in the library. The
gateway and `magpie library mcp router on` had no agent gate: the gate
was the page's alone.

Now, with no agent to write to, or in gateway mode (where no agent is
shown), the Library is its MCP tab alone (`agentless` in client.js):
- servers without agent chips, found servers or projects;
- the router's switch, there before the first server too;
- its lines and status say any app connects at its address, the
  router is on or off;
- the servers it serves are checked once it is on;
- Connect… has Other apps alone, with the gateway key line.
Gateway mode hides only Agents now. The two keys of the empty state
are gone; the gateway-mode subtitle no longer says "no Library".

Remote use goes through the guard /v1 has, unchanged: lanGuard and
serveMCP. TestHubMCPRemoteEntryNeedsKey holds /mcp/magpie/hub to it
from another computer: not shared 403; shared with no key 401 (no
Origin, tools/list, a wrong key); Origin null, chrome-extension://,
file://, moz-extension://, a foreign site and another computer's page
refused from there and from here; a rebound Host with a browser's
marks (Origin = Host, Sec-Fetch only, a Mozilla UA) refused from
here and there; a proxy or tunnel here (X-Forwarded-For,
Cf-Connecting-IP) with no key refused; nothing ran for any of them;
with the key it runs, through the proxy too.

Run on mote at ef20ff690 (on origin/main b4799a6bb); rebased again on
6a78060c6 (gateway.go changed there), the gateway's Hub and LAN tests
and the Budget test ran again ok:
- go test -tags nogui ./internal/gateway -run Hub: ok
- go test ./internal/gui -run Budget: ok (no budget raised; the core
  scripts were 137 bytes over with a longer comment, cut back)
- gofmt -l clean; GOOS=linux and GOOS=windows go vet of gateway, gui: ok
- GUI, both engines, every language: library-mcp-agentless (new, 22
  of 22), gateway-mode, last-page, library-mcp-hub, mcp-hub-direct,
  library-servers-bulk, i18n-keys: 87 of 88; the red is i18n-keys
  "a plugin's words are its own", below.
- Before the rebase, the GUI files a change here can reach (every
  library-*, gateway-mode*, last-page, i18n-*, mcp-hub-direct,
  agent-prefs, bare-ids, images-library-way, search-/vision-mcp-library,
  gateway-conversations; 70 files): 1535 of 1536. The one red is
  i18n-keys "a plugin's words are its own", on main already: #5327,
  #5332, #5426 (files this change doesn't touch).

Broken by hand:
- library-mcp-agentless against origin/main's client.js and app.js:
  22 of 22 red (no router row with no agent; no Library tab in
  gateway mode).
- rebound() returning false and serveMCP's Origin check off:
  TestHubMCPRemoteEntryNeedsKey red on the rebound Host cases and on
  chrome-extension://, file:// and moz-extension:// from here. The
  test passes on the old Go code: the guard was there already.

Not tried: a real remote MCP client against a headless magpie serve
or magpie web on another machine; the TUI (it has no Library page of
its own for the router; the CLI's router on needs no agent).

Reported-by: treeman_26897
2026-11-06 12:12:20 +08:00
yetone c42522e241 quotas: the gateway's whole-page refresh reads saved Claude accounts again too (#5443)
POST /v1/magpie/quotas/refresh with no card named ran ReadAllCards,
which only cleared the caches (AskUsage). A saved, inactive Claude
account's /usage was never run again, so another magpie's refresh of
this one, or an app with a gateway key, kept showing its old numbers.
#5380 (814a625a2) fixed the GUI and the TUI and missed this route.

- ReadAllCards asks AskEveryClaudeUsage, as the Usage page's Refresh
  does. The 30s per-account floor and the running holds are unchanged;
  saved accounts are read side by side by fetchSubscriptionUsage, each
  bounded by its 20s wait, inside the handler's 30s.
- A key told only some cards had them read one after another, each
  waiting up to 20s, so a few cards outlasted the 30s handler.
  RefreshEach reads them side by side.
- Another magpie's refresh of its remote card waited 8s for the POST
  (remoteBody's GET wait) and fetched the old cards while the remote was
  still reading. The refresh POST now waits remoteRefreshWait (25s);
  kept-card and history GETs keep 8s.

Other routes checked: the GUI's asked=1&all=1 and the TUI's r already
read every account. The CLI has no whole-page refresh: `magpie quota`
and `accounts` open with AskClaudeUsage by design, `quota refresh
<provider>` reads per card, `quota wait` waits, `accounts refresh`
renews logins. Unchanged.

Run at this head (rebased on b4799a6bb), on mote through mote-run:
  go vet, go test -count=1 ./internal/provider: ok (148.3s)
Run at f86dd7910 (b4799a6bb since touched quota history in provider only):
  go test -count=1 ./internal/provider: ok (131.9s)
  go test -count=1 -run 'Quota|Remote|LAN|Lan|Cors|ReadOnly|Readonly|Held|Antigravity|Draw'
    ./internal/gateway: ok (36.3s)
  go vet of internal/provider and internal/gateway: clean.
  GOOS=linux and GOOS=windows go vet of both, at d2c29abe7: clean.
  gofmt -l: clean.
Broken by hand, each red, then restored:
  ReadAllCards back to AskUsage: TestReadAllCardsReadsSavedClaude fails
    (ran the saved account's /usage 0 times, want once more).
  The refresh POST back on the 8s wait (remoteWait):
    TestRemoteMagpieRefreshWaitedFor fails (old Used 0).
  RefreshEach made serial: TestRefreshEachReadsSideBySide fails (alone).
Not tried: the reporter's case end to end with a built magpie in a
sandbox HOME (a fake claude binary behind a real gateway); a real Claude
account; Windows and Linux runs (vetted for both). The full suite runs
after the push, under mote's suite lock.

Reported-by: prgrmrwy
2026-11-06 12:09:21 +08:00
yetone 8216592a84 plan: a Le Chat plan's month of Mistral Vibe on its key's card (dhanyqaz on Discord)
Le Chat Pro, Student and Team come with a monthly Mistral Vibe budget,
which the plan's Vibe key (chat.mistral.ai/code/extensions?focus=key) is
told at Mistral's billing API, the routes Mistral's own Vibe CLI reads
(mistralai/mistral-vibe c96a6db, vibe/app_server/_billing.py and
_account.py, fixtures in tests/app_server/test_billing.py):
GET https://api.mistral.ai/v1/billing/budget and /v1/billing/subscription,
the key as a Bearer. A key on api.mistral.ai now has a plan source
(planQuotaSourceOf, not sure): vibe_budget becomes one Month window, its
usage_percentage the share used, initial_budget the limit in its currency
(EUR), reset at reset_at, and Aside while pay-as-you-go is on (the
budget's payg_enabled, else the subscription's vibe_payg_enabled), since
what goes past it is billed then rather than stopped. The plan's name is
billing's plan_name titled as Vibe titles it (EDU is Student, INDIVIDUAL
Pro), asked only of a key with a budget; the card stands without it.
A key with no Vibe budget (initial_budget 0 or none, a la Plateforme key)
has no windows and no card, and a refusal gives no card unless one was
read before. Le Chat's own message limits are told by no API.

Run (mote): go test ./internal/provider (whole package, ok), plus the
Balance/Plan/Quota/Usage/Allowance/Key tests of internal/gui and
internal/gateway; GOOS=linux and GOOS=windows go vet ./internal/provider;
gofmt -l clean.
Broken by hand: with the budget's own payg_enabled ignored,
TestMistralVibeBudget goes red.
Not tried: a real Vibe key. None was at hand. Live, both billing routes
answer 401 "Invalid API Key" to a bad key while an unknown /v1/billing
path is 404, so they exist; the bodies are Vibe's own test fixtures
("Producer: dashboard billing_api_public"), not a reply seen.

Reported-by: dhanyqaz
2026-11-06 11:53:33 +08:00
yetone dbe875ef30 balance: ModelScope's 魔粒 on the API-Inference token's card (jiabubu on Discord)
ModelScope's public OpenAPI (modelscope.cn/.well-known/openapi.json,
1.1.0+master.20261103) has GET /magicubes/balance at
https://modelscope.cn/openapi/v1, with bearerAuth ("ModelScope API
Token"): the same token API-Inference takes. Its reply is
{"success":true,"data":{"total_balance","available_balance",
"frozen_amount"}}; total is available plus what running tasks hold, so
the card shows available_balance, as "250 魔粒". A refusal
({"success":false,"message":…}) is told by balanceRefusal as ModelScope
words it. The Usage page's daily list (/magicubes/transactions) is not in
the OpenAPI, so what is spent a day comes from the card's own trend
(balanceTrend, "about N 魔粒 a day"). No web session is needed.

Run (mote): go test ./internal/provider (whole package, ok), plus the
Balance/Plan/Quota/Usage/Allowance/Key tests of internal/gui and
internal/gateway; GOOS=linux and GOOS=windows go vet ./internal/provider;
gofmt -l clean.
Broken by hand: with the api-inference.modelscope.cn case removed,
TestBalanceSourceByHost and TestModelScopeBalance go red.
Not tried: a real ModelScope token. None was at hand; unauthenticated and
fake-bearer calls to the live endpoint answer InvalidAuthentication, so
the route exists and wants a token, but a real reply's shape is the
OpenAPI's, not one seen. Short-term 魔粒 expire after 24h and the daily
grants come back, so the trend can count an expiry as spending.

Reported-by: jiabubu
2026-11-06 11:53:33 +08:00
yetone d2c29abe73 codex: a chat the Codex app had open as magpie became its provider moves once the app lets it go (crypto0xfish on Discord)
crypto0xfish on Discord, the Codex app: "Model provider mismatch. This
chat uses OpenAI, but your current provider is magpie. Switch to OpenAI
to continue."

magpie makes itself Codex's provider (model_provider = "magpie") when
Codex has no ChatGPT sign-in, is signed in with an API key, the user
picks magpie API, or the ChatGPT account is used up (the takeover).
bringOver then moves OpenAI's threads to magpie, a paginated one by its
row (RetagPagedCodexThreads), skipping any a Codex holds open (its
writer lock) or wrote to in the last minute, "for the next sync". The
Codex app holds the lock of every thread it has loaded, the chat on
screen among them, however long ago it was written (tried below), and
nothing asked for that next sync: Sync runs on catalog changes, which
can be hours away. So the chat open at the switch stayed on OpenAI;
the app refuses it while loaded (app-server
check_thread_model_provider_for_input compares the loaded thread's
provider with config.toml at each turn), and after the app let it go it
was refused again on resume by its row, until something else synced.
681a472ca fixed the same gap for bringBack by time alone and named the
held-lock case as not tried.

- sessions.CodexThreadsBusyOn also counts a thread on the provider
  whose writer lock a Codex holds (codexLockedIDs: the lock files in
  thread-writer-locks, each tried and let go under Codex's coordination
  lock, none made or removed).
- codexThreadsLater(dir, p) now looks every 15s, for up to 12h, and asks
  for the Sync once nothing on p is busy or held; one wait per home and
  provider. bringBack keeps calling it for magpie; bringOver calls it
  for the provider it moved from, and lendOwn for openai (the same skip,
  OpenAI's threads onto a provider of the user's).
- Tests: TestCodexOpenThreadFollowsMagpieOnceLetGo (new: a paginated
  OpenAI thread held open stays at the takeover, no Sync is asked while
  held, one is once let go, and that Sync moves it to magpie);
  TestCodexTakeoverThreadComesBackOnceQuiet now expects the Sync only
  after the thread is quiet. TestMain turns the wait off so no goroutine
  outlives a test; the two tests end theirs in Cleanup.
- docs/subsystems/agent-wiring.md says so.

The chat loaded at the moment of the switch can't be helped from
outside: the app goes on with it once it reloads it (quit and reopen).
Codex's identity line, base_instructions and every value of the user's
are untouched.

Run on mote at this tree (base cff530079):
- gofmt -l: clean; go build ./...: ok;
- go vet ./internal/agent ./internal/sessions for darwin, linux -tags
  nogui and windows: clean;
- the two tests with -race -count=3: ok;
- go test ./internal/agent ./internal/sessions: ok.
On Windows (win-run): the two tests and TestCodexPagedThreadsFollowByRow: ok.

Broken by hand: bringOver's call turned off (`if false &&`), the new test
fails "no later Sync asked for"; the lock check in CodexThreadsBusyOn
turned off, it fails the same way. Restored, both pass.

Real Codex: codex-cli 0.165.0's app-server in a sandbox CODEX_HOME, a
thread started and a turn sent (to a dead fake provider). With the thread
loaded and its rollout quiet 73s, its lock was held, a probe built from
this tree said CodexThreadsBusyOn true and RetagPagedCodexThreads moved
nothing; after the app-server exited and a quiet minute, busy was false
and the retag moved the row.

Not tried: the real Codex desktop app (whether leaving a chat for another
lets its lock go within a minute, or only quitting does), and a live
switch with a real used-up or API-key account. The reporter's own setup
(why Codex was on magpie for them) is not known.

Reported-by: crypto0xfish
2026-11-06 11:26:41 +08:00
yetone d487aaab79 library: no second copy of a skill the user keeps in ~/.agents/skills
math_milian: a skill given to every agent was in ~/.agents/skills and
in ~/.pi/agent/skills, and Pi warned
  "hunk-review" collision: ~/.agents/skills/hunk-review (skipped)
Pi 1.4.0 reads ~/.pi/agent/skills, then ~/.agents/skills
(userAgentsSkillsDir in dist/core/package-manager.js), and drops a
skill read twice only when both paths are one file (realPathSet in
dist/core/skills.js). magpie already left out its own link for an
agent that reads the shared folder when the entry there was the
library's folder, magpie's link, or a holder's (Goose, Kimi Code). It
did not when the entry was the user's own copy of the same files
(another installer's, or copied by hand), so Pi, Codex, Gemini CLI,
OpenCode and the other readers each got a second tree beside it.

inShared now also counts such a copy (sharedCopy: not ours, not the
library's own folder, sameTree with the library's). The reader gets
nothing in its own folder, and the existing unlink loop takes out
magpie's link or marked copy there on the next sync, which only ever
touches entries ours() proves magpie made. The user's copy is never
touched; once it differs from the library's, the library's is given
again. Readers checked in their own code: Pi 1.4.0's loader, Codex
0.165.0's binary (user-agent-skills, .agents/skills), Gemini CLI
0.35.3's bundle (Storage.getUserAgentSkillsDir) and OpenCode 2.0.25's
binary (home/.agents). Amp isn't a skills target of magpie's.

Run:
- mote-run go test -count=1 ./internal/library ./internal/gui
  ./internal/cli: library and cli ok; gui red only on
  TestMainWindowCorners/macOS_26_SDK, #3949 (mote is macOS 27). go vet internal/library (darwin, GOOS=linux
  -tags nogui, GOOS=windows): ok. gofmt -l: clean.
- Real Pi 1.4.0's own loader (DefaultResourceLoader) in a sandbox HOME,
  cwd outside the home: a link in ~/.pi/agent/skills to the library's
  folder beside the user's copy in ~/.agents/skills gives
  'name "hunk-review" collision'; with the link gone (what the sync now
  does) the skill loads from ~/.agents/skills and no diagnostic.
Broken by hand: sharedCopy's return replaced with false,
TestSharedCopyNotGivenTwice red (link and copy: pi's and codex's
second entry stays).
Not tried: the magpie GUI against the reporter's real tree (their
layout is inferred from the warning); a library skill that is itself
a link to the agent's own folder beside such a copy keeps both (that
folder is the library's); a Pi or omp of unknown version is given its
own as before; Windows and WSL not run.

Reported-by: math_milian
2026-11-06 11:18:51 +08:00
yetone cff530079f wsl: a bridged distro reaches Windows on the bridge's adapter, not the LAN router
ecalpal_ on Discord (magpie 0.1.2689, Windows 11, WSL 3.0.3.0, Ubuntu
22.04.5; .wslconfig vmSwitch=WSL_Bridge_Switch, networkingMode=Bridged,
dhcp=false). In bridged networking the distro is a peer on the LAN and its
default route is the router, 192.168.9.1. magpie took that next hop for
Windows: wsl.json got {"net":"bridged","gateway":"192.168.9.1"} and Pi's
models.json a baseUrl on 192.168.9.1:3425, where nothing listens, with the
gateway token rather than the WSL key. serveWSL already listened on
192.168.9.147, Windows' address on vEthernet (WSL_Bridge_Switch).

wslrun.HostAt now picks the address: "" where the distro's 127.0.0.1 is
Windows' (mirrored, consomme, virtioproxy, as before); the next hop as it
is when it is Windows' own address on a WSL adapter (NAT, unchanged);
otherwise Windows' address on the one WSL adapter whose network holds
that next hop (bridged: 192.168.9.1 in 192.168.9.147/24 -> .147). A next
hop on no WSL network is kept as it was. The adapter list moved from
gateway.wslNets to wslrun.Nets (gateway.WSLNets still wraps it), so both
probes use it: agent's parseProbe (distro.Gateway, what place writes into
agents) and wslrun's (Tool.Host, a 127.0.0.1 proxy handed to a WSL CLI),
which had the same bug.

The key follows the address: keyAt(http://192.168.9.147:3425) is on a WSL
net (OnWSLNet), so agents there get the WSL key.

Existing users: on the next start, the first probe of the running distro
writes the new gateway into wsl.json and keeps 192.168.9.1 in Was. The
startup SyncCatalog then rewrites Pi's provider block (baseUrl and apiKey)
at the new address; keptaway treats the old router address as magpie's
because it is in Was. A distro that isn't running at start is fixed at its
first probe after it runs, and its agents' files at the next sync after
that. Codex in WSL, which keeps its own base_url, gets the existing
"unreachable" drift with "Use 192.168.9.147:3425" (wslMovedFrom), not an
automatic rewrite.

Tests (fixtures are the reporter's values):
- wslrun TestHostAt: bridged/nat/mirrored/consomme each with its own route
  and adapters; TestParseProbeBridged (Tool.Host and proxy).
- agent TestWSLBridgedReachesWindowsOnTheBridge (bridged .147, nat
  172.20.0.1 unchanged, mirrored 127.0.0.1) and
  TestWSLBridgedOldRouterWrittenOver: wsl.json and Pi's models.json as
  0.1.2689 wrote them, then a probe and a sync: baseUrl .147, apiKey the
  WSL key, wsl.json rewritten.

Run:
- Broken by hand: probe code put back to HostLoopback only. Both new agent
  tests and TestParseProbeBridged FAIL (Gateway/Host 192.168.9.1).
- mote: gofmt -l empty; go vet, GOOS=windows go vet, GOOS=linux go vet
  -tags nogui for wslrun, gateway, agent; GOOS=windows go build: ok.
- mote: go test -timeout 45m ./internal/wslrun ./internal/agent
  ./internal/gateway: ok (wslrun 1.3s, agent 231s, gateway 855s)
- xiaomi-gpu (win-run): go test ./internal/wslrun ./internal/gateway
  -run 'HostAt|ParseProbe|WSL' ok; ./internal/agent -run
  'WSL|ParseProbe|Omp' ok. A first try with a fallback (bridged + one WSL
  adapter -> that adapter) went red there on TestParseProbe and
  TestWSLNetworkingFromWslinfo, because the box's real NAT adapter
  (vEthernet (WSL (Hyper-V firewall)) 172.17.32.1/20) was taken for the
  bridge; the fallback was dropped.
- xiaomi-gpu, real adapters: HostAt("nat", "172.17.32.1", Nets()) =
  172.17.32.1; magpie-desktop is NAT (wslinfo nat, default via
  172.17.32.1), so its value is unchanged.

Not tried: a real bridged WSL (none on the LAN; magpie-desktop's
networking was not changed), a real magpie start against an existing
wrong config, and the full go test ./... before the push (run after).
2026-11-06 10:49:35 +08:00
yetoneandggbdpq 7e5a54147f gateway: a routing group's intent sureness is its own, intent-sure= (#5101)
Jev's sure of an intent had to reach jevSure, a fixed 0.4, for every
group. zminds measured 39 of 237 turns in one day (16.5%) refused at sure
0.153 to 0.395, and those turns went by the group's routing as if it had
no intent rules. A group can now set its own threshold: intentSure, from
0 (take Jev's likeliest intent however unsure) to 1. Missing keeps 0.4.

readJev keeps Jev's likeliest intent, its sure and Topic (an answer of
intents rather than levels). ruleFor applies the group's own sure through
intentOf, so two groups sharing one classifier and its cached answer each
judge it at their own. "none of these" is never an intent, at 0 too.
Levels and effort are as before.

Set from a terminal: magpie group set <group> intent-sure=0.25, empty to
unset. SaveGroup and the CLI refuse a value outside 0 to 1, NaN too: the
patch's `v < 0 || v > 1` let intent-sure=NaN through the CLI, which
SaveGroup then failed on as "json: unsupported value". cloneGroups copies
the new pointer, since TestCloneGroupsSharesNothing went red on it.

Changed from ggbdpq's patch on #5101:
- The group editor's "Intent sure" row is left out. Its hints were long
  secondary text, it showed for every classifier when only Jev answers
  with a sure, and it had no GUI test. The Routing page instead carries
  intentSure through each save it makes of a group (the editor's Save,
  the routing menu, the manual pick), so a value set from the CLI isn't
  wiped by the next GUI save.
- Its i18n strings and site/public/docs/intent.html are left out. A
  site/ change waits for the maintainer (docs/contributors.md). The site
  diff was documentation text only: a paragraph id="sure", a sentence
  in "Match the rules" and one table row. It had no links or scripts.
- docs/subsystems/gateway-routing.md has a bullet for IntentSure.

Run on mote (mote-run):
- gofmt -l internal/: clean.
- go vet -tags nogui, also with GOOS=linux and GOOS=windows, on
  internal/gateway, internal/cli and internal/provider: clean.
- go test -tags nogui -run 'TestGroupIntentSure|TestJev|Rule|Classif|Decide'
  ./internal/gateway: ok.
- -run 'Group|Apply' ./internal/cli: ok.
- -run 'Group|Save|Clone' ./internal/provider: ok.
- go test -run Budget ./internal/gui: ok.
- node --test group-intent-sure (new), routing-group-strategy and
  group-first-token, in Chromium and WebKit: 42 pass, 0 fail.
- i18n-keys has one red, "a plugin's words are its own". It fails the
  same on origin/main b712adb84 and is filed as #5327, #5332 and #5426.
  i18n-en-no-cjk: ok.

Broken by hand, each red, then restored:
- sureNeeded always returns 0.4: TestGroupIntentSureThreshold,
  ZeroTakesTheArgmax and IsPerGroup FAIL.
- The patch's `< 0 || > 1` checks put back: TestGroupIntentSurePairs
  FAILs on "NaN" and "nan"; TestGroupIntentSureRange FAILs on NaN.
- The cloneGroups copy removed: TestCloneGroupsSharesNothing FAILs.
- The editor's Save sending intentSure null: group-intent-sure FAILs 4/4
  ("the editor's Save keeps it").
- The routing menu's pick sending null: it FAILs 4/4 ("a routing pick
  keeps it").

Not tried: a real Jev account with a group at 0.25; the full suite.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-06 10:44:24 +08:00
yetoneandggbdpq 429f9317d2 uninstall: Codex's base URL at magpie's gateway goes even with magpie's notes gone (#3866)
Uninstalling disconnected only the agents that read as connected. A
Codex whose config still had openai_base_url at magpie's gateway (or
model_provider = "magpie") but whose notes in magpie's folder were gone
(the folder deleted by hand, a fresh install beside an old config, a
magpie older than the notes) read as not connected, so the uninstall
left it pointing at a port nothing answers: every Codex turn then failed
with a connection error that never names magpie.

Uninstall's Agents step now ends with Codex's leftovers pass
(agent.TakeCodexLeftovers, the Agent's TakeLeftovers): the base URL goes
by viaBase()/dropBase and magpie as provider by asProvider()/dropProvider,
the same gates and drops a Disconnect uses, notes or not. Codex's own
model, its own provider and keys stay, and so does
[model_providers.magpie], which threads started on magpie name. Taking
anything shows "Codex's leftover settings" in the report and restarts
the Codex app's app-server. docs/subsystems/agent-wiring.md says so.

Not changed: deleting magpie.exe by hand runs no code, so the reporter's
Windows case is covered only through Settings > About > Uninstall magpie
or `magpie uninstall`. The pass is this machine's Codex only, like
EndCodexFailover; a WSL distro's config is left as it was. viaBase
matches any loopback port with /backend-api/codex, as Disconnect does.

Run on mote, base origin/main 4e7661adc:
- gofmt -l on the touched files: nothing
- go vet -tags nogui ./internal/agent/ ./internal/uninstall/,
  GOOS=linux go vet -tags nogui, GOOS=windows go vet: clean
- go test -tags nogui -count=1 ./internal/uninstall/: ok
- go test -tags nogui -run 'Uninstall|Run|Keep|Data' ./internal/cli/: ok
- go test -tags nogui -run Codex ./internal/agent/: ok (44s)

Broken by hand: TakeLeftovers returning false at once and Agents not
calling endLeftovers: TestCodexLeftoversGoAtUninstallWithoutTheMarks and
TestCodexProviderLeftovers... FAIL "took false, err <nil>"; TestRunOrder,
TestKeepData and TestRunTakesCodexLeftovers FAIL (no "leftovers" step,
the Codex app not restarted, a failed pass not reported).

Not tried: a real `magpie uninstall` (it removes the login service, which
a sandbox HOME doesn't isolate), the Codex app, Windows.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-06 10:44:24 +08:00
yetone 6ddfc15843 library: an MCP command's $HOME, ${NAME} and ~ work in every agent (math_milian)
A Library server whose command is $HOME/bin/x (one value for a Mac's
/Users and Linux's /home) reached each agent as written. Claude Code
spawns '$HOME/bin/x' (it expands only ${NAME}), Codex and the rest
spawn it with no shell, and magpie's own check, router and Codex run
did the same.

library.json keeps what the user wrote. withCmdVars (cmdvars.go) makes
the copy an agent is written, in sync after runVia and in a project's
files:
- an agent that expands a reference in command and args itself
  (Claude Code, CodeBuddy, WorkBuddy, Grok, Gemini, omp/Qoder/AtomCode,
  OpenCode as {env:NAME}, Cursor as ${env:NAME}) gets the reference in
  its syntax, $NAME written ${NAME}, so it is read from the agent's own
  environment and a token in an arg stays out of its file;
- every other agent (Droid, which shares Claude Code's format, by the
  new NoCmdRefs; Codex, Kiro, Crush, Copilot, Goose, Pi, Hermes, dsh,
  Command Code, LiveAgent and those reading none) gets the values: HOME
  is its own home, the rest from magpie's environment or a terminal's;
  in WSL the distro's home and no variable of magpie's;
- a leading ~ is put in for all of them; a variable nothing has is
  left as written.
Sync compares against that copy, so a second sync rewrites nothing.
magpie starting the command itself (startServer for the check and the
router, a distro's HOME asked of its login shell; specOf for Codex on
magpie) puts the same values in (launchCmd). Env and headers keep
their ${NAME} handling (envref.go) as before.

Run:
- mote: go vet ./internal/library for darwin, linux and windows;
  gofmt -l clean; go test ./internal/library ./internal/gui: every test
  but TestRunServerAsks (once, then 10/10 alone; filed #5433, my change
  leaves a command without $ or ~ as it is) and TestMainWindowCorners
  (macOS 27 on mote, #3949).
- wsl-run and win-run: TestCmdVars*, TestEnvRefs*, TestCheckStdio ok.
- Real Claude Code 2.1.316 in a sandbox HOME/CLAUDE_CONFIG_DIR, claude
  mcp list: "${HOME}/bin/srv" Connected, "$HOME/bin/srv" ENOENT
  posix_spawn '$HOME/bin/srv', the reporter's failure and why $NAME is
  written ${NAME} for it.

Broken by hand: with the sync, specOf and startServer wiring taken out,
TestCmdVarsSync (claude and codex files) and TestCmdVarsLaunch ($VAR,
~ and the spec) are red.

Not tried: the reporter's own agent and server; a real Codex, Cursor,
OpenCode, Gemini or Droid starting the written entry (their expansion
is as envref.go's cited sources say); a real WSL distro (distroHome is
unit-free, the WSL target is tested with a set Home); npxDirect on a
command spelled with a variable (it still sees the written value).
2026-11-06 10:20:34 +08:00
yetone e17c6976b2 provider: Voyage AI preset, its embedding and rerank models (heatonz on Discord)
heatonz on Discord asked for Voyage AI, its embeddings and rerank. The
gateway already had /v1/embeddings and /v1/rerank; what was missing was
a way to add Voyage and have its models found there.

- presets.go: `voyage`, a vendor with an API key at
  https://api.voyageai.com/v1 (docs.voyageai.com, keys at
  dashboard.voyageai.com). Voyage has no /models, so it is NoList and
  the preset names its models in two new PresetDef fields, Embeddings
  (voyage-4-large, -4, -4-lite, code-4, finance-2, law-2, 3-large, 3.5,
  3.5-lite, code-3, code-2) and Rerankers (rerank-3, -3-lite, 2.5,
  2.5-lite), as Voyage's docs list them on 11-06. Region gets
  Rerankers too.
- models.go: planMedia marks each plan model with what it serves
  (catalog.Model.Serves), falls back to the preset's own lists when the
  provider has no region, and PlanRerankers / PlanRetrieval(kind) sit
  beside PlanEmbeddings. A NoList provider's ListAll has them too,
  marked, so catalog.Chat keeps them out of agents' lists, keys and
  Routing's chat pickers.
- gateway: resolveRetrievalModel and servesKind look up the kind asked
  for (PlanRetrieval(kind)) and not only embeddings. Before this, a plan's
  embedding model named on /v1/rerank was sent there, and a plan's
  reranker was never found.
- catalog.ServesOf: `voyage-*` is an embedding model (its ids have no
  "embed"), so Test, detection and a relay serving voyage ids know it.
- test.go / gui providers.go: the retrieval-only Test fallback and the
  editor's "retrieval" count read PlanRetrieval as well.
- docs/reference.md: a new "Embeddings and rerank" section with both
  routes' bodies (OpenAI's for embeddings; the Cohere/Jina/Voyage shape
  for rerank, top_n or top_k) and the Voyage preset. READMEs and the
  import docs pages (en, ja, zh) list it.

Not served: Voyage's contextualized and multimodal embeddings (their own
endpoints). A Voyage 4xx comes back as its raw {"detail": ...} body with
its status (errorSaid has no "detail" reader).

Tests (no network; a fake built from Voyage's documented request and
reply shapes): TestVoyageEmbeddingsAndRerank (bare and provider ids,
input_type/output_dimension and top_k/return_documents passed on, usage
total_tokens recorded), TestVoyageModelsStayOnTheirRoutes,
TestVoyageRefusalSaysWhy, TestVoyagePreset,
TestVoyageTestAsksItsRetrievalAPIs, TestServesOf's voyage cases.

Run on mote: go test -count=1 -timeout 45m ./internal/provider
./internal/catalog ./internal/gui ./internal/gateway. provider, catalog
and gateway ok. gui has one red, TestMainWindowCorners/macOS_26_SDK,
which is #3949 (red on macOS 27); this change doesn't touch AppKit.
go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
./... ok. gofmt -l clean.

Broken by hand:
- resolveRetrievalModel/servesKind back on PlanEmbeddings:
  TestVoyageEmbeddingsAndRerank red (rerank-3: 404 "magpie knows no
  model"), TestVoyageModelsStayOnTheirRoutes red (voyage-4 on /v1/rerank
  answered 200).
- the voyage- prefix out of ServesOf: TestServesOf and TestVoyagePreset
  red.

Not tried: against the real API. No Voyage key was available, so the
endpoints, auth and shapes come from Voyage's docs alone. Not tried in
the GUI's Add sheet by hand, and not on Windows or Linux beyond vet.
2026-11-06 10:17:08 +08:00
yetoneandggbdpq 766d2a9f54 gateway: a Claude turn sent again while its run is busy with it goes on from a copy of its session (#5405)
A client's connection dropped mid-reply and its request was retried,
with no cancel reaching magpie (#5405, margbug01: a gateway between
the client and the server magpie retried after "unexpected EOF"). The
run the first attempt resumed was still busy with the very turn, so
resume and unshelve found nothing, and the retry started a new Claude
Code told the whole conversation in one message: only Claude Code's
own system prompt and tools read from the cache, the rest (92K to 142K
tokens in the report) written again on every retry.

retryBranch, tried in start between unshelve and retire, finds a busy
run of the account whose last heard request is this one, message for
message, and starts the retry's run from a copy of that run's session
cut before the turn (cutReply at backLine/backMsg), told only the
turn, as a branch off a side question already is. The busy run is left
alone; when both park at the same key, keepIdle lets the older go.
nil, and the conversation told whole as before, when no run matches,
the client places its own cache marks, the run was or is being taken
back, it was started for this turn (nothing before the turn to cut
at), or the session can't be cut (logged).

Changed from ggbdpq's patch: it matched with follows, which also takes
a request that goes on past the busy run's turn; the retry is matched
by the heard request's key alone. A copy cut for an older run is
discarded when a newer one is taken, a failed cut is logged as the
patch's notes say, and a run with a reply id but no line yet is cut
by the reply, as branchAt does. The test waits for the busy run to
have heard the turn instead of sleeping 200ms, and stops the held
first attempt in t.Cleanup, so a failing assert doesn't leave it
running. The doc's "goes on to step 3" now says step 4.

Run (mote, -tags nogui):
- TestClaudeTurnSentAgainWhileItsRunIsBusyBranchesOffItsSession
  (print, interactive) -count=3: ok.
- Broken by hand: claude_subscription.go back to origin/main, test
  kept: FAIL in both modes, "0 runs branched, 2 started anew, want one
  of each". Restored: ok.
- TestClaudeTurnPastABusyRunsTurnIsNotBranchedOffIt (print,
  interactive): a turn sent past the busy run's own, with a reply the
  client has, is told whole (one message, or the interactive mode's
  transcript), not branched off the busy run. -count=3 with the other
  test: ok; -race -count=5 of both: ok.
- Broken by hand: the match back to follows: FAIL in both modes, "the
  turn past the busy run's was branched off it" (nextTurn gives its run only
  "now commit it", the turn and reply before it lost). Restored: ok.
- -run TestClaude ./internal/gateway/: ok 139s.
- -race -count=5 -run of the busy-retry, fork, side-question,
  given-up, rewind, unshelve and branch tests: ok 52s.
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of
  internal/gateway: clean.
- gofmt -l on both Go files: empty.

Not tried: a real Claude subscription with a real dropped
connection. The full suite runs after the push.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-06 10:04:01 +08:00
yetoneandggbdpq baf70992f6 usage: a call the vendor answered with another model is priced as the model that served it (#5340)
The ledger priced a call at the model asked for and fell back to the
model the reply named (Served) only when the asked-for one had no price
(#1498). That order is right for a relay that sells kimi-k3 as
moonshot-kimi-k3 and bills by the name it sold, but it also priced a
real substitution: claude-opus-5-5 asked, claude-opus-5 served. The
vendor bills for the model that ran. kaimo455's ledger had 836 such
rows, every one at the asked-for rate: $374.06 reported against
$493.28 at the served model's rate. gateway-key cost limits (KeySpent,
NewCoster) and budgets read the same pricer.

Pricer now prices a call the ledger marks swapped at the served model's
price. That covers a price the user set for the served model and every
other layer of BasePriceIn. A price the user set for the model asked for
still wins, 0 included (new provider.UserBasePriceIn is BasePriceIn's
user layer alone). When the served model has no price, the asked-for
one's stands. Renames, vendor aliases, serving names and region
deployments price as before, and rate windows still read each record's
own time. apiPricer, the API price behind a subscription window's whole,
follows the same rule: the served model's API price first, then the
asked-for one's.

Review changes on top of ggbdpq's patch:
- The swap is judged the way the ledger's Swapped column judges it: on
  the model id and on the name that went out (SentNameIn over the
  user's ModelWires). A model the user sends under the served one's name
  was answered as asked, so it keeps its own price. The patch judged the
  model id alone, so such a row was priced as swapped while the Requests
  page said it wasn't. The pricers' memo keys now include the effort,
  because the sent name depends on it.
- apiPricer (window holds) got the same rule. The patch left it on the
  old order.

Tests:
- TestLedgerPricesASwappedCallAsTheModelThatServed (patch, plus a
  ModelWires case) checks the ledger and the Requests page.
- TestLedgerPricesARenamedModelAsTheOneServed: the sol row (sol asked,
  kimi-k3 served, both priced) is a genuine swap, so it now prices at 3,
  not 2.
- TestHoldsPriceTheModelTheReplyNamed: claude-opus-4-7 answered by
  gpt-5.5 is priced at gpt-5.5's API price. Answered by an unpriced name,
  it keeps opus's.

Run on mote at this tree, on origin/main 4e7661adc:
- The three tests above: ok.
- Product files (ledger.go, window_holds.go, provider/models.go) put
  back to origin/main, tests kept: all three FAIL ("served luna:
  priced=true cost=10, want 33"; "sol: ... cost=2, want ... 3"; "a call
  answered by another model wasn't priced as that one: &{Input:5 ...}").
- servedInstead's sent-name check broken by hand (return true): the
  ModelWires case FAILs ("served luna: priced=true cost=33, want 10").
- go test -tags nogui -count=1 ./internal/usage/ ./internal/provider/
  ./internal/budget/ ./internal/otlp/ ./internal/middleware/: all ok
  (usage 44.9s, provider 158.3s).
- gofmt -l: clean. GOOS=linux go vet -tags nogui and GOOS=windows go vet
  of internal/usage and internal/provider: clean.

Not tried: a real ledger with Anthropic's refusal fallback. The rows in
the tests are built from the shape the reporter describes. The full
suite runs after the push.

#5340, kaimo455 (report, measurement and the proposed order)

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-06 09:57:18 +08:00
yetone 4e7661adce redact: an app's one-word name the model took for a person's goes as written
Reported by ylorn. on Discord (11-06): choosing apps in Alma, a question
about one app was answered with another's facts. Privacy Filter took the
apps' names (Cicada, Mimi, Phosphor, Parakeet, Muesli) for people's: in a
bare list of them, alone, and in the Markdown list of apps the assistant
answered with (probed on the real model: ~0.99 each). The follow-up
questions ("How about Mimi?", "Phosphor vs Parakeet") it did not flag, so
they went as written while the history held the names as placeholders;
Phosphor and Parakeet (8 bytes) then became known values and were masked
everywhere. The vendor could not tell which placeholder was which app.

Restore was not the cause: placeholders are a keyed hash of kind and value,
one per value, and restore maps each back to its own value in any case
(TestManyNamesRestoreEachToItself, a guard: it passes on the old code too).

personFits now lets one ASCII word go when what is around it says a thing
and nothing says a person (thingNamed, internal/redact/thingname.go): a
person's word beside it (my colleague, Hi, Mr, said, told) masks; a thing's
word beside it (using, switched to, the ... app, vs, apps like, 这个软件)
lets go; else its sentence decides (he/she/relations/greetings/said mask;
app/macOS/subscription/vs/软件 let go); else a list item among items that
speak of apps, or a text of capitalized names only, lets go.

Trade-off, by design: a single first name alone, or a first name in a
sentence that speaks of an app with nothing of a person ("Mimi uses the
app daily"), goes as written. A full name (John Smith), a Chinese name
(张伟), and a first name beside a relation, a greeting, said or a pronoun
are masked as before.

Run (mote, worktree at 84ad780b6 + this):
- go test ./internal/redact/... ./internal/pii/... ./internal/masking/...
  ./internal/otlp/... ./internal/sessions/... ./internal/settings/... ok
- go test -run 'Mask|Redact|Privacy|Person|Known' ./internal/gateway
  ./internal/gui ok
- TestMaskEval re-recorded with both real models (MAGPIE_EVAL_CACHE);
  only the 12 new cases' recordings are added, old entries kept as they
  were (mote's re-record drifted 4 AstrLink and 2 Privacy Filter entries
  by score; not taken in). New cases app-names, app-alone, app-markdown
  (real Privacy Filter flags), app-compare/vs/list/using/zh (model finds
  none; guard), app-and-person, app-and-full-name, app-and-zh-name,
  greeting (person controls).
- gofmt -l clean; GOOS=linux and GOOS=windows go vet ./internal/redact ok.

Broken by hand:
- the personFits hook off: TestAppNamesNotPersons red 9/9,
  TestPersonBesideAppStillMasked red on the 3 apps, TestMaskEval red on
  app-names (5), app-alone, app-markdown (3) with the real recordings.
- thingNamed always true: TestPersonBesideAppStillMasked red on Mimi (x2),
  Laura, Daniel.

Not tried: a real Alma chat through the gateway with the model on; Windows
and Linux runs (pure Go string code, vetted for both); the full suite runs
after the push.
2026-11-06 09:28:25 +08:00
yetone 84ad780b65 gui: DeepSeek's image-files setting in the provider editor's Advanced (#5407)
matrix0487 on Discord (#feedback, 11-05) asked to change image-files from
the GUI: 8fbf8e0af made it CLI-only (`magpie provider set <id>
image-files=off`). The editor's Advanced now has an Images tick, "Upload
images once and send them by file id", on by default. It shows only where
the setting has effect: a provider on api.deepseek.com, the built-in
DeepSeek or a custom one with that base.

The rule has one source: provider.ImageFilesAt(to) (own key, no account or
plugin, Chat/Responses/Anthropic, host == provider.DeepSeekHost), and
TakesImageFiles for the editor. The gateway's dsFilesOn and forward's
dsSent setup ask ImageFilesAt instead of their own host checks.
/api/providers sends imageFilesOff and takesImageFiles; /api/provider/save
takes imageFilesOff as *bool, so a save that leaves it out keeps the old
value (CLI-set off stays off), false turns it on, true off. app.js sends it
only when the row is shown. Strings in zh, zh-TW, ja and de. app.js is 135
bytes under its base (four comments cut to one line); no budget raised.

Run on mote:
- provider-image-files.test.cjs: chromium + webkit, en/zh/zh-TW/ja/de,
  1100 and 420 wide, 60/60. Shown for DeepSeek and a custom
  api.deepseek.com base, hidden for another relay, toggling saves the
  field, CLI-set off shows off.
- i18n-keys, i18n-en-no-cjk, editor-advanced-align, editor-fold-clickable,
  provider-limit-rest, provider-image-files: 131/132; the red is i18n-keys
  "a plugin's words are its own" from other tests' strings ("View
  routing", "No session ID"), #5332 / #5327.
- go test -timeout 45m ./internal/provider ./internal/gateway
  ./internal/cli ok; ./internal/gui ok but TestMainWindowCorners, the
  macOS 27 red (#3949). TestProviderSaveImageFiles and
  TestCoreScriptBudget rerun after the comment cut.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.

Broken by hand, each red then restored:
- row condition `if (false)`: GUI red (chromium en 420).
- save field renamed: GUI red (webkit zh 420).
- imageFilesOff left out of draftOf: GUI red ("one set off from the CLI").
- the old keep-only save restored: TestProviderSaveImageFiles red
  ("ticked on in the editor, still saved off").
- host rule loosened to contains "deepseek": TestProviderSaveImageFiles
  red (api.deepseek.com.example.com offered).

Not tried: a real DeepSeek key or the real app; a URL edit on an unsaved
provider doesn't show or hide the row live (it follows the saved row's
flag).
2026-11-06 08:01:14 +08:00
yetone ef176e21f6 sessions: a Claude Code session moved with /cd is listed under its new folder
usrname1833 on Discord (#feedback, 11-05): after Claude Code's /cd the
session's file is in the new folder's .claude/projects directory, while
magpie kept showing the session under the folder it was started in.

What /cd does (Claude Code 2.1.316, read in the binary and run for real
in a sandbox CLAUDE_CONFIG_DIR against a fake API): relocateSessionTranscript
renames projects/<old>/<id>.jsonl and its <id>/ folder to
projects/<new>/, and appends {"type":"relocated","relocatedCwd":"<new>"}.
The lines from before keep the old cwd; a second /cd adds another line,
and the last one names the folder.

Cause: a Claude Code session's folder was its first line's cwd only, and
a relocated line went to the default case. Every place that groups or
resumes by folder (GUI, TUI, `magpie sessions`, stats, the resume
command's cd) reads Session.Cwd, so all of them showed the old folder.

- claudeLine reads the relocated line (ccRelocated): the last move's
  folder is the session's.
- A parse kept by an earlier magpie isn't read again when the file
  hasn't changed. One whose folder isn't the project folder the file is
  in (ccStale, with Claude Code's own name: non-alphanumerics as "-",
  past 200 cut and a hash added) is read again once. state.CdRead marks a
  parse made by this reader, and a kept one in its right folder is marked
  on the first refresh, so the name isn't worked out on every poll.
  parseVersions isn't raised: that would read every Claude file again.
- A glance (a long file's row before its first read) takes a relocated
  line in the last 64 KB too.
- Sibling, magpie's own project move (relocateClaudeJSONL): a /cd'd
  session was judged by its first cwd, so moving the folder it was moved
  to failed with "a different project cwd", and relocatedCwd was never
  rewritten. It now judges by the last move and rewrites relocatedCwd.
- docs/subsystems/gateway-sessions.md says how the folder is found.

Fixtures (internal/sessions/testdata/claude-cd) are Claude Code
2.1.316's own lines from that run, paths written as /w, without request
records, attachments and file snapshots.

Run (mote, at a754660b2 + this):
- go test -count=1 ./internal/sessions ./internal/tui ./internal/cli: ok.
  ./internal/gui: ok but TestMainWindowCorners/macOS_26_SDK, which is
  #3949 (macOS 27 on mote), not this change.
- GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...: ok.
  gofmt -l: clean.
- wsl-run go test ./internal/sessions: ok.
- win-run go test ./internal/sessions: the new tests ok; TestAgySessions,
  TestAgyRowOnly (#4115) and TestCCListingKeepsItsNames (#4925/#5277) are
  red on Windows the same on a754660b2 alone.

Red on the old code (a754660b2 with the new tests):
TestClaudeCdListedUnderNewFolder (under /w/projA, resume cd '/w/projA')
and TestClaudeRelocationAfterCd ("a different project cwd").

Broken by hand, each red: ccRelocated not called (ListedUnderNewFolder,
KeptParseReadAgain); ccStale always false (KeptParseReadAgain); the kept
parse not marked (KeptParseReadAgain); the glance tail skipping relocated
lines (TestClaudeCdGlance); relocateClaudeJSONL not resetting the first
cwd on a move, and not rewriting relocatedCwd (RelocationAfterCd).

No GUI file changed and the GUI tests stub /api, so no GUI test was run.

Not tried: the reporter's own files; the fixed build against a real /cd'd
session in the app (only the package's listing, Find and resume command
in tests); a /cd across WSL, or Windows paths beyond the vet and the
package run there.

Reported by usrname1833 on Discord.
2026-11-06 07:32:04 +08:00
yetone a754660b2a gateway: requests that come together spread over a pool's accounts (#5242)
Moody-Sin and Tericerice (#5242, magpie 0.1.3072 on Linux): an
antigravity provider with three accounts and affinity turn sent four
requests at once all to one account, under In turn and By pace alike,
each request with its own X-Magpie-Session.

Cause:
- Nothing counted the requests in flight when a request was planned.
  Pace (internal/routes/strategies.go:348) goes by pace, wallet and
  Tokens, all of which move only once a reply ends; a key's lane counts
  a request only once its try starts, after planning. Requests that came
  together were planned on the same figures and all went to the first.
- In turn's next turn (affinity.go:685 "new-turn" → after(), :937) reads
  a stick that moves only when an answer comes back, so a burst of turns
  of conversations already answered all went to the one next account.
- conversationID (gateway.go:9160 on origin/main) ignored
  X-Magpie-Session, so callers that named their own sessions but opened
  alike were one conversation and kept together.

Fix:
- burst.go: burstSpread, called in serve once the candidates are planned
  (gateway.go:3013), counts each request on the account it goes to until
  it ends, and puts first, among the accounts routing would as soon pick
  (burstAlike: In turn any ready one; By pace a pace within a tenth, no
  wallet told apart, none near its cap; Least used within a point), the
  one with the fewest in flight. A kept conversation (session, turn's
  stick, strict), a pin, a lead's account, a checkpoint and a new
  conversation leastHeld spread are counted where they are, not moved.
  Fallbacks, reserved, aside, resting, held, barred and capped accounts,
  other routings (Smart, In order, ...) and a group in a group keep
  their order. In a group, a member routed its own way is alike only to
  its own provider's. The one step covers direct models, groups, plugin
  providers and a remote magpie.
- affinityID: the stick key (stickKey), a group rule's key (ruleKey) and
  the sealed lead's stick read X-Magpie-Session after an agent's own
  session header. conversationID, which Kilo and a plugin are sent as the
  conversation, is unchanged, so the caller's session never goes
  upstream.
- docs/subsystems/gateway-routing.md says both.

Not done: putting a markedly slower account behind by its TTFT. A first
token's wait goes with the prompt's size and the vendor's queue more than
with the account, so a small sample would move turns away from a fine
account and off its cache; it needs its own design.

Run (mote, mote-run):
- go test ./internal/gateway -run 'TestABurst|TestBurst|TestMagpieSession|
  Kilo|Sealed|Rule|Stick|Affinity|Conversation': ok
- go test ./internal/gateway ./internal/routes: ok (654s, 0.3s)
- GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok; gofmt -l: clean
New tests (burst_spread_test.go): six at once over three keys, rotate
and pace × affinity turn/off/auto × x-session-id / X-Magpie-Session /
same body × fresh and warm; over a group of three providers and of one
provider's keys; behind a remote magpie; over a plugin's three accounts
(fake plugin, streaming); a kept session stays on one account; paces
{10, 9.5} spread and {10, 5} don't; three X-Magpie-Sessions in turn get
an account each under session affinity, and conversationID never
returns X-Magpie-Session.

On the old code every pace case went 6 of 6 to k1, and rotate's warm
cases 6 of 6 to the next account.

Broken by hand:
- reorder forced false: every pace case, rotate's warm cases, the group
  pace cases, the remote and the plugin tests red.
- !aff.Kept dropped: TestABurstKeepsAKeptConversation red
  (map[k1:2 k2:2 k3:2]).
- affinityID without X-Magpie-Session: TestMagpieSessionIsTheConversation
  red (map[k1:3]); the burst tests stay green, as the count covers them.

Not tried: real Antigravity accounts, a run on Linux, a real remote
magpie on another machine.
2026-11-06 07:05:37 +08:00
yetone 5ae0ed1ab0 claude warm-up: a week left out while the five hours run is one the account hasn't
koohoko5924 (v0.1.3057, Claude Enterprise): the account has only a
five-hour window, and the warmer kept warming a week it doesn't have
(state Idle, 189 tries). warmNow walks withExpected(q.Windows, expect),
which adds the 7-day window whenever a reading leaves it out, since
Anthropic leaves a window out until the request that starts it. But
any request starts every window a plan has, so a week left out while
the five hours are running is not a week waiting to start.

warmNow now marks such a window Absent (codex-warmup.json, compared in
mapsEqual) and sends it nothing (windowAbsent). The rule: the reading
leaves it out, the reading is whole (no partial window), a shorter
plan window is running (shorterRunning), and it was never seen with a
reset or use. A week seen running before, or left out of a partial
reading, is warmed as before. usageRead counts an expected missing
window as due only when no shorter window runs. withExpected itself is
unchanged: claudeWithUnstarted uses it for the card. Codex has no
expect list, so it is untouched.

Docs: providers-accounts.md gets the rule.

Run (mote, at this tree): go test ./internal/provider -run
'Warm|NotStarted|UsageRead|Claude|Codex' ok; gofmt -l clean.

Broken by hand: windowAbsent off and the old usageRead check:
TestClaudeWarmLeavesAWeekTheAccountHasnt red (12 "7 days" sends),
TestClaudeWarmStartsAWeekThatReset's "never read" warmed, and
TestUsageReadLeavesAWeekTheAccountHasnt told five-only@x. With the
seen/partial guard taken out, "reset" and "partly told" go red.

Not tried: a real Enterprise account or a real warm-up; the state is
the report's (Idle 189), rebuilt in the test.
2026-11-06 06:30:23 +08:00
yetone beba9e8a1f claude warm-up: the account it started is read again, its old reading keeping its time
koohoko5924 (v0.1.3057): after a warm-up the card said "just updated"
over windows read before it. claudeWarmedNow cleared the kept
reading's time (e.at) and kept its windows, so claudeReadAt gave nil
and readNow stamped them now. Nothing read the account again either:
claudeWindows' next read waits on when /usage last ran (e.tried),
which the warm-up left alone.

claudeWarmedNow now clears e.tried, which makes the next read due as
for an account never read, and keeps e.at, so until that read the card
shows the reading's own time. Codex's warmed hook only drops its cache
(its usage is a fresh API read), so it has no such sibling.

Run (mote, at this tree): go test ./internal/provider -run
'TestClaudeWarmedReadAgain|Warm|Claude' ok; gofmt -l clean.

Broken by hand: on the old claudeWarmedNow TestClaudeWarmedReadAgain is
red ("the kept reading's time is <nil>"); keeping e.at but not clearing
e.tried, red ("warmed, not read again", the 10% reading kept).

Not tried: a real warm-up on a real Claude account.
2026-11-06 06:30:23 +08:00
yetone 77031d5817 claude usage: a /usage panel with no window is no window started, and a failure says why
koohoko5924 (Discord #help, v0.1.3057, macOS): a Claude Enterprise
account with a five-hour window only. A manual refresh took ~5s and
gave the card no window and the error "Claude Code's usage showed no
usage figures: ▐▛███▜▌ … magpie-claude-work…": Claude Code's banner,
not a reason.

Claude Code 2.1.316's Usage tab (gi) draws a window only once
Anthropic's answer has it non-null, and a window is null until the
request that starts it. An idle 5h-only account's panel loads with
the session's cost, maybe the plan's credit bar, and no window. The
helper told that panel's words, joined from the top of the screen, and
the card took them as a failure with the banner first.

- claudetui: a panel that loaded (tabs, Session/Total cost, nothing
  loading, refreshing, stale or failed, no gateway Spend limit) with no
  "Current session"/"Current week" is told as NoUsageWindow ("No usage
  window has started"). The provider reads that as no window started:
  no error, the unstarted 5h window as for any account.
- claudetui: the two rate-limit errors gi draws ("Claude is temporarily
  limiting requests to the usage page (not your usage limit)…",
  "Usage endpoint is rate limited until …") are failures to load, like
  "Failed to load usage data": retried once, then told as an error with
  the panel's own "Error: …" text, never the banner. A panel with no
  window and no error is told from its tabs on, the session's cost
  lines left out.
- provider: "(not your usage limit)" no longer reads as an account
  refused (claudeDenied, at every place claudeUsageDenied judged a
  reading: the CLI parse, codex_switch, quota_last, subscription_usage).
  Counts ("Last 7d · 403 requests …") are taken out wherever they sit in
  a line before that check, as the panel's words come on one line now.
  A no-figures error keeps every line (600 runes), not the first clipped
  at 120.

Tests are built from 2.1.316's own strings (ko/gi/hi in the bundled
cli.js), drawn on the helper's 200x50 grid row by row. Guessed: the
exact bytes of a real Enterprise panel (not captured; no such account
here) and the credit bar's layout.

Run (mote, at this tree): go test ./internal/claudetui ./internal/provider
-run 'Usage|Claude|Shim|Quota|Codex' ok; go vet for claudetui, provider,
gateway; GOOS=linux -tags nogui and GOOS=windows go vet; gofmt -l clean.

Broken by hand (each red, then restored):
- the NoUsageWindow case off: TestShimReadsUsageWithNoWindow red in all
  three panels (told the panel's words as success);
- the provider's claudeNoWindow branch off: TestClaudeUsageNoWindowStarted
  red ("showed no usage figures: No usage window has started");
- claudeDenied back to claudeUsageDenied: TestClaudeUsageWhyKept red
  ("read as an account refused");
- usageFailed back to "Failed to load usage data" and the whole screen as
  the reason: TestShimToldWhyUsageFailed red in all three (the banner as
  the reason; the rate-limit panels told as no window), TestUsageNoWindow
  red.

Not tried: a real Claude Enterprise account; a real rate-limited panel.
2026-11-06 06:30:23 +08:00
qiqllandggbdpq b7631300ec claudetui: a successful interactive turn tells its account's allowance
Since the interactive mode replaced -p for Claude subscription turns
(43966a53, e5f66f8a, 10-31), a turn that succeeded told no
rate_limit_event, so NoteClaudeLimits never ran and the Usage page's
5h/7d figures moved only on a manual refresh (/usage). Only a turn that
ended in a <synthetic> API error told one, from its transcript row.

What changed:
- tap.js, when a main-class reply opens, also copies its
  anthropic-ratelimit-unified-* response headers into the {s, open}
  line as "h". It only reads them; the request to Anthropic is sent as
  Claude Code made it.
- tap.go (rateLimitInfo) turns them into the rate_limit_info -p tells
  (Claude Code 2.1.291): status plus unifiedWindows five_hour, seven_day,
  seven_day_overage_included (5h, 7d, 7d_oi), each only when both its
  utilization and reset are numbers, the reset rounded to a second.
- A streamed reply tells it just before its message_start, as -p does,
  so the bridge keeps it before the reply begins. A reply whose message
  was told whole from the transcript, or that never began one, keeps it
  for the turn's end (tap.settle). Only the latest is told: a kept
  reading from an older reply is never told after a later reply's
  (toldOf), whether the older one ended before or after the later one
  began, since NoteClaudeLimits keeps the last it hears.
- transcript.go: a <synthetic> API error settles the tap first, then
  tells its own rate_limit_info, so the error's reading is the newest.
- docs/subsystems/claude-subscription-bridge.md says all of this.
  The gateway is unchanged: it already turns a rate_limit_event into
  NoteClaudeLimits and limitHeaders.

Run at this head (base origin/main 6c201095):
- gofmt -l on the changed Go files: nothing
- go vet ./internal/claudetui/, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet: clean
- go test -count=1 ./internal/claudetui/: ok (62s)
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway/ -run
  'Claude|Tap|TUI': ok (60s)

Broken by hand:
- tap.go, tap.js and transcript.go at 6c201095 with the new tests: all of
  TestTapTellsReplyLimits, TestTapLimitsOfMessageToldWhole,
  TestTapErrorLimitsLast, TestShimTellsTapLimits and
  TestTapKeptLimitsNotAfterNewer (both subtests) red.
- keepLimits without `n > t.toldOf`: TestTapKeptLimitsNotAfterNewer/
  ended_after red (told 0.42 then 0.3). message_start without dropping an
  older kept reading: /ended_before red the same way.

Not tried: a turn on a real claude.ai account, so the headers were not
checked against a captured reply; Windows and WSL; the full go test
./... suite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Review: chosen over #5012, which reads the same headers but emits a
rate_limit_event the moment its line arrives. That event can land while an
unstreamed message is pending, and the bridge settles that message early.
This one tells the limits just before message_start, keeps them for a cut
stream's end, and never tells an older reply's limits after a newer one's.
ddnio's real setup-token run on #5012 shows Bun's response headers are
readable there, the same thing this reads.
Run at the pushed head on mote, go1.26.8: go test -tags nogui -count=1
./internal/claudetui/ ok (83s).
Broken by hand: with the limits before message_start turned off,
TestTapTellsReplyLimits, TestShimTellsTapLimits and
TestTapKeptLimitsNotAfterNewer are red.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-06 05:54:00 +08:00
ggbdpq 3da58c3dfc fix(plugin): end ordinary RPCs' plugin work when their caller leaves (#4678)
A plugin model list's deadline and an ordinary RPC's cancellation released
only the caller. inTime raced the hook without stopping it, and host.go
marked only gatewayRequest cancellable, so a cancelled usage or providers
call never told the host: the plugin's task kept running, the host's
pending count kept it, and repeated reads left task after task alive past
their callers. Reported with an offline host-script reproduction that
shows abort reaching none of three pending usage tasks and five model
tasks outliving their deadlines.

The cancellation path a fetch and a gateway request already take now
carries ordinary RPCs too:

- host.go marks every call but init cancellable, so a caller whose
  context ends has the host told (the existing callAborting write), the
  way it already tells it of a stopped fetch. init is left alone: a start
  that overruns is stopped whole.
- host.js registers each ordinary RPC's AbortController; an aborted
  RPC's answer, nobody's then, is not sent.
- the handler is handed the signal: usage passes it to the plugin's
  auth.usage hook as its own options, and a model list's hook options
  carry it, with the listWait deadline aborting the same controller, so
  vendor I/O that supports stopping stops at the deadline or when the
  caller leaves, whichever comes first.

Sign-in renewal and its persistence are untouched: fresh() runs before
the hooks, and an aborted RPC's handler still finishes what it saves.

Refs #4678

Generated-by: GLM-5.3-Flash (ZCode)

Reviewed and ported, narrowed: an aborted ordinary RPC is no longer
answered "Aborted" at once and dropped from pending. It stays pending
until its handler ends, as on main. host.go's stop() closes the host's
stdin and then gives a renewing host up to stopRenewing to save the
rotated token; with the early done(), host.js's own `pending === 0 &&
closed` exit ended the process at once under a cancelled call whose
handler was still renewing or saving (keepSignedIn, set, signOut, a
usage hook mid-refresh). The Go side needs no answer: an aborted call
is released once its abort is written. The signal to the usage and
models hooks, and the listWait deadline aborting the models hook, are
kept as the patch had them.
TestCancelledCallKeepsTheHostTillItsHookEnds is new: a usage hook that
ends 600ms after its abort, then Settle() closing the host's stdin; the
hook's end must reach its trace.

Run on mote (darwin arm64, Go 1.26.8, Bun via testenv): go test -tags
nogui -count=1 ./internal/plugin/... ok 102.8s; -run Plugin
./internal/gateway/ ok 52.1s and ./internal/provider/ ok 13.3s.
Broken by hand: host.js and host.go at main, tests kept:
TestOrdinaryCallCancelTellsTheHost FAIL "the host was told of the
cancellation didn't happen", TestCancelledUsageReachesThePlugin FAIL
"the plugin's usage hook was handed a signal didn't happen",
TestModelListDeadlineTellsTheHook FAIL "the models hook was handed a
signal didn't happen". host.js as the patch had it (early answer):
TestCancelledCallKeepsTheHostTillItsHookEnds FAIL "the host left
before the hook ended; trace: {"signal":"live"}...".
Not tried: the reporter's replay.py against the built host, and a real
plugin's usage hook that passes the signal to its fetch. The reporter's
"host lives on after stdin closes with a task pending" row is unchanged
by design: that is the renewal safeguard.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-06 05:53:23 +08:00
ggbdpqandIkki c6d2bd3316 library: ZCode reads the shared skills folder too (#4987)
ZCode reads ~/.agents/skills beside its own ~/.zcode/skills, but it
wasn't among the readers of the shared folder: a skill kept there
behaved as if ZCode didn't have it — its chip unlocked, a tick writing
a second link into its own folder. It reads it as the others do.

Generated-by: GLM-5.3-Flash (ZCode)

Reviewed and ported: docs/subsystems/library.md now lists ZCode among the
readers of ~/.agents/skills, as Ikki6666's own branch (a23828e81) had it;
the reporter checked the published ZCode builds for a version boundary
and found none (#4987).

Run on mote (darwin arm64, Go 1.26.8): go test -tags nogui -count=1
./internal/library/ ok 76.5s; -run 'ZCode|Shared|Always' ok.
Broken by hand: "zcode" taken out of readsShared, test kept:
TestSharedSkillReachesZCode FAIL "zcode has a second link to it in its
own folder" and "zcode's own folder got it on the sync too".
Not tried: a real ZCode install reading the skill.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
Co-authored-by: Ikki <824310075@qq.com>
2026-11-06 05:41:29 +08:00
yetone acde144a7a providers: a vendor of embedding and rerank models alone is detected on /embeddings and /rerank (heatonz)
heatonz on Discord (#help, 11-05): a custom provider whose models are only
embedding and rerank models couldn't be added. Detect APIs ("检测协议")
picked the first listed model, an embedding model, and asked it to chat on
every API, so nothing answered.

- tiny: an embedding or rerank model (catalog.ServesOf) on Chat is asked
  where the gateway's retrieve sends it: the OpenAI base's /embeddings
  ({"model","input"}) or /rerank ({"model","query","documents"}). tested
  adds no extra body there, as the gateway sends none.
- detectModel asks each API a model that chats when the list has one, so
  a chat vendor's detection is unchanged. A retrieval model is a last
  resort on Chat only. Responses, Anthropic and Gemini say why they weren't
  asked (DetectModels too).
- testModel: a saved provider with nothing to chat with tests on a
  retrieval model its list keeps apart (LiveServing). testOne asks such a
  model on Chat and never moves it to another API.
- provider.ListAll is List with Serves models kept. /api/provider/list and
  the provider's JSON carry a `retrieval` count. The add form's Fetch models
  and the saved editor say "Only embedding and rerank models are listed.
  They need no pick: ask them on /v1/embeddings and /v1/rerank." in place
  of "the list is empty". One new string, in zh, zh-TW, ja and de.
- app.js stays under TestCoreScriptBudget with no raise: +42 bytes, paid
  for by two add-form comments cut.
- The gateway already routes /v1/embeddings and /v1/rerank to such a
  provider (#765, resolveRetrievalModel by prefix or KindGroup), so nothing
  changed there.

Run (mote, at this tree on origin/main 60fe6645a):
- go test ./internal/provider ./internal/catalog: ok.
- go test ./internal/gui: ok, except TestMainWindowCorners/macOS_26_SDK,
  which is #3949 (mote is macOS 27).
- go build ./..., go vet (darwin), GOOS=linux go vet -tags nogui and
  GOOS=windows go vet of provider and gui: ok. gofmt -l: clean.
- node --test, chromium and webkit: provider-retrieval-only (new: en, zh,
  zh-TW, ja, de, with and without retrieval models, add form and saved
  editor), provider-detect, provider-add-models, azure-endpoint,
  provider-listed-as, provider-add-gemini, i18n-en-no-cjk and i18n-keys.
  94 of 95 pass. The red is i18n-keys "a plugin's words are its own", red
  on origin/main 60fe6645a too (#5332/#5327).

Broken by hand:
- New tests on origin/main's code. TestDetectEmbeddingOnly red ("The
  model BAAI/bge-m3 does not support chat" on chat, 404 on the rest).
  TestTestEmbeddingOnly red ("no model to try"). TestProviderListBeforeSave
  red (retrieval = 0).
- Retrieval models not kept out of chat probes: the mixed-list case is red
  (bge-m3 asked beside glm-5).
- tested adding the extra body to /embeddings: red (prompt_cache_key
  sent).
- detectOne asking non-Chat APIs with a retrieval model: red (404 on
  /v1/responses).
- testModel's LiveServing fallback off: TestTestEmbeddingOnly red.
- provider-retrieval-only on the old app.js with the new i18n.js: the 5
  retrieval cases red, the 5 empty-list ones green.

Not tried:
- A real embedding/rerank vendor (heatonz's is unknown). Fake httptest
  servers only.
- The whole GUI suite.
- Windows and Linux test runs (vet only).
- Models whose ids don't say embed, bge- or rerank (gte-, e5-, m3e-,
  text2vec-, voyage-) are still taken as chat models. The /embeddings probe
  goes by the id, and a Xinference model_type isn't read.
2026-11-06 05:21:05 +08:00
yetone 60fe6645a9 claude: a caller's folder Claude Code would ask about is known before the run, and the session kept (sleepy_shibe)
sleepy_shibe on Discord (magpie 0.1.2996, Claude Code 2.1.318, own
account, interactive mode): message counts 36, 65, 85, 108, 128 for one
conversation. Confirmed at origin/main 74d1cda42: a caller's folder Claude
Code asked about was passed over for untrustedFor (10 min) only. Past
that, the next run went in the caller's folder again, claudeSessions
pointed at another project folder than the conversation's session in
magpie's folder, so `from` went nil and the run was told the whole
conversation; Claude Code asked about trust, startTrusted dropped
req.branch and started from nil in magpie's folder (the deferred
from.discard() had already removed the session), told it all again.

Now, for the own account in the interactive mode, each run first decides
as Claude Code does (untrustedHere -> claudeTrusts), from
hasTrustDialogAccepted in claudeProfilePath()'s .claude.json
(provider.ClaudeTrustedProjects; a missing file is nothing trusted, an
unreadable one unknown, which goes on as before). The rules are Claude
Code 2.1.316's, read from its bundled JS (UI/zh/jh/Y0/lr): the key of the
repository's main checkout (a worktree's is the checkout it was added
from), or any folder from the run's up to the git root and never past it
(a nested repository isn't trusted by its parent), every folder above
outside a repository; NFC keys, forward slashes on Windows
(claudeTrustKey, shared with claudeTrustKeys). An untrusted folder stays
in magpie's folder with its session; a folder trusted since is run in on
the next run. When Claude Code asks all the same, startRun keeps `from`
and startTrusted goes on from it in magpie's folder with the branch.

Run (mote, at this tree on 74d1cda42):
- go test ./internal/gateway -run TestClaude: ok (118s);
  go test ./internal/provider -run Claude: ok
- GOOS=windows and GOOS=linux go vet ./internal/gateway ./internal/provider: ok
- win-run go test ./internal/gateway -run TestClaudeTrust: ok
- real Claude Code 2.1.316 in a sandbox HOME + CLAUDE_CONFIG_DIR (dummy
  key, no account), tmux, 10 cases: repo/subfolder/parent-in-repo/
  worktree-of-trusted/worktree-itself trusted -> no question; worktree
  under a trusted parent, nested repo in a trusted repo, repo under a
  trusted parent, unrelated folder -> asked; outside a repo a trusted
  parent -> no question. All ten match claudeTrustedBy.
Broken by hand:
- untrustedHere returning passedOver only (the old choice):
  TestClaudeTUIUntrustedFolderKeepsItsSession/untrusted red (helper
  started twice) and TestClaudeTUIFolderTrustedLaterRunInAtOnce red (ran
  in magpie's folder).
- startTrusted dropping req.branch and starting from nil (the old
  fallback): .../unknown red (resumed a new transcript, not the
  conversation's session).
Not tried: the owner's real account or a real turn through the gateway
(no sign-in in the sandbox); Claude Code 2.1.318 itself (2.1.316 is
installed here); a Windows or Linux real Claude Code; the full suite
before the push (it runs after, through the suite lock).
2026-11-06 04:35:12 +08:00
yetone 8fbf8e0af6 gateway: DeepSeek's own API gets an agent's images once, by file id, not on every turn (#5407)
DeepSeek's API is stateless, so every turn re-sent every inline image in
the history. Now, on api.deepseek.com only (never a relay or another
base), for a model with "flash" in its name (deepseek-flash sees images;
deepseek-v4-pro reads them as "[Unsupported Image]"), each base64 data:
image goes up once through POST /files (purpose=user_data, expires_after
a day) with the candidate's own key, and later turns name it by file id:
- Chat: {"type":"file","file_id":…} (flat, as DeepSeek's vision guide);
- Responses: input_image with file_id in place of image_url;
- Anthropic: source {"type":"file","file_id":…} plus anthropic-beta
  files-api-2025-04-14.
Shapes checked against api-docs.deepseek.com files_api, vision,
responses_api and anthropic_api. The Anthropic guide names the "file"
source type and the beta; the field name file_id is Anthropic's Files
API's, which DeepSeek says it follows. Not confirmed with a real call.

Ids are kept per key hash + image sha256 in deepseek-files.json beside
providers.json (temp+rename, unparseable file moved to .bad), reuploaded
with under an hour left. One upload per image and key however many
requests want it; a request waits at most 8s for its uploads, and what
isn't up goes inline this turn. A failed upload leaves the image inline
and rests that key's uploads for 10 minutes. A 4xx naming a file-api id
or a missing/expired file forgets the ids, uploads again and asks once
more; refused again, the request goes inline. detail:low stays inline.
`magpie provider set <id> image-files=off` turns it off (kept on GUI
save). Doc: docs/subsystems/gateway-routing.md.

Run (mote, at this tree on 498b6419f):
- go test -run 'DeepSeek|DsFileGone' ./internal/gateway: ok; -race -count=3 ok
- go test ./internal/gateway ./internal/provider ./internal/cli: ok
- go test ./internal/gui: TestMainWindowCorners/macOS_26_SDK red, the
  known macOS 27 red on mote (#3949); nothing in gui's code path changed
  but a kept field on save
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok;
  go build ./... and GOOS=linux -tags nogui ok

Broken by hand, each red: host check removed (InlineElsewhere), switch
ignored (ImageFilesOff), singleflight off (FilesOneUpload), breaker off
(UploadFailsInline), key left out of the cache key (FilesPerKey and
others), beta not added (ImagesByFile/anthropic), retry off
(FileGoneUploadsAgain), store not read from disk (FilesKeptOnDisk), the
flash check removed (InlineElsewhere), the 8s wait cap removed
(UploadSlowGoesInline).

Not tried: a real DeepSeek key (none available in the sandbox), so the
exact refusal text for a gone file and the Anthropic file_id field are
unconfirmed against the live API. Not covered: a custom_tool_call_output's
images (walkImages doesn't read it); files aren't deleted (they expire in
a day).
2026-11-06 02:46:46 +08:00
yetone 498b6419ff claude: a turn Anthropic refuses in the interactive mode as a third-party app's is asked again as claude -p, and the agent's prompt is remembered
Raven (Discord #general): Cindy with Pi as its engine, routed through
group/auto to a Claude subscription, failed every turn with "Anthropic
refused an interactive-mode turn on claude-opus-5-5 as a third-party
app's", and the message told them to turn the interactive mode off in
Settings, which makes every request of every agent run as -p (about twice
the plan count).

Now, with the interactive mode on:
- a refusal carrying "Third-party apps now draw from your extra usage",
  met before a byte of the reply reached the client (stream head, or a
  whole reply with no parts), is asked again once as claude -p
  (redoAsPrint); the client sees only the -p answer;
- the agent's system prompt (sha256 of its first 2KB, billing header
  dropped, so Pi's trailing <cwd> doesn't change it) is remembered for
  12h, and its next turns go straight to -p (wantTUI, req.tuiRefused,
  clientCache.print) while every other agent stays interactive;
- a refusal after the reply had begun (keepalive sent, or text said) is
  not redone, so nothing is spent twice; the prompt is still remembered
  and the message now says magpie runs its next turns as -p: ask again;
- a -p run that is refused too fails as before ("run as claude -p"),
  once, no loop;
- the setting is untouched; with it off (claudePrintMode) everything is
  -p as before. The run is the real claude binary, nothing else changed
  in what is sent.

This reverses the #4503 call (fbbdf6e05, v0.1.2754: no automatic -p redo)
and the 10-31/11-01 "nothing ever runs as -p with the interactive mode
on", for this refusal only. The switch's foot, the Settings text (en, zh,
zh-TW, ja, de) and docs/subsystems/claude-subscription-bridge.md say so.

Run (mote, at this head rebased on 1100ed649):
- go test -run 'ThirdParty|TUIRefusal|ClaudeTUI|ClaudeSubscription|ClaudePrint'
  ./internal/gateway/ ok; Budget/i18n tests in ./internal/gui ok
- gofmt -l clean; go vet ./internal/gateway (darwin, GOOS=linux,
  GOOS=windows) ok; GOOS=windows go vet ./internal/gui ok. GOOS=linux go
  vet ./internal/gui fails in wails' cgo-only linux files on mote, the same
  on main, untouched here.
- GUI, chromium and webkit: claude-mode, claude-tui-setting,
  claude-quota-onboarding, mobile-web, i18n-keys, gui-zh-tw, gui-ja,
  gui-de: 57 pass, 6 fail in each engine; the fails are i18n-keys "a
  plugin's words are its own" (#5327, #5332) and mobile-web (#3952,
  #5013), the same 6 at origin/main 1100ed649 alone.
- Red on the old code: the new tests run against 1d704f819 all fail (400,
  the old "turn the interactive mode off" message).

Broken by hand: dropping len(col.res.Parts)==0 from the whole-reply redo
turns TestClaudeTUIThirdPartyRefusalAfterWordsNotRedone/whole red;
dropping the refusedTUI call turns ...PromptRemembered, ...AfterStart and
...AfterWords/stream red.

Tests use the real Pi 1.1.0 system prompt (testdata/workdir/pi-1.1.0.json)
with its cwd changed per conversation.

Not tried: a real Claude account (no refused turn reproduced against
Anthropic; the refusal text is the one the reporter's log and #4503
carry). A -p run continuing with tool results under a remembered prompt
(the wantTUI resume path) has no test of its own.
2026-11-06 01:20:14 +08:00
yetone 1d704f8190 codex: OpenAI's threads follow a provider of the user's at the top, where Codex resumes them
harris on Discord (the Codex app, after switching from CC Switch):
"This chat uses openai, but your current provider is custom. Switch to
openai to continue." CC Switch left its "custom" as config.toml's
model_provider, which magpie keeps since #4347, and Codex 0.166 resumes
a thread only on the provider it is on now. Every thread started on
OpenAI before was refused, and switching to OpenAI would refuse
custom's threads instead, so the user was stuck. Nothing moved them:
bringOver moves only onto magpie, bringBeside only from such a provider
onto OpenAI.

lendOwn (each Sync) moves OpenAI's threads onto that provider, as
bringBeside does the other way: in place at OpenAI's length, by the row
for a paginated thread, the last 30 days rewritten with a copy kept
otherwise. The ids go in stash codex.lent; giveLent returns exactly
those to OpenAI once Codex is on it again (CC Switch's official card),
keeps the record while Codex is on that provider or on magpie, and
drops it on any other. Nothing moves while a profile names openai,
after the user disconnected Codex, or from a distro's Codex.
TestCodexThreadsComeBackOffMagpie/by_hand expected an OpenAI thread to
stay on OpenAI with custom set by hand at the top, the stuck state
itself; it now expects it on custom. docs/subsystems/agent-wiring.md
says so.

Run (mote, go 1.26.8): go test -count=1 ./internal/agent/ ok (250s);
GOOS=windows, GOOS=linux and native go vet ./internal/agent/ ok;
gofmt -l clean.
Broken by hand: Sync without lendOwn, TestCodexOwnProviderTakesOpenAIThreads
red (thread left on "openai", rollout not on custom); without the
disconnected and profile guards, TestCodexOwnProviderLeavesOpenAIThreads
red for both cases.
Not tried: a real Codex app resuming a moved thread on a real relay;
harris's config.toml wasn't seen, so the "custom" here is CC Switch's
relay table as it writes it. A thread moved from the ChatGPT backend to
a relay carries its encrypted reasoning, which a relay on another
account may not accept; the thread then fails on the relay as a
switch to it by hand would.
2026-11-06 00:51:01 +08:00
yetone 845e324b13 liveagent: each model on its own API, and the request format the user picks stays (xiaoxiaofei)
xiaoxiaofei on Discord: "magpie 默认导入的是 message 格式的,要可以自定义请求格式".
magpie wrote one LiveAgent provider, "magpie", type claude_code with
api anthropic-messages, for every model. K-brain asks all of a
provider's models on the provider's one API (routing/client.go builds
the client per provider; PiModel.api is only validated), and LiveAgent's
settings lock an Anthropic provider's API: only an OpenAI provider
(type codex) has a request format to pick (ProviderModalView.tsx,
resolveProviderApi; K-brain settings_provider.go accepts
openai-completions and openai-responses). So the format couldn't be
changed, and a GPT served on Responses was translated from Messages on
every turn.

Now, as dsh's routes do (dshKinds), each model goes on the provider of
the API it is served on natively (catalog.Model.APIs):
- magpie: type codex, Chat Completions, baseUrl the gateway's /v1, for
  every model with no Responses or Messages API of its own (groups, Chat
  providers' models);
- magpie-responses: type codex, Responses, baseUrl /v1;
- magpie-anthropic: type claude_code, Messages, baseUrl the root (K-brain
  appends /v1; for OpenAI it appends only /chat/completions or
  /responses, hence /v1 there).
A codex provider is written with api and requestFormat, as LiveAgent's
settings write one; when the user switches it in LiveAgent, a sync keeps
their format (one LiveAgent doesn't offer goes back to magpie's). A
provider left with no model is taken out. A config.json from before (all
on one claude_code "magpie") is moved on the next sync: each model brings
its record (the user's display name) and whether it was turned off, and
a default/compact/task pick of it follows it to its new provider.
Disconnect takes all three out. Docs: reference.md, agent-wiring.md.

Run (mote, through mote-run):
- go test -tags nogui ./internal/agent -run '^TestLiveAgent|Key': all pass,
  new TestLiveAgentRequestFormat and TestLiveAgentFormatMove included.
- go test -tags nogui -timeout 45m ./internal/agent: ok (320s).
- GOOS=linux and GOOS=windows go vet ./internal/agent: clean; gofmt -l clean.
- K-brain 507f560 (the version LiveAgent af89ea7 pins), with Go 1.27.0
  on mote: config.LoadFile on the config.json magpie writes in
  TestLiveAgentRequestFormat loads it, and routing.ClientForProvider
  builds *ai.OpenAI at http://127.0.0.1:3425/v1 for magpie,
  *ai.Responses at /v1 for magpie-responses and *ai.Anthropic at the
  root for magpie-anthropic (a throwaway test, not committed).

Broken by hand (a copy), each turned a test red:
- the user's format not kept -> TestLiveAgentRequestFormat;
- no carried record from another provider of magpie's -> FormatMove;
- picks not following their model -> FormatMove;
- Responses models left on magpie -> both;
- an emptied provider not taken out -> FormatMove;
- turned-off not carried to the new provider -> FormatMove.

Full suite at c24915f04 (the change before this one), go test -timeout
45m ./... on mote: 86 packages ok, internal/gui red on
TestMainWindowCorners/macOS_26_SDK (#3949) and
TestPanelHiddenByWailsMarksPageOutOfSight (#5322), both filed, both
macOS 27 on mote.

Not tried: the LiveAgent app itself (its UI showing the three providers
and switching a format, then a real turn through the gateway); LiveAgent
on Windows or Linux; a real config.json of a user's.
2026-11-06 00:48:29 +08:00
yetone 814a625a24 usage: the top refresh reads saved Claude accounts again (#5380)
The tray panel's Allowances refresh said "Allowances refreshed" but a
saved, non-active Claude account kept its old reading: claudeWindows runs
Claude Code's /usage for a saved account only under savedRefresh, which
only that account's own card refresh sets.

Now a refresh of every allowance by hand asks usage/quotas?asked=1&all=1
(AskEveryClaudeUsage). It marks its ask generation in claudeEveryAsked,
and for claudeEveryFor (2 minutes) each saved account not read since is
read as its card's refresh would, under the same due check, the
30-second per-account floor and the same running holds. Opening the
Usage page or the Allowances tab (?asked=1 alone), the timed refresh and
every background read are unchanged, so nothing polls more. Callers:
the panel's top refresh (refreshPage "allowances"), the Usage page's
refresh and sidebar reload (refreshUsage -> loadQuotas("all")),
Routing's Read allowances, and the TUI's r. loadQuotas no longer lets a
lesser load on its way (an opening's asked read) swallow a Refresh.

Siblings: saved Codex accounts are already read anew on every asked
whole read (loginReading over HTTP after AskUsage clears the cache), so
Codex is unaffected. PlanQuotas and KeyBalances keep their 1-minute cache
on an asked read; left as is. The core scripts' budget is not raised:
the ~140 bytes are paid for by two loadQuotas/quotasOpened comments cut.

Run (mote, at 807341cdc on origin/main 5666cb049; rebased onto
505534992 after, which touches only internal/plugin and internal/proc;
the core script budget rechecked at the pushed head, 193 bytes under):
- go test ./internal/provider/ ./internal/gui/ ./internal/tui/ ok
  (TestMainWindowCorners/macOS_26_SDK red on mote's macOS 27, #3949;
  green when run with the -run set at the pushed head)
- go vet the three packages; GOOS=linux go vet -tags nogui and
  GOOS=windows go vet of them ok; go vet provider+tui in WSL ok; gofmt -l
  clean
- GUI, Chromium and WebKit, en+zh: refresh-page, claude-usage-asked,
  usage-refresh, routing-read-allowances, allowance-open-read,
  quota-refresh-order, usage-refresh-flight all pass. A wider set of 119
  files (quota*, panel-quota*, usage-*, allowance*, routing-read/account,
  menu-*, tray-*, i18n-keys) has reds in 6 files, identical at the parent
  commit and filed: i18n-keys #5332, menu-input-scroll #3402,
  tray-cell-click #5215, usage-agents-hide #3414, usage-fold #3415,
  usage-ledger #5048.
- New TestRefreshEveryReadsSavedClaude: an opening's ask runs nothing
  for saved accounts; a top refresh reads each anew; an unasked read and
  a plain asked read after it don't; rapid refreshes keep the floor; the
  every-ask lapses after claudeEveryFor.

Broken by hand: dropping "|| every" from claudeWindows' read turns
TestRefreshEveryReadsSavedClaude red ("top refresh read no allowance of
saved max@x.com"); the panel's refreshPage back on loadQuotas(true)
turns refresh-page's panel subtests red in both engines.

Not tried: a real saved Claude account's /usage run from the real tray
panel (the test fakes Claude Code's /usage per account directory); the
full GUI suite; the de/ja/zh-TW GUI runs (no string changed).
2026-11-06 00:35:39 +08:00
yetoneandbaijiu666 5055349922 plugin: a host ended ends what its plugin started, at any depth (#5402)
A plugin host was ended with cmd.Process.Kill(), the host alone. A
plugin that starts a browser or a daemon (magpie-magicrew-auth's
headless Edge behind a WAF) left it running with no parent: 620
msedge.exe (6.8GB) and 382 temp profiles (57GB) in an hour on one
Windows machine. Bun's own job ends its direct children with it on
Windows, but lets their children out, so Edge's gpu/renderer processes
lived on. On macOS and Linux nothing ended them at all.

The host now starts as a proc.Tree (new Output.StartTree): a session of
its own on Unix, a job (kill on close) on Windows. host.kill kills the
tree; stop (after stopWait, so EndHosts, Restart, a moved proxy, an
update) and the line-too-long path both use it. A host that ends by
itself is swept by the tree's Wait: the Unix group is killed, the
Windows job closed. Nothing outside the host's own session or job is
signalled, so magpie's own process group is never reached.

Ported from baijiu666's fix/plugin-host-tree (a8172a1), which called
proc.End then Process.Kill. Reviewed against it:
- macOS/Linux: proc.End is SIGTERM to the host pid alone, followed at
  once by SIGKILL; host.js has no SIGTERM handler and the host was in
  magpie's own process group with no session of its own, so nothing it
  started was ended. Red on mote and WSL, same as main.
- Windows: endTree walks living parents, so it covers the killed host
  but not a host that ends on its own (crash, process.exit) or one that
  leaves when its input closes; those were red on Windows too.
- Its test was Windows-only and checked a direct child, which Bun's job
  already ends: the new test checks a grandchild, through a real host.

Run (TestHostEndedEndsWhatItsPluginStarted: a real Bun host whose
plugin starts a child that starts another; subtests stop / killed /
own end):
- origin/main 125fd93ec: red 3/3 on macOS (mote), Windows (win-run) and
  Linux (wsl-run).
- baijiu666's host.go: red 3/3 on macOS and Linux; on Windows red on
  stop and own end, green on killed.
- this change: green 3/3 on all three; -race green on mote and WSL with
  TestEndHostsLeavesNoChild, TestHostReapedWhileItsChildHoldsStdout and
  TestHostRunsAsMagpieBun.
- go test ./internal/plugin ./internal/proc: ok on macOS and Linux; on
  Windows ok except TestPiPackage, red the same at 125fd93ec (no `sh`
  on PATH there; #4115).
- go vet: darwin, linux, windows (./internal/... for windows). gofmt -l
  clean.
Broken by hand: the old and baijiu666 trees above are the fix taken out.
Not tried: a real headless Edge plugin (magpie-magicrew-auth) on
Windows; a plugin reading /dev/tty (the host has no controlling
terminal now, as every proc.Tree child).

Co-authored-by: baijiu666 <198813975+baijiu666@users.noreply.github.com>
2026-11-06 00:34:42 +08:00
yetone c24915f04e library: LiveAgent in the MCP and Skills pickers (zero2sin)
LiveAgent was missing from the Library's MCP and Skill agent pickers
(zero2sin on Discord #feedback). It is now a target, written in its own
engine's formats, read from K-brain 507f560 (the one LiveAgent af89ea7
pins), not guessed:

- MCP: <data dir>/config.json.live-mcp.json (cmd/kn/backend.go,
  internal/mcp/live.go LiveSettings): {"servers":[{"id","enabled",
  "transport":"stdio"|"http","command","args","env" | "url","headers",
  ...}],"selected":[...]}. Streamable HTTP only, so SSE is refused.
  ${NAME} in env and headers resolves as K-brain's secret refs
  (internal/config/secret.go). The user's servers and their
  description/enabled/cwd/timeoutMs/policy/auth/... are kept; untouched
  servers are written back byte for byte (json.RawMessage). A non-empty
  selected gets magpie's server added (or it would have no tools) and
  taken out on remove, never the last one. With no file yet, K-brain
  reads config.json's "mcp" object (settingsFromConfigs), so the first
  write carries those servers over the way K-brain's own first save
  does. A new file is 0600 like K-brain's. A file K-brain itself could
  not parse is not written over.
- Skills: <data dir>/skills, as copies (Target.Copy): K-brain refuses a
  link in a skill's path (safePath) and ScanDetailed walks past one. A
  skill there loads only when picked in skills-settings.json
  global.selected (Manager.Effective), so syncLiveAgentPicks picks each
  copy magpie makes once (Applied.Picked), never again after the user
  unpicks it, and unpicks it when the copy goes. Names K-brain refuses
  (validManagedName) are never put in selected, since its next save
  would fail on them. Its built-in skills-creator/skills-installer are
  not offered for import.
- Not added: instructions (K-brain's brain.md is its own memory file).
  A server written while LiveAgent runs is seen at its next start (the
  app holds the list in memory and saves it whole).

Run (mote-run, at base 326e72f4c):
- go test -run LiveAgent ./internal/library/: 7 tests ok
- go test ./internal/library/... ./internal/agent/ ./internal/gui/:
  library ok, agent ok, gui FAIL only TestMainWindowCorners/macOS_26_SDK
  (#3949, macOS 27 on mote, no library code)
- GOOS=linux and GOOS=windows go vet ./internal/library/: clean;
  gofmt -l: clean
- node --test of 100 GUI files (library-*, *skill*, *mcp*, i18n-keys)
  in chromium and webkit: 1941 of 1946 pass. Red: i18n-keys "a plugin's
  words are its own" (two Go test files elsewhere say a plugin's word)
  and found-skill-pick-remove "en at 420px" in both engines; this change
  touches no GUI file.
- Rebased on origin/main 125fd93ec and run again there:
  go test ./internal/library/ ok; found-skill-pick-remove and i18n-keys
  red the same (en at 420px both engines; "a plugin's words are its
  own"), and red the same on a clean origin/main 125fd93ec worktree:
  filed as #5013 and #5327/#5332.

Broken by hand, each red: Copy=false (TestLiveAgentTarget,
TestLiveAgentSkills: a link); no syncLiveAgentPicks call (nothing
picked); re-picking every sync (TestLiveAgentSkills: xlsx picked again
after the user unpicked it); no built-in skip (found lists
skills-creator); no selected append (TestLiveAgentMCP); no config.json
seeding (TestLiveAgentMCPFromConfig); no chmod (0644); no name check
(TestLiveAgentSkillsNewSettings: My_Skill picked).

Not tried: a real LiveAgent app reading the written files (no LiveAgent
on mote or here); Windows and Linux test runs (vet only).
2026-11-06 00:26:59 +08:00
yetone 2df5d40ee3 usage: a ChatGPT API account's calls count in the same ChatGPT account's Codex window estimate (jctaoo on Discord)
A ChatGPT account signed in through Sign in with ChatGPT (chatgpt-api) and
to Codex draws on one plan's five hours and week. Only the Codex card reads
those windows, and its whole-window estimate (usage.windowHolds) keyed the
ledger's calls by provider + account, so the chatgpt-api calls were never
counted and the estimate came out low.

provider.SamePlanAccounts maps each chatgpt-api account to the Codex
account that is the same ChatGPT account, matched on the tokens'
chatgpt_account_id and chatgpt_user_id, both known and both equal, never
on a name: two Team seats of one email share the name and the user id,
not the account id. A token that names neither matches nothing, as
before. windowHolds (current and HistoricalWindowHolds) counts a matched
account's calls as the Codex account's, dry runs included. chatgpt-api
alone (no Codex account) is unchanged: its card reads no windows, so
there is nothing to estimate. Routing's caps and pace go by the vendor's
own reading of the windows and don't sum the ledger, so they are
unchanged; the per-provider account breakdown in the summary stays per
provider on purpose.

Run (mote, at this tree):
- go test ./internal/usage/ ./internal/provider/: ok.
  ./internal/gui/: TestMainWindowCorners/macOS_26_SDK red, the AppKit
  test filed as #3949 (macOS 27 on mote), untouched by this change;
  the rest ok.
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of
  internal/usage and internal/provider: ok. gofmt -l: nothing.
- quota-holds.test.cjs in Chromium and WebKit: 2/2 each (the GUI only
  renders the server's holds; no asset changed).
Broken by hand:
- remap removed in windowHolds: TestWindowHoldsCountsTheSameChatGPTAccount-
  ThroughTheAPI red, "whole 5 hours 2500 tokens, want 10000" and "the
  personal account holds 2500 tokens, want 10000".
- account id ignored (user id only) in SamePlanAccounts: red, "the Team
  seat holds 12500 tokens, want 5000" and "whole 5 hours 10000 tokens,
  want 2500" (token naming no account).
Not tried: a real chatgpt-api sign-in. No such account on this machine,
so whether OpenAI's Sign in with ChatGPT tokens carry chatgpt_account_id
and chatgpt_user_id (Codex's do, checked on the real Codex logins here)
is not verified; if they don't, nothing is matched and the estimate stays
as before. GUI suite in other languages not run (no strings changed).
2026-11-05 23:57:33 +08:00