codex: threads of the provider Codex was on before magpie follow it onto magpie (hxy920830 on X)

hxy920830 on X: "magpie希望codex接入的时候自定义供应商名称,我现在名称被替换成了
magpie,原来的会话可以看到,但是加载不出来模型了". Codex had been on a
provider of the user's own (a relay's [model_providers.<id>] table, or CC
Switch's "custom"). Wired with no ChatGPT sign-in, magpie sets
model_provider = "magpie". bringOver moved only OpenAI's threads onto
magpie, so the relay's threads stayed on their provider. From Codex 0.166
(codex-rs app-server config_manager.rs load_for_resume) a thread resumes
only on the provider Codex is on now. The app lists them (thread/list
with model_providers [] lists every provider) but opening one stops at
modelProviderMismatch: "This chat uses <id>, but your current provider is
magpie". Nothing a user can set changes that, so a setting to rename the
provider wouldn't be needed. The threads should just open.

bringOver now moves the threads of the provider Codex was on before magpie
(stash codex.provider, "openai" when none was set), not only OpenAI's:
- an id of magpie's length ("custom") is relabelled in place
  (RelabelCodexThreads), then packed ones from the last 30 days
  (MovePackedCodexThreads), as OpenAI's already were;
- any other id ("myrelay") can't be written in place, so the threads of
  the last 30 days, plain or packed, are rewritten with a copy kept in
  the trash, newest first, 128 MB a sync (new
  sessions.MoveRecentCodexThreads, sharing MovePackedCodexThreads' body
  with packedOnly off). Older ones are left for Sessions' Move/Resume.
#887's guarantee still holds where it matters. Threads of any other
provider stay put. OpenAI's stay when Codex was on another provider. No
threads move for a provider a profile names (the user picks it with -p),
for cc-switch-official (bringOfficial handles it), or for a distro's
Codex. The Disconnect puts the user's model_provider back and bringBack
returns the threads to it, and CC Switch switching back to that provider
does the same. If Codex leaves magpie for a different provider,
bringBack hands them to that one, as it already did with OpenAI's moved
threads. profileNamed moved up so bringOver can use it.
docs/subsystems/agent-wiring.md says so.

Tests:
- TestCodexThreadsFollowMagpieIn "on a provider of the user's before"
  used to assert that the custom thread stays. Now it moves to magpie in
  place, with no copy, and goes back to custom at Unwire, with
  model_provider custom restored.
- New subtest "on a relay's table of another length": myrelay's plain
  and packed threads move with a copy kept, a 40-day-old one stays,
  OpenAI's stays, and everything goes back at Unwire.
- New subtest "on a provider a profile names": the thread stays.
- New TestMoveRecentCodexThreads: newest first, a copy each, an old
  thread and another provider's stay, and the packed-only move still
  leaves a plain thread.

Run at this tree (on origin/main 823e7c250), on mote through mote-run:
- gofmt -l internal/agent internal/sessions: clean.
- GOOS=windows go vet, GOOS=linux go vet -tags nogui and go vet (darwin)
  of ./internal/agent ./internal/sessions: ok.
- go test -count=1 -timeout 45m ./internal/agent ./internal/sessions: ok
  (296s, 85s). An earlier run before the last tweak (plain file must be
  regular) was ok as well.

Broken by hand:
- bringOver back to OpenAI-only plus packedOnly forced: three of the four
  new assertions in TestCodexThreadsFollowMagpieIn and
  TestMoveRecentCodexThreads fail ("thread ...c3 on "custom", want
  "magpie"", "moved [only the packed one], want the plain then the packed
  one").
- the profileNamed guard dropped: "on a provider a profile names" fails.

Not tried: a real Codex 0.166 app or CLI resuming a moved relay thread
(this reasons from the codex-rs source for rust-v0.166.0, and earlier
commits record real 0.166 resuming moved threads); a real CC Switch
switch; the whole ./... suite (mote was at load ~75-100 with two other
sessions' full suites); a Windows or WSL run.
This commit is contained in:
yetone
2026-11-04 22:52:05 +08:00
parent 6bef4fe043
commit d6e3a36ffc
5 changed files with 255 additions and 40 deletions
+1 -1
View File
@@ -153,7 +153,7 @@ something else shows up as drift.
- Codex's sign-in (`login`) is ChatGPT (`""`, the default), Always ChatGPT (`chatgpt`) or magpie API (`api`). With ChatGPT, magpie's models join Codex's own beside the sign-in (`openai_base_url`), and while the Codex app holds the ChatGPT account Codex is signed in to (`codexUsedUp`, `provider.CodexUsedUp`: OpenAI no longer allows the account and it has no credits left, a workspace still within its overage excepted), magpie is made Codex's provider (`codex.out`): the Codex app sends nothing at all on an account it holds, a magpie model's turn included (#540), and as a provider of its own magpie is past that. A window at 100% with credits left doesn't count, and Codex stays signed in. Sync puts it back beside the sign-in once the account has room. Always ChatGPT never does that: Codex stays in its ChatGPT state, and the Codex app may send nothing till the account has room, while Codex CLI's turns still reach magpie by the base URL, and its routing and other accounts serve them. Codex's app-server answers `account/read` and `getAuthStatus` with no account and no token for a provider without `requires_openai_auth`, and the Codex app then switches to an identity of no account: its ChatGPT mode's chats and projects ("Work") are gone, with its Chrome control (#1824) and cloud tasks, while magpie's models still answer (Qyburn3 on X). So `[model_providers.magpie]` says `requires_openai_auth = true` while Codex has a ChatGPT sign-in with room (`openaiAuth`: `codexChatGPTKnown` and not `codexUsedUp`), magpie API included; Codex still sends magpie's key (`experimental_bearer_token`) and no ChatGPT-Account-ID, with the same tools (tried with ChatGPT.app 26.1021 and its codex 0.164.0-alpha.11 against a capturing server). Not for an API key alone (Codex drops its image tool for a provider requiring OpenAI auth, `uses_openai_actor_authorization`), no sign-in (the app would ask for one), or a sign-in the Codex app holds: the app would read its rate limit again and grey Send for magpie's models too, which `codex.out` exists to get past. Sync writes the key in or takes it out as the sign-in or the allowance changes, an older magpie's table included (`authStale`), and the key is part of the app-server's route (`codexAppRoute`), so the Codex app is restarted onto its account (`TestCodexMagpieProviderKeepsChatGPTAccount`, `TestCodexAppRouteFollowsOpenAIAuth`). While magpie is Codex's provider for `codex.out` the app has no account till the reset, so the Agents row opened over that takeover names browser use among what is off and offers Keep on ChatGPT right there (`keepChatGPT`, posting `login` = `chatgpt`); picked on one of Codex's own models taken over (`codex/<model>`), `set` puts Codex back on its sign-in at once, `model_provider` and `model_catalog_json` gone, where it had left magpie the provider (eddie.zhan on Discord, `TestCodexOwnModelOutThenKeptOnChatGPT`). While magpie is Codex's provider (magpie API, or `codex.out`), `Joined` reports false although the `codex.joined` mark stays for Sync's way back: the Agents row said Codex's own models stay in `/model` beside magpie's, the ChatGPT state the Codex app blocks sending in, and the app only leaves that state once it is restarted (#2267, `TestCodexProviderIsNotJoined`). A Codex that reaches the gateway from another machine (a WSL distro under NAT, or `MAGPIE_ADDR` pinned beyond loopback, `onAnotherMachine(at.gw())`) is wired as one with no ChatGPT sign-in (`chatGPT()` is false there): never joined or beside, since beside its sign-in it would send its ChatGPT token to `/backend-api/codex`, and from there the gateway takes a named key alone, so every request was a 401 (#2145, `TestCodexBeyondLoopbackNotJoined`). magpie is its provider and it sends `gwKey()`, the LAN sharing key; one of its own models picked goes straight to OpenAI on its sign-in.
- Whether Codex is signed in to ChatGPT is read from its auth.json or keychain item (`codexChatGPTKnown`, `provider.CodexSignInKnown`). Codex rewrites auth.json in place when it refreshes its tokens (codex-rs `FileAuthStorage::save` opens it with truncate), so a read in that moment finds it empty or cut off, and a keychain read can fail for a moment. Such a read is unknown, and Codex is taken to be as magpie last wired it (joined, beside, or `codex.out`); only a sign-in that isn't there (no auth.json, no item) or holds no ChatGPT token is "not signed in". Taking an unknown read for "not signed in" made Sync or a pick move Codex from beside its sign-in to magpie as its provider, with no `codex.out` to bring it back, and the Codex app showed "magpie" for its account and magpie's catalog for its models, on and off (lucy on Discord, v0.1.1394; `TestCodexHalfWrittenAuthKeepsSignIn`, `TestCodexHalfWrittenAuthKeepsOut`, `TestCodexSignInKnown`). A top-level `forced_login_method = "api"` in Codex's config.toml (another tool or guide writes it; magpie never does) counts as no ChatGPT sign-in: Codex logs such a sign-in out as the TUI starts and its app-server reads no account (codex-rs `enforce_login_restrictions`, `load_auth`), so wired beside it the Codex app asked for a sign-in and offered an API key alone (Tiger on Discord). magpie is then the provider without `requires_openai_auth`, and Codex needs no sign-in. The line is the user's and stays; taking it out brings the ChatGPT account back to the Codex app (`requires_openai_auth`) (`TestCodexForcedAPILoginIsNoChatGPT`). So does a sign-in OpenAI refused to refresh for good (jjt on Discord, #4308): Codex keeps its auth.json as it was and the refusal in memory alone, and wired beside it every turn, magpie's models too, failed at Codex's workspace routing discovery (`/wham/accounts/check`, 401). magpie refreshes Codex's sign-in itself (`codexTokenRenewing`, on its usage read), and a refusal Codex takes as permanent (codex-rs `request_chatgpt_token_refresh`: `refresh_token_expired`, `_reused` or `_invalidated`, a 400 `invalid_grant`, or a 401 carrying an error code; `codexRefreshGone`) is kept for that Codex home as the refused refresh token's hash (`codex-signin-gone.json`, only while the store still holds that token). `codexChatGPTKnown` reads that sign-in as none (`provider.CodexSignInGone`), and magpie is the provider without `requires_openai_auth`; the user's auth.json stays. A 5xx, a network error, a 401 with no code, or a token Codex replaced meanwhile marks nothing, and a record that can't be read is unknown. Signed in again, the refresh token is another one and counts at once; `KeepOnAnAccountWithRoom`'s loop (`noteCodexGoneNow`) has Sync write `requires_openai_auth` back within minutes (`TestCodexGoneSignInIsNoChatGPT`, `TestCodexSignInGoneWhenRefusedForGood`). In left-alone mode magpie doesn't refresh Codex's sign-in, so nothing is recorded there.
- Codex signed in to ChatGPT and not connected still gets `openai_base_url` while more of its ChatGPT accounts are on in magpie (`failover`, stash `codex.failover`; with a CC Switch mirror as its provider, the mirror's `base_url` and `codex.mirror_failover`), so a turn its own account has no allowance for goes on to the next — never for a Codex that reaches the gateway from another machine, where that path takes a named key alone and the failed-over turn came back a 401 (#2145, `TestCodexFailoverBeyondLoopbackNotWritten`); Sync takes one it wrote before off again. That Codex is `FailingOver`: not `Wired`, yet its requests go through magpie. The Agents row says so and what turns it off (`FailoverSaid` in the CLI and TUI, `failover` in `/api/state`, a button to Providers › Codex in the GUI), and the gateway hands it only its own models from `/backend-api/codex/models` (`CodexOwnOnly`, set on `gateway.CodexOwnOnly` by main; its ETag carries `provider.CodexOwnListTag`, and Sync ages a `models_cache.json` without it). A connected WSL Codex shares the gateway path, so while one is connected every Codex gets magpie's models (#1385). A base URL the user wrote by hand (#856) isn't failover's and stays a plain not-connected row. A Codex the user disconnected gets no failover till they connect it again. The app serving the gateway takes failover out as it quits (`EndFailover`, `EndCodexFailover` in `OnShutdown`), so a Codex left on its own goes straight to OpenAI rather than retrying a gateway that's gone (Leon920717 on X); the next start's Sync writes it again. Codex's app-server read the old base URL as it started and keeps it, and `KeepCodexDaemonCurrent` ends with magpie, so `EndCodexFailover` restarts it there when no codex session is on it (`codexDaemonCheck`); with one on it, it stays on the gone gateway until the user restarts it (thisisvainxx on X: "several restarts"). So does every thread already open, in the Codex app above all: each turn went to the closed port, and a system proxy in between answered `503 Service Unavailable: Unknown error, url: http://127.0.0.1:3425/backend-api/codex/responses` until magpie was opened again (idkatbro on X; without a proxy Codex says "Connection refused" and reconnects). Masking plays no part: it runs only in the gateway, and its own 503 says why. When `EndCodexFailover` took failover out, the gateway's address is this computer's and Codex runs (`provider.CodexPIDs`: the app's app-server, the daemon, the CLI's sessions, an editor's codex), `OnShutdown` starts `magpie codex-relay` apart from itself (`agent.RelayOpenCodex`, `codexrelay.Start`; Setsid, or a detached process on Windows). It waits up to 60 s for the gateway to let go of the port, then serves only `/backend-api/codex/*` from Codex on this computer (a loopback Host, no Origin) and passes each request to the ChatGPT backend as the gateway passes a turn of Codex's own: the same item-id, compaction and Claude-seal rewrites, zstd and proxy, signed by the caller's own Authorization (`gateway.CodexRelay`). A magpie model, a turn on one of magpie's accounts, and a turn masking would have masked are refused with a readable 400 instead (Codex retries a 5xx five times over and shows a 4xx at once); anything else says magpie isn't running, never as magpie (`ServedBy`). It ends once every Codex process it was left for has and nothing is in flight, and the next magpie to serve the gateway asks it to leave (`codexrelay.Leave` in `ListenAndServe` and `serveGatewayLocked`; a POST with the token from `codex-relay.json`, 0600 in magpie's folder): it closes its listener at once and finishes the turns it streams, up to 30 minutes. `TestCodexRelay*`, `TestLeaveFreesPortAndFinishesStream`, `TestEndsWhenCodexGone`, `TestLeaveNeedsToken`. Not covered: a connected Codex (magpie's models, left pointed at magpie by design), a Codex in a WSL distro, and a magpie that ends without quitting. Every restart magpie makes runs `codex app-server daemon restart` as its own responsible process on macOS (`proc.CombinedOutputOwn`, a disclaimed `posix_spawn`): the daemon works in the folder of each codex attached to it, and as magpie's child the first codex in ~/Desktop had macOS ask for the Desktop folder in magpie's name (reformed9448 on Discord; `TestRestartedCodexDaemonIsNotMagpies`). A magpie built without cgo (the CLI) still restarts it as its own child. A connected Codex keeps magpie as it quits: its model is one of magpie's, and Disconnect is what puts its own config back. A magpie that ends without quitting (killed, a crash, `magpie serve`) leaves failover in place.
- A Codex thread keeps the provider it was started on. While a magpie model is on, CC Switch's provider tables go through magpie too (`takeTables`), and get their own base URL back when Codex steps off magpie (`giveTables`, stash `codex.tables`). CC Switch's OpenAI mirror (a table of another id, `name = "OpenAI"`, `requires_openai_auth`, no `base_url`) isn't reached by `openai_base_url`, which takes only the built-in provider to magpie: a thread started on it and reopened went straight to ChatGPT, which refused the magpie model picked in it, and magpie never saw the request (#1796). While Codex goes to magpie by the base URL, `takeMirrors` gives each such mirror magpie's ChatGPT backend as its `base_url` (stash `codex.mirrors`), and `giveMirrors` takes it off again; a mirror a profile names, or one whose `base_url` was changed since, stays as it is. Moving the threads onto another provider is the Sessions page's Move (#887). Codex 0.166 refuses to resume a thread whose provider isn't the one configured ("This chat uses openai, but your current provider is magpie", openai/codex#58865; 毅 on Discord), and the rollout's `session_meta` wins over the state DB row. So when magpie becomes the provider, bringOver relabels plain rollouts in place and also moves threads Codex packed to `.jsonl.zst` that were updated in the last 30 days, up to 128 MB a sync, newest first, each with a copy kept in the trash (`sessions.MovePackedCodexThreads`, `TestCodexThreadsFollowMagpieIn`, `TestMovePackedCodexThreads`); bringBack moves them back. A thread started on `cc-switch-official`, the id CC Switch 3.17 to 3.20 gave the official account, is moved to `openai` (or `magpie`, whichever Codex is on) while magpie wires Codex, as CC Switch 4 does itself (#7948 there), unless the user's own top-level `model_provider` or a profile names that id (`bringOfficial`, AcMilan on Discord, `TestCodexMovesCCSwitchOfficialThreads`). Threads on any other provider, and packed ones older than 30 days, stay put: the Sessions page's Move or Resume takes them over.
- A Codex thread keeps the provider it was started on. While a magpie model is on, CC Switch's provider tables go through magpie too (`takeTables`), and get their own base URL back when Codex steps off magpie (`giveTables`, stash `codex.tables`). CC Switch's OpenAI mirror (a table of another id, `name = "OpenAI"`, `requires_openai_auth`, no `base_url`) isn't reached by `openai_base_url`, which takes only the built-in provider to magpie: a thread started on it and reopened went straight to ChatGPT, which refused the magpie model picked in it, and magpie never saw the request (#1796). While Codex goes to magpie by the base URL, `takeMirrors` gives each such mirror magpie's ChatGPT backend as its `base_url` (stash `codex.mirrors`), and `giveMirrors` takes it off again; a mirror a profile names, or one whose `base_url` was changed since, stays as it is. Moving the threads onto another provider is the Sessions page's Move (#887). Codex 0.166 refuses to resume a thread whose provider isn't the one configured ("This chat uses openai, but your current provider is magpie", openai/codex#58865; 毅 on Discord), and the rollout's `session_meta` wins over the state DB row. So when magpie becomes the provider, bringOver relabels plain rollouts in place and also moves threads Codex packed to `.jsonl.zst` that were updated in the last 30 days, up to 128 MB a sync, newest first, each with a copy kept in the trash (`sessions.MovePackedCodexThreads`, `TestCodexThreadsFollowMagpieIn`, `TestMovePackedCodexThreads`); bringBack moves them back. That is done for the provider Codex was on before magpie (stash `codex.provider`, `openai` when none), a provider of the user's own too: a relay's table or CC Switch's `custom`, whose threads the Codex app listed and refused to open on magpie ("This chat uses custom, but your current provider is magpie", hxy920830 on X). An id of magpie's length (`custom`) is relabelled in place; any other (`myrelay`) is rewritten with a copy kept, the threads of the last 30 days, 128 MB a sync, newest first (`sessions.MoveRecentCodexThreads`); OpenAI's threads then stay on OpenAI, and none moves of a provider a profile names. The Disconnect puts the user's `model_provider` back and bringBack returns the threads to it; so does CC Switch switching back to that provider (`TestCodexThreadsFollowMagpieIn`, `TestMoveRecentCodexThreads`). A thread started on `cc-switch-official`, the id CC Switch 3.17 to 3.20 gave the official account, is moved to `openai` (or `magpie`, whichever Codex is on) while magpie wires Codex, as CC Switch 4 does itself (#7948 there), unless the user's own top-level `model_provider` or a profile names that id (`bringOfficial`, AcMilan on Discord, `TestCodexMovesCCSwitchOfficialThreads`). Threads on any other provider, and ones older than 30 days that can't be relabelled in place, stay put: the Sessions page's Move or Resume takes them over.
- An agent's config is written in the form the installed version reads, taken from what that version declares, not the latest one. VSCodium has no Copilot Chat of its own, and the Marketplace's last one (0.48.1) has no Custom Endpoint provider, only OpenAI Compatible (`customoai`, #1014). magpie reads the provider list in the package.json of the `github.copilot-chat` installed under `~/.vscode-oss/extensions` (`vscodeChatOf`). It writes its group for `customendpoint` when that is declared, for `customoai` when only that is, with each model's window as `maxInputTokens` + `maxOutputTokens` and the token as `x-api-key` (that version drops an Authorization in `requestHeaders`). A missing or unreadable extension keeps `customendpoint`. Sync rewrites a group written for the other provider, and Check reports it, as it does a Copilot Chat declaring neither. That Copilot Chat registers its providers only while signed in to GitHub with a personal Copilot plan, which the Notice says.
- Tuned settings are written only on the user's click, never by Sync or Connect. A window that is Long conversations (`TuneLong`) is stashed once as Long conversations was (`tune.long.compact`, one stash for both agents, as the value is one), and Undo puts it back, Full window included, unless the user changed it since. Codex's card is always Long conversations, unless config.toml has a `model_auto_compact_token_limit` of the user's, which Codex stops at first: that one is `locked`. A limit an older magpie's tune wrote there (`tune.codex.compact`) is moved by `tuneMigrateCodex`, from Codex's Sync and from the card: Long conversations at magpie's default, or under Full window, takes it as the user's own choice; one the user typed takes it only when it is lower, where Codex compacted; the file gets back what it had; and a limit the user changed after the click is theirs and stays. Claude Code's `CLAUDE_CODE_AUTO_COMPACT_WINDOW` is Long conversations when magpie wrote it from that value (`claude.compact_long` beside `claude.compact_window`, set by `writeCompact`), and its top-level `autoCompactWindow` when magpie wrote it (`claude.compact_default`) and it equals Long conversations; a window from a provider's Compact at, or the user's own, stays `locked`. A Claude model's own `modelSettings` window, under no such variable, is still per model, since Long conversations doesn't reach Claude models. The value there before is stashed once (`tune.<agent>.<knob>[.<model>]` in `stash.json`), so Undo puts it back, or takes the key out (and a `modelSettings` entry left empty). A value the user changed after the click is theirs: Undo then only forgets the stash. A variable that comes before the setting (`CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `FORCE_PROMPT_CACHING_5M`, `CLAUDE_CODE_PROMPT_CACHE_TTL`, `CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL`, in settings.json's `env` or magpie's own) is shown as `locked` and Apply refuses, since the setting would change nothing. Claude Code compacts at the smaller of the window set and the model's own (its `/autocompact` says "capped to 200k by model"), so advice starts from that, and a model that isn't Claude's has no window here (magpie's own compact wiring serves it). Codex's window is the one magpie's catalog lists for each model it ran (typed, or the vendor's), and with none in config.toml it runs now at what magpie tells Codex (`provider.CompactFor`, else Long conversations in the agent's opened row, as `codexcat` writes it); a model of magpie's whose window isn't known caps nothing short of 1M (or the user's own larger value), never the largest prompt seen (zhemu on Discord: a 1M model at 750K was offered up to 410K), and only Codex's own models, outside the catalog, keep 272K or the largest prompt (`codexWindow`, `TestTuneWindowsAreTheUsers`). Advice changes a value only when the replay saves 3% or more, and of the windows within 1% of the cheapest takes the largest; with the compactions timed, it never advises a window that compacts more often than the one now, so never a longer wait: of the windows that compact no more often it takes the cheapest, and of those within 3% of that (`sameCost`, the same bar as changing at all) the one that compacts least, the larger of two that compact as often. Tokens and seconds share no unit the files measure, so the advice doesn't trade one for the other at a guessed rate; a cheaper window that waits longer is said with its wait in the row and the picker, for the user to choose. The wait per compaction is taken as the same at every window: the files time compactions only near the window the user ran with, too narrow to fit how it grows with the prompt. Tokens are weighed as billed: cache reads 0.1, 5-minute writes 1.25, hour writes 2, output 5 for Claude; reads 0.1, writes 1, output 8 otherwise.
- A plugin's agent writes each key in place (JSON, YAML or env), the user's comments and other keys kept. An object or array `connect` returns is taken as its JSON text (`agentplug.keys`), so it is written in the order the plugin gave it, not sorted as a Go map would be: Kilo lists its effort variants in key order (#1890, `TestPluggedKeepsPluginOrder`). What each key held before the first write is stashed under `plugin:<id>:<path>`, typed, and its own model or Disconnect puts every key back and takes out the ones that weren't there; the file is never written whole. A `connect` that throws or takes over a second writes nothing and says why. Its gateway key is `magpie-<id>` (`agentKeyAt`), and usage names its requests by that key or by its `ua` words (`usage.PluginAgents`). Its `agent.library` (instructions, `mcp` with `mcpFormat`, skills) gives it the Library's three as well, written by `internal/library` as any agent's are ([library](library.md)); a `mcpFormat` outside `agentplug.MCPFormats`, or an `mcp` without one, keeps the plugin from loading. Turning the plugin off or removing it (`provider.SetPluginOff`, `provider.RemovePlugin`, from the CLI or the Plugins page) first disconnects its agent as `magpie <agent> default` does (`provider.PluginAgentGoing`, set to `agent.UnwirePlugin` in [`plugged_gone.go`](../../internal/agent/plugged_gone.go)), since without the plugin magpie no longer knows the agent (#3810); a plugin already off is read from its module as it is, and one whose module is gone puts back each file whose stash names its spec. A failure keeps the plugin as it was. On again, the agent stays as the user had it, and connecting it puts back the model it was on (Disconnect's `.reconnect`). The stash records the plugin's spec and the file's format, so `magpie <id> default` for the agent of a plugin deleted on disk puts the file back from the stash alone (`agent.RestoreGone`; an older stash's format is its file's name, `agentplug.FormatOf`); a file that no longer holds the gateway's key is the user's and left alone, and one that can't be read is put back over by nothing; with the plugin only switched off, it says the agent is off magpie already, not "unknown agent" (`TestPluginOffPutsItsAgentBack`, `TestRestoreGoneAgent`, `TestGoneAgentDefault`).
+58 -27
View File
@@ -735,6 +735,19 @@ func codexIn(at place) *Agent {
dropList()
return nil
}
// profileNamed are the provider tables a profile of config.toml names:
// the user's to pick, each left as it is
profileNamed := func(names []string) map[string]bool {
named := map[string]bool{}
for _, n := range names {
if strings.HasPrefix(n, "profiles.") {
if t, _ := edit.GetTOMLTable(path, n); t["model_provider"] != "" {
named[t["model_provider"]] = true
}
}
}
return named
}
// bringBack moves the threads started while magpie was Codex's
// provider (model_provider "magpie") onto the provider Codex is on now,
// once it is off magpie: Codex lists only the threads of its current
@@ -785,11 +798,25 @@ func codexIn(at place) *Agent {
// place (RelabelCodexThreads): those Codex has packed, a week after
// their last turn, stay on OpenAI, as a rewrite of every one would
// copy the whole history. bringBack moves them back as Codex leaves
// magpie. Only OpenAI's, and only when Codex was on OpenAI before
// magpie: threads of a provider of the user's (CC Switch's) stay, and
// so do OpenAI's when Codex was on another provider, whose threads
// bringBack would hand them to. None while a profile is chosen, whose
// provider is the one Codex lists, and none from a distro's Codex.
// magpie. Only the threads of the provider Codex was on before magpie
// (stash codex.provider, OpenAI when none was set): those of any other
// provider stay, and so do OpenAI's when Codex was on another one,
// whose threads bringBack would hand them to. None while a profile is
// chosen, whose provider is the one Codex lists, none of a provider a
// profile names, which the user picks to go on with them there, and
// none from a distro's Codex.
//
// The provider Codex was on before can be one of the user's own, a
// relay's table or CC Switch's "custom". Its threads stayed on it at
// first (#887 asked for a Move by hand: Codex 0.159 only left them out
// of its list), but Codex 0.166 lists them in the app and refuses to
// open one on magpie ("This chat uses custom, but your current
// provider is magpie", hxy920830 on X: "原来的会话可以看到,但是加载不
// 出来模型了"), so they move as OpenAI's do. Disconnected, or with CC
// Switch back on that provider, bringBack gives them back to it. An id
// of magpie's length moves in place; any other is rewritten with a
// copy kept, the last 30 days of it as the packed ones below; older
// ones from Sessions.
//
// Codex 0.166 resumes a thread only on the provider it is on now (the
// app: "This chat uses openai, but your current provider is magpie.
@@ -804,22 +831,39 @@ func codexIn(at place) *Agent {
if at.spell != nil || !asProvider() || sessions.CodexProviderIn(dir) != magpieID {
return
}
if p := stashShared()[at.key("codex.provider")]; p != "" && p != "openai" {
from := stashShared()[at.key("codex.provider")]
if from == "" {
from = "openai"
}
// CC Switch's official route is bringOfficial's
if from == magpieID || from == ccSwitchOfficial {
return
}
moved, err := sessions.RelabelCodexThreads(dir, "openai", magpieID)
if len(moved) > 0 {
log.Printf("codex: %d thread(s) started on OpenAI moved to magpie, where Codex lists them now", len(moved))
if from != "openai" {
names, _ := edit.TOMLTables(path)
if profileNamed(names)[from] {
return
}
}
if err != nil {
log.Println("codex: moving OpenAI's threads to magpie:", err)
if len(from) == len(magpieID) {
moved, err := sessions.RelabelCodexThreads(dir, from, magpieID)
if len(moved) > 0 {
log.Printf("codex: %d thread(s) started on %s moved to magpie, where Codex lists them now", len(moved), from)
}
if err != nil {
log.Printf("codex: moving %s's threads to magpie: %v", from, err)
}
}
packed, err := sessions.MovePackedCodexThreads(dir, "openai", magpieID, time.Now().Add(-packedSince), packedBudget)
move := sessions.MovePackedCodexThreads
if len(from) != len(magpieID) {
move = sessions.MoveRecentCodexThreads
}
packed, err := move(dir, from, magpieID, time.Now().Add(-packedSince), packedBudget)
if len(packed) > 0 {
log.Printf("codex: %d packed thread(s) started on OpenAI moved to magpie, where Codex resumes them now", len(packed))
log.Printf("codex: %d thread(s) started on %s rewritten onto magpie, where Codex resumes them now", len(packed), from)
}
if err != nil {
log.Println("codex: moving OpenAI's packed threads to magpie:", err)
log.Printf("codex: moving %s's threads to magpie: %v", from, err)
}
}
// mirrorsTaken are the mirrors takeMirrors pointed at magpie (#1796)
@@ -843,19 +887,6 @@ func codexIn(at place) *Agent {
u := t["base_url"]
return u == "" || (u == at.codexURL() && (stashShared()[at.key("codex.mirror_failover")] == p || slices.Contains(mirrorsTaken(), p)))
}
// profileNamed are the provider tables a profile of config.toml names:
// the user's to pick, each left as it is
profileNamed := func(names []string) map[string]bool {
named := map[string]bool{}
for _, n := range names {
if strings.HasPrefix(n, "profiles.") {
if t, _ := edit.GetTOMLTable(path, n); t["model_provider"] != "" {
named[t["model_provider"]] = true
}
}
}
return named
}
// bringOfficial moves the threads of CC Switch's "cc-switch-official"
// to the provider Codex is on with magpie (OpenAI beside the sign-in,
// or magpie). CC Switch 3.17 to 3.20 sent the official ChatGPT account
+102 -7
View File
@@ -1,10 +1,12 @@
package agent
import (
"database/sql"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/klauspost/compress/zstd"
@@ -21,9 +23,9 @@ import (
//
// Now the threads Codex started on OpenAI move to magpie while it is
// Codex's provider, in place (the id is one length), the file's time
// kept, and back at the Disconnect, with no copy of each. A provider of
// the user's stays, and OpenAI's stay when Codex was on another provider
// before magpie.
// kept, and back at the Disconnect, with no copy of each. Another
// provider's threads stay, and OpenAI's stay when Codex was on another
// provider before magpie, whose threads move instead (hxy920830 on X).
//
// Threads Codex has packed (.zst) stayed on OpenAI, which Codex 0.166's
// app refuses to resume on magpie ("This chat uses openai, but your
@@ -96,21 +98,114 @@ func TestCodexThreadsFollowMagpieIn(t *testing.T) {
t.Fatalf("copied: %v", l)
}
})
// hxy920830 on X: Codex had been on a relay's table of the user's
// own, and with magpie its provider the Codex app listed those threads
// and refused to open them ("This chat uses custom, but your current
// provider is magpie": "原来的会话可以看到,但是加载不出来模型了").
// The threads of the provider Codex was on before magpie move as
// OpenAI's do, and back to it at the Disconnect; OpenAI's stay, as
// bringBack would give them to that provider.
t.Run("on a provider of the user's before", func(t *testing.T) {
cfg := "model = \"m\"\nmodel_provider = \"custom\"\n\n[model_providers.custom]\nname = \"custom\"\nbase_url = \"https://relay.example/v1\"\nwire_api = \"responses\"\n"
home, _ := codexHome(t, "", cfg)
dir := filepath.Join(home, ".codex")
codexThreadOn(t, dir, plain, "openai")
theirsPath := codexThreadOn(t, dir, theirs, "custom")
cx := codex(home)
if err := cx.Fields[0].Set("fake/m1"); err != nil {
t.Fatal(err)
}
if p, _ := edit.GetTOMLTop(filepath.Join(dir, "config.toml"), "model_provider"); p != "magpie" {
t.Fatalf("provider %q, want magpie", p)
}
cx.Sync()
for id, want := range map[string]string{plain: "openai", theirs: "magpie"} {
if p := codexRowOn(t, dir, id); p != want {
t.Errorf("connected: thread %s on %q, want %q", id, p, want)
}
}
// "custom" is magpie's length: in place, no copy
if l, _ := filepath.Glob(filepath.Join(settings.Dir(), "trash", "codex-provider", "*"+theirs)); len(l) > 0 {
t.Fatalf("copied: %v", l)
}
if err := cx.Unwire(); err != nil {
t.Fatal(err)
}
if p, _ := edit.GetTOMLTop(filepath.Join(dir, "config.toml"), "model_provider"); p != "custom" {
t.Fatalf("provider %q after the Disconnect, want custom back", p)
}
for id, want := range map[string]string{plain: "openai", theirs: "custom"} {
if p := codexRowOn(t, dir, id); p != want {
t.Errorf("disconnected: thread %s on %q, want %q", id, p, want)
}
}
if b, _ := os.ReadFile(theirsPath); !strings.Contains(string(b), `"model_provider":"custom"`) {
t.Fatalf("rollout not back on custom:\n%s", b)
}
})
// a relay's id of another length is rewritten, a copy kept, the last
// 30 days of it; an older thread stays for Sessions to move
t.Run("on a relay's table of another length", func(t *testing.T) {
const old = "019a0000-0000-7000-8000-0000000000c4"
cfg := "model = \"m\"\nmodel_provider = \"myrelay\"\n\n[model_providers.myrelay]\nname = \"My relay\"\nbase_url = \"https://relay.example/v1\"\nwire_api = \"responses\"\n"
home, _ := codexHome(t, "", cfg)
dir := filepath.Join(home, ".codex")
codexThreadOn(t, dir, plain, "openai")
theirsPath := codexThreadOn(t, dir, theirs, "myrelay")
packedPath := codexThreadOn(t, dir, packed, "myrelay")
packThread(t, packedPath)
codexThreadOn(t, dir, old, "myrelay")
db, err := sql.Open("sqlite", filepath.Join(dir, "state_5.sqlite"))
if err != nil {
t.Fatal(err)
}
if _, err := db.Exec(`UPDATE threads SET updated_at = ? WHERE id = ?`, time.Now().Add(-40*24*time.Hour).Unix(), old); err != nil {
t.Fatal(err)
}
db.Close()
cx := codex(home)
if err := cx.Fields[0].Set("fake/m1"); err != nil {
t.Fatal(err)
}
for id, want := range map[string]string{plain: "openai", theirs: "magpie", packed: "magpie", old: "myrelay"} {
if p := codexRowOn(t, dir, id); p != want {
t.Errorf("connected: thread %s on %q, want %q", id, p, want)
}
}
if b, _ := os.ReadFile(theirsPath); !strings.Contains(string(b), `"model_provider":"magpie"`) {
t.Fatalf("rollout still on myrelay:\n%s", b)
}
if p := zstMetaProvider(t, packedPath+".zst"); p != "magpie" {
t.Fatalf("packed rollout on %q, want magpie", p)
}
if l, _ := filepath.Glob(filepath.Join(settings.Dir(), "trash", "codex-provider", "*"+theirs, "move.json")); len(l) != 1 {
t.Fatalf("rewritten with no copy kept: %v", l)
}
if err := cx.Unwire(); err != nil {
t.Fatal(err)
}
for id, want := range map[string]string{plain: "openai", theirs: "myrelay", packed: "myrelay", old: "myrelay"} {
if p := codexRowOn(t, dir, id); p != want {
t.Errorf("disconnected: thread %s on %q, want %q", id, p, want)
}
}
if b, _ := os.ReadFile(theirsPath); !strings.Contains(string(b), `"model_provider":"myrelay"`) {
t.Fatalf("rollout not back on myrelay:\n%s", b)
}
})
// a provider a profile names is the user's to go on with there
t.Run("on a provider a profile names", func(t *testing.T) {
cfg := "model = \"m\"\nmodel_provider = \"custom\"\n\n[model_providers.custom]\nname = \"custom\"\nbase_url = \"https://relay.example/v1\"\nwire_api = \"responses\"\n\n[profiles.relay]\nmodel_provider = \"custom\"\n"
home, _ := codexHome(t, "", cfg)
dir := filepath.Join(home, ".codex")
codexThreadOn(t, dir, theirs, "custom")
cx := codex(home)
if err := cx.Fields[0].Set("fake/m1"); err != nil {
t.Fatal(err)
}
cx.Sync()
for id, want := range map[string]string{plain: "openai", theirs: "custom"} {
if p := codexRowOn(t, dir, id); p != want {
t.Errorf("thread %s on %q, want %q", id, p, want)
}
if p := codexRowOn(t, dir, theirs); p != "custom" {
t.Fatalf("thread on %q, want custom, where `codex -p relay` lists it", p)
}
})
}
@@ -130,3 +130,75 @@ func TestMovePackedCodexThreadsNoUpdatedAt(t *testing.T) {
t.Fatalf("row on %q", got)
}
}
// hxy920830 on X: Codex had been on a provider of the user's own, a
// relay's table, and once magpie was its provider the app listed those
// threads and refused to open one ("This chat uses myrelay, but your
// current provider is magpie"). An id of another length than magpie's
// can't be written in place, so MoveRecentCodexThreads moves the recent
// ones, plain or packed, each rewritten with a copy kept; an older one
// and another provider's stay.
func TestMoveRecentCodexThreads(t *testing.T) {
_, home := manageSetup(t)
const (
plain = "019a0000-0000-7000-8000-0000000000f1"
packed = "019a0000-0000-7000-8000-0000000000f2"
old = "019a0000-0000-7000-8000-0000000000f3"
theirs = "019a0000-0000-7000-8000-0000000000f4"
)
week := time.Now().Add(-8 * 24 * time.Hour).Truncate(time.Second)
paths := map[string]string{}
on := map[string]string{plain: "myrelay", packed: "myrelay", old: "myrelay", theirs: "custom"}
for id, p := range on {
paths[id] = cxRollout(t, home, "sessions", id, p, week)
}
pack(t, paths[packed], false)
db := filepath.Join(home, "state_5.sqlite")
d, err := sql.Open("sqlite", db)
if err != nil {
t.Fatal(err)
}
if _, err := d.Exec(`CREATE TABLE threads (id TEXT PRIMARY KEY, rollout_path TEXT NOT NULL, model_provider TEXT NOT NULL, title TEXT NOT NULL, archived INTEGER NOT NULL DEFAULT 0, updated_at INTEGER NOT NULL)`); err != nil {
t.Fatal(err)
}
now := time.Now()
for id, ago := range map[string]time.Duration{plain: 8, packed: 9, old: 40, theirs: 8} {
if _, err := d.Exec(`INSERT INTO threads VALUES (?, ?, ?, 't', 0, ?)`, id, paths[id], on[id], now.Add(-ago*24*time.Hour).Unix()); err != nil {
t.Fatal(err)
}
}
d.Close()
since := now.Add(-30 * 24 * time.Hour)
moved, err := MoveRecentCodexThreads(home, "myrelay", "magpie", since, 64<<20)
if err != nil {
t.Fatal(err)
}
if len(moved) != 2 || moved[0].ID != plain || moved[1].ID != packed {
t.Fatalf("moved %+v, want the plain then the packed one", moved)
}
for _, mv := range moved {
if _, err := os.Stat(filepath.Join(mv.Backup, "move.json")); err != nil {
t.Fatalf("%s: no copy kept: %v", mv.ID, err)
}
}
want := map[string]string{plain: "magpie", packed: "magpie", old: "myrelay", theirs: "custom"}
for id, prov := range want {
if got, _, _ := threadProvider(t, db, id); got != prov {
t.Errorf("row %s on %q, want %q", id, got, prov)
}
f := paths[id]
if id == packed {
f += zstSuffix
}
if got := codexMetaProvider(f); got != prov {
t.Errorf("file %s on %q, want %q", filepath.Base(f), got, prov)
}
}
if b, _ := os.ReadFile(paths[plain]); !bytes.Contains(b, []byte("remember: the build uses make")) {
t.Fatalf("plain rollout after the move:\n%s", b)
}
// the packed-only move of the same leaves a plain thread
if moved, err = MovePackedCodexThreads(home, "custom", "magpie", since, 64<<20); err != nil || len(moved) != 0 {
t.Fatalf("packed-only: %+v %v", moved, err)
}
}
+22 -5
View File
@@ -542,6 +542,21 @@ func moveCodexThreadIDs(home, from, to string, ids []string, budget int64) ([]Co
// provider is magpie"), so a packed thread left on OpenAI couldn't be
// reopened while magpie was Codex's provider.
func MovePackedCodexThreads(home, from, to string, since time.Time, budget int64) ([]CodexMove, error) {
return moveRecentCodexThreads(home, from, to, since, budget, true)
}
// MoveRecentCodexThreads is MovePackedCodexThreads for every thread on
// from whose last turn is since since, plain or packed: for a provider
// whose id isn't magpie's length, which RelabelCodexThreads can't write
// in place, so each one moved is rewritten with a copy kept. A thread of
// the user's own provider (a relay's, "myrelay") was listed by the Codex
// app once magpie was its provider, and refused: "This chat uses myrelay,
// but your current provider is magpie" (hxy920830 on X).
func MoveRecentCodexThreads(home, from, to string, since time.Time, budget int64) ([]CodexMove, error) {
return moveRecentCodexThreads(home, from, to, since, budget, false)
}
func moveRecentCodexThreads(home, from, to string, since time.Time, budget int64, packedOnly bool) ([]CodexMove, error) {
if !codexProviderRe.MatchString(from) || !codexProviderRe.MatchString(to) || from == to || budget <= 0 {
return nil, fmt.Errorf("can't move Codex's threads from %q to %q", from, to)
}
@@ -566,12 +581,14 @@ func MovePackedCodexThreads(home, from, to string, since time.Time, budget int64
if !filepath.IsAbs(path) || !strings.Contains(filepath.Base(path), id) || !sameDir(codexHomeOf(path), home) {
continue
}
// packed: the plain file gone, the .zst there and on from
// packed: the plain file gone, the .zst there and on
// from; or, packedOnly not, the plain file on from
plain, _ := strings.CutSuffix(path, zstSuffix)
if _, err := os.Lstat(plain); err == nil {
continue
}
if fi, err := os.Lstat(plain + zstSuffix); err != nil || !fi.Mode().IsRegular() || codexMetaProvider(plain+zstSuffix) != from {
if fi, err := os.Lstat(plain); err == nil {
if packedOnly || !fi.Mode().IsRegular() || codexMetaProvider(plain) != from {
continue
}
} else if fi, err := os.Lstat(plain + zstSuffix); err != nil || !fi.Mode().IsRegular() || codexMetaProvider(plain+zstSuffix) != from {
continue
}
ids = append(ids, id)