From d2c29abe73b16eaeed5fb7b56f5488093b39c663 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 6 Nov 2026 11:26:37 +0800 Subject: [PATCH] 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 --- docs/subsystems/agent-wiring.md | 2 +- internal/agent/codex.go | 81 +++++++++-- internal/agent/codex_takeover_thread_test.go | 139 +++++++++++++++++-- internal/agent/main_test.go | 5 + internal/sessions/codex_provider.go | 74 +++++++++- 5 files changed, 268 insertions(+), 33 deletions(-) diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 4bf3fdbaf..e94bf4574 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -154,7 +154,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/`), `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 for a legacy thread 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 legacy 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 paginated thread (`history_mode = 'paginated'` in the row, every thread Codex 0.166 starts) is listed and resumed on the provider its row names, never its files' (codex-rs thread-store `read_thread`: "Paginated history may contain only a suffix, so its display metadata lives in SQLite"), so the 30 days and the budget left an API-key user's older OpenAI threads refused in the Codex app (Parry_Moody and Cyrus on Discord). Every one now moves by its row alone, of any age, packed or not, an id of any length, its files neither written nor copied (`sessions.RetagPagedCodexThreads`, after the in-place relabel), in bringOver, bringBack, bringOfficial, bringBeside and giveBeside (`RetagPagedCodexThreadIDs`); one a Codex has open (its writer lock, which would write its provider back) or wrote to in the last minute waits for the next sync. The Sessions page lists a paginated thread on its row's provider (`codexPagedProviders`, read again when the database or its WAL changes). Tried with the real codex 0.166.0 (`codex exec resume`): refused on magpie with the row on openai, resumed after the retag, and back on OpenAI after the reverse (`TestCodexPagedThreadsFollowByRow`, `TestRetagPagedCodexThreads`). Codex rebuilds a row from the rollout when a search listing or a missing row reconciles it, which would put a retagged thread back on its file's provider until the next sync. A thread bringBack leaves on magpie because it was written to in the last minute (the one a turn ran in during the takeover, as the account came back) gets one more Sync once it is quiet (`sessions.CodexThreadsBusyOn`, `codexThreadsLater`, ActiveWindow+5s, one wait at a time): no other Sync may come for hours, and until it moves the Codex app can't resume it on OpenAI, so Retry fails each time and its model reads unavailable (nb5p on Discord, `TestCodexTakeoverThreadComesBackOnceQuiet`). 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 stay on OpenAI there (on the user's provider itself they follow it, `lendOwn` below), 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`). Before #4347 (v0.1.2652) the beside wiring took a provider of the user's (CC Switch's `custom`) down and kept it in stash `codex.provider`, leaving Codex on OpenAI by the base URL with every thread of that provider refused ("This chat uses custom, but your current provider is openai", yikelizi9438 on Discord). While Codex stays so (routed by `openai_base_url`, no top-level `model_provider`), `bringBeside` moves that provider's threads to `openai` the same way (in place at OpenAI's length, the last 30 days rewritten otherwise) and records them in stash `codex.brought`; the Disconnect puts the provider back and `giveBeside` returns exactly those threads to it (`sessions.MoveCodexThreadIDs`), and if magpie becomes Codex's provider instead they go on to `magpie` (`followBeside`), where bringBack returns them at the Disconnect (`TestCodexBesideBringsTakenProvidersThreads`). The other way round, Codex on a provider of the user's at the top (CC Switch's `custom`, kept since #4347; not magpie, `openai`, `cc-switch-official` or CC Switch's OpenAI mirror) could not continue a thread started on OpenAI before ("This chat uses openai, but your current provider is custom. Switch to openai to continue", harris on Discord, after CC Switch). Each Sync moves OpenAI's threads to that provider the same way (`lendOwn`: in place at OpenAI's length, by the row for a paginated one, the last 30 days rewritten otherwise) and records them in stash `codex.lent`; once Codex is on OpenAI again `giveLent` returns exactly those (`sessions.MoveCodexThreadIDs`, `RetagPagedCodexThreadIDs`), the record kept while Codex is on that provider or on magpie and dropped on any other. None moves while a profile names `openai`, after the user disconnected Codex, or from a distro's Codex (`TestCodexOwnProviderTakesOpenAIThreads`, `TestCodexOwnProviderLeavesOpenAIThreads`). 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. +- 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 for a legacy thread 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 legacy 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 paginated thread (`history_mode = 'paginated'` in the row, every thread Codex 0.166 starts) is listed and resumed on the provider its row names, never its files' (codex-rs thread-store `read_thread`: "Paginated history may contain only a suffix, so its display metadata lives in SQLite"), so the 30 days and the budget left an API-key user's older OpenAI threads refused in the Codex app (Parry_Moody and Cyrus on Discord). Every one now moves by its row alone, of any age, packed or not, an id of any length, its files neither written nor copied (`sessions.RetagPagedCodexThreads`, after the in-place relabel), in bringOver, bringBack, bringOfficial, bringBeside and giveBeside (`RetagPagedCodexThreadIDs`); one a Codex has open (its writer lock, which would write its provider back) or wrote to in the last minute waits for the next sync. The Sessions page lists a paginated thread on its row's provider (`codexPagedProviders`, read again when the database or its WAL changes). Tried with the real codex 0.166.0 (`codex exec resume`): refused on magpie with the row on openai, resumed after the retag, and back on OpenAI after the reverse (`TestCodexPagedThreadsFollowByRow`, `TestRetagPagedCodexThreads`). Codex rebuilds a row from the rollout when a search listing or a missing row reconciles it, which would put a retagged thread back on its file's provider until the next sync. A thread a move leaves where it was because it was written to in the last minute or a Codex holds it open gets one more Sync once it is quiet and let go (`sessions.CodexThreadsBusyOn`: a recent rollout, or its writer lock held, tried under Codex's coordination lock; `codexThreadsLater` looks every 15s for up to 12h, one wait per home and provider): no other Sync may come for hours. bringBack's (the thread a turn ran in during the takeover, as the account came back) otherwise stayed on magpie, and the Codex app couldn't resume it on OpenAI, so Retry failed each time and its model read unavailable (nb5p on Discord, `TestCodexTakeoverThreadComesBackOnceQuiet`). bringOver's and lendOwn's are the chats the Codex app had loaded as magpie became Codex's provider: the app holds every loaded thread's lock however long ago it was written (tried with codex 0.165's app-server), checks a loaded thread's provider against config.toml at each turn, and refuses it ("This chat uses OpenAI, but your current provider is magpie", crypto0xfish on Discord) until it lets the thread go; resumed after that, it was refused again on its row's `openai` until something else synced (`TestCodexOpenThreadFollowsMagpieOnceLetGo`). The chat open at the switch can't be helped from outside: it goes on once the app reloads it (the app quit and reopened; whether leaving the chat for another lets it go was not tried). 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 stay on OpenAI there (on the user's provider itself they follow it, `lendOwn` below), 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`). Before #4347 (v0.1.2652) the beside wiring took a provider of the user's (CC Switch's `custom`) down and kept it in stash `codex.provider`, leaving Codex on OpenAI by the base URL with every thread of that provider refused ("This chat uses custom, but your current provider is openai", yikelizi9438 on Discord). While Codex stays so (routed by `openai_base_url`, no top-level `model_provider`), `bringBeside` moves that provider's threads to `openai` the same way (in place at OpenAI's length, the last 30 days rewritten otherwise) and records them in stash `codex.brought`; the Disconnect puts the provider back and `giveBeside` returns exactly those threads to it (`sessions.MoveCodexThreadIDs`), and if magpie becomes Codex's provider instead they go on to `magpie` (`followBeside`), where bringBack returns them at the Disconnect (`TestCodexBesideBringsTakenProvidersThreads`). The other way round, Codex on a provider of the user's at the top (CC Switch's `custom`, kept since #4347; not magpie, `openai`, `cc-switch-official` or CC Switch's OpenAI mirror) could not continue a thread started on OpenAI before ("This chat uses openai, but your current provider is custom. Switch to openai to continue", harris on Discord, after CC Switch). Each Sync moves OpenAI's threads to that provider the same way (`lendOwn`: in place at OpenAI's length, by the row for a paginated one, the last 30 days rewritten otherwise) and records them in stash `codex.lent`; once Codex is on OpenAI again `giveLent` returns exactly those (`sessions.MoveCodexThreadIDs`, `RetagPagedCodexThreadIDs`), the record kept while Codex is on that provider or on magpie and dropped on any other. None moves while a profile names `openai`, after the user disconnected Codex, or from a distro's Codex (`TestCodexOwnProviderTakesOpenAIThreads`, `TestCodexOwnProviderLeavesOpenAIThreads`). 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..[.]` 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::`, 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-` (`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 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 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`). diff --git a/internal/agent/codex.go b/internal/agent/codex.go index bdaa90c2e..f0b3afd7e 100644 --- a/internal/agent/codex.go +++ b/internal/agent/codex.go @@ -804,7 +804,7 @@ func codexIn(at place) *Agent { // each time and its model reads unavailable (nb5p on Discord). // Another Sync comes once the thread is quiet. if sessions.CodexThreadsBusyOn(dir, magpieID) { - codexThreadsLater() + codexThreadsLater(dir, magpieID) } } // bringOver is bringBack the other way: while magpie is Codex's @@ -903,6 +903,12 @@ func codexIn(at place) *Agent { if err != nil { log.Printf("codex: moving %s's threads to magpie: %v", from, err) } + // one the Codex app has open (the chat on screen as magpie became + // the provider) or wrote to this minute stayed on from: it moves + // once it is let go (crypto0xfish on Discord) + if sessions.CodexThreadsBusyOn(dir, from) { + codexThreadsLater(dir, from) + } } // mirrorsTaken are the mirrors takeMirrors pointed at magpie (#1796) mirrorsTaken := func() []string { @@ -1423,6 +1429,9 @@ func codexIn(at place) *Agent { if err != nil { log.Printf("codex: moving OpenAI's threads to %s: %v", to, err) } + if sessions.CodexThreadsBusyOn(dir, "openai") { + codexThreadsLater(dir, "openai") + } if len(ids) == 0 { return } @@ -2797,24 +2806,66 @@ var codexThreadsAgain func() func init() { codexThreadsAgain = SyncCatalogSoon } -// codexThreadsWait is how long codexThreadsLater waits: past the window -// in which a thread counts as being written to. -var codexThreadsWait = sessions.ActiveWindow + 5*time.Second +// codexThreadsWait is how often codexThreadsLater looks again: within +// it of a thread going quiet, or of the Codex app letting it go, the +// Sync is asked for. +var codexThreadsWait = 15 * time.Second -var codexThreadsPending satomic.Bool +// codexThreadsFor is how long codexThreadsLater keeps looking, in +// nanoseconds: a thread the Codex app keeps open all day waits for the +// next Sync after it. Read at each look, so a test ends a wait by +// setting it to 0. +var codexThreadsFor satomic.Int64 -// codexThreadsLater runs codexThreadsAgain once codexThreadsWait has -// passed, for the threads bringBack left on magpie as they were being -// written to. One wait at a time: another call while one is pending -// adds none. -func codexThreadsLater() { - if !codexThreadsPending.CompareAndSwap(false, true) { +func init() { codexThreadsFor.Store(int64(12 * time.Hour)) } + +var ( + codexThreadsMu sync.Mutex + codexThreadsPending = map[string]bool{} +) + +// codexThreadsLater runs codexThreadsAgain once no thread of the Codex +// home dir on the provider p is being written to or held open +// (sessions.CodexThreadsBusyOn), for the threads a move off p left there: +// bringBack's on magpie as they were being written to (nb5p on Discord), +// and bringOver's and lendOwn's on OpenAI that the Codex app had open as +// magpie became Codex's provider. Those the app refuses to go on with +// ("This chat uses OpenAI, but your current provider is magpie", +// crypto0xfish on Discord) while it keeps them loaded, and once it lets +// them go (the chat closed, the app quit) it resumes them on the provider +// their row names, so they have to move by then; nothing else may Sync +// for hours. It looks every codexThreadsWait, which is a database read +// and a try of the locks Codex holds, for up to codexThreadsFor. One wait +// at a time for each home and provider: another call while one is +// pending adds none. +func codexThreadsLater(dir, p string) { + key := dir + "\x00" + p + codexThreadsMu.Lock() + if codexThreadsPending[key] { + codexThreadsMu.Unlock() return } - time.AfterFunc(codexThreadsWait, func() { - codexThreadsPending.Store(false) - codexThreadsAgain() - }) + codexThreadsPending[key] = true + codexThreadsMu.Unlock() + done := func() { + codexThreadsMu.Lock() + delete(codexThreadsPending, key) + codexThreadsMu.Unlock() + } + wait := codexThreadsWait + go func() { + for start := time.Now(); time.Since(start) < time.Duration(codexThreadsFor.Load()); { + time.Sleep(wait) + if !sessions.CodexThreadsBusyOn(dir, p) { + // let go first: the Sync it asks for may find another + // thread busy and ask again + done() + codexThreadsAgain() + return + } + } + done() + }() } // codexUsedUp reports whether the ChatGPT account Codex is signed in to diff --git a/internal/agent/codex_takeover_thread_test.go b/internal/agent/codex_takeover_thread_test.go index 12891a614..172e7b6da 100644 --- a/internal/agent/codex_takeover_thread_test.go +++ b/internal/agent/codex_takeover_thread_test.go @@ -1,13 +1,45 @@ package agent import ( + "database/sql" "os" "path/filepath" "strings" "testing" "time" + + "github.com/yetone/magpie/internal/filelock" ) +// watchCodexThreads stands in for codexThreadsLater's Sync, looking every +// 10ms, and ends every wait it started when the test ends. +func watchCodexThreads(t *testing.T) <-chan struct{} { + t.Helper() + asked := make(chan struct{}, 4) + oldAgain, oldWait := codexThreadsAgain, codexThreadsWait + codexThreadsAgain = func() { asked <- struct{}{} } + codexThreadsWait = 10 * time.Millisecond + codexThreadsFor.Store(int64(time.Minute)) + t.Cleanup(func() { + codexThreadsFor.Store(0) + for end := time.Now().Add(5 * time.Second); ; { + codexThreadsMu.Lock() + n := len(codexThreadsPending) + codexThreadsMu.Unlock() + if n == 0 { + break + } + if time.Now().After(end) { + t.Error("a wait for Codex's threads outlived its test") + break + } + time.Sleep(5 * time.Millisecond) + } + codexThreadsAgain, codexThreadsWait = oldAgain, oldWait + }) + return asked +} + // nb5p on Discord: with the ChatGPT account Codex is signed in to used // up, magpie became Codex's provider (the takeover), and the turn the // user sent then started a thread on magpie. When the account came back @@ -24,14 +56,8 @@ func TestCodexTakeoverThreadComesBackOnceQuiet(t *testing.T) { if err := cx.Fields[0].Set("fake/m1"); err != nil { t.Fatal(err) } - asked := make(chan struct{}, 4) - oldAgain, oldWait := codexThreadsAgain, codexThreadsWait - codexThreadsAgain = func() { asked <- struct{}{} } - codexThreadsWait = 10 * time.Millisecond - t.Cleanup(func() { - codexThreadsAgain, codexThreadsWait = oldAgain, oldWait - codexUsedUp = func() bool { return false } - }) + asked := watchCodexThreads(t) + t.Cleanup(func() { codexUsedUp = func() bool { return false } }) codexUsedUp = func() bool { return true } if err := cx.Sync(); err != nil { @@ -56,13 +82,18 @@ func TestCodexTakeoverThreadComesBackOnceQuiet(t *testing.T) { t.Fatalf("a thread being written to was moved: %q", p) } select { + case <-asked: + t.Fatal("a Sync asked for while the thread is still written to") + case <-time.After(100 * time.Millisecond): + } + // quiet now + old := now.Add(-2 * time.Minute) + os.Chtimes(path, old, old) + select { case <-asked: case <-time.After(5 * time.Second): t.Fatal("the thread left on magpie as it was written to: no later Sync asked for") } - // that Sync, the thread quiet by then - old := now.Add(-2 * time.Minute) - os.Chtimes(path, old, old) if err := cx.Sync(); err != nil { t.Fatal(err) } @@ -75,3 +106,89 @@ func TestCodexTakeoverThreadComesBackOnceQuiet(t *testing.T) { case <-time.After(50 * time.Millisecond): } } + +// crypto0xfish on Discord, the Codex app: "Model provider mismatch. This +// chat uses OpenAI, but your current provider is magpie. Switch to OpenAI +// to continue." The app holds the writer lock of every thread it has +// loaded, the chat on screen among them, and a thread's row moves to +// magpie (bringOver) only when no Codex holds it, so the chat open as +// magpie became Codex's provider stayed on OpenAI. Nothing asked for +// another Sync, so it stayed there after the app let it go, and the app +// refused it on every reopen until something else synced, which can be +// hours. bringOver now asks for that Sync once the thread is let go, and +// it moves the thread to magpie, where the app resumes it. +func TestCodexOpenThreadFollowsMagpieOnceLetGo(t *testing.T) { + const id = "019a0000-0000-7000-8000-0000000000b2" + home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "") + dir := filepath.Join(home, ".codex") + // a paginated thread of OpenAI's, quiet for a day and packed by + // Codex, that the Codex app has open (codex-rs rollout writer_lock.rs) + packThread(t, codexThreadOn(t, dir, id, "openai")) + db, err := sql.Open("sqlite", filepath.Join(dir, "state_5.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if _, err := db.Exec(`ALTER TABLE threads ADD COLUMN history_mode TEXT NOT NULL DEFAULT 'legacy'`); err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`UPDATE threads SET history_mode = 'paginated' WHERE id = ?`, id); err != nil { + t.Fatal(err) + } + locks := filepath.Join(dir, "thread-writer-locks") + os.MkdirAll(locks, 0o755) + lf, err := os.OpenFile(filepath.Join(locks, id+".lock"), os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + t.Fatal(err) + } + if got, err := filelock.TryLock(lf); !got { + t.Fatal("lock:", err) + } + letGo := func() { filelock.Unlock(lf); lf.Close() } + defer func() { + if lf != nil { + letGo() + } + }() + + cx := codex(home) + if err := cx.Fields[0].Set("fake/m1"); err != nil { + t.Fatal(err) + } + asked := watchCodexThreads(t) + t.Cleanup(func() { codexUsedUp = func() bool { return false } }) + codexUsedUp = func() bool { return true } + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if cfg := read(); !strings.Contains(cfg, `model_provider = "magpie"`) { + t.Fatalf("used up, magpie not Codex's provider:\n%s", cfg) + } + if p := codexRowOn(t, dir, id); p != "openai" { + t.Fatalf("a thread a Codex holds open was moved: %q", p) + } + select { + case <-asked: + t.Fatal("a Sync asked for while the app still holds the thread") + case <-time.After(100 * time.Millisecond): + } + // the app lets it go: the chat closed, or the app quit + letGo() + lf = nil + select { + case <-asked: + case <-time.After(5 * time.Second): + t.Fatal("the thread the app had open stayed on OpenAI: no later Sync asked for") + } + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if p := codexRowOn(t, dir, id); p != "magpie" { + t.Fatalf("thread on %q after the later Sync, want magpie, where the app resumes it", p) + } + select { + case <-asked: + t.Fatal("another Sync asked for with nothing left on OpenAI") + case <-time.After(50 * time.Millisecond): + } +} diff --git a/internal/agent/main_test.go b/internal/agent/main_test.go index f3a85851c..fcf95422b 100644 --- a/internal/agent/main_test.go +++ b/internal/agent/main_test.go @@ -28,6 +28,11 @@ func TestMain(m *testing.M) { // whether Codex's ChatGPT account is out of its allowance is asked of // OpenAI; never from here codexUsedUp = func() bool { return false } + // a thread a Codex holds open is looked at again later, on its own + // goroutine, which would outlive its test; the tests about it set + // their own wait + codexThreadsAgain = func() {} + codexThreadsFor.Store(0) // Sandboxed config writes must never write into the real OS keychain. zedCredential = func(string) error { return nil } // Pi's and omp's model registries are read from their installs; never diff --git a/internal/sessions/codex_provider.go b/internal/sessions/codex_provider.go index eade0044f..d377ee601 100644 --- a/internal/sessions/codex_provider.go +++ b/internal/sessions/codex_provider.go @@ -535,11 +535,16 @@ func codexThreadsOn(home, p string) []string { // CodexThreadsBusyOn says whether a thread a Codex folder's state // databases keep on the provider p was written to in the last -// ActiveWindow, which a move of p's threads leaves where it is: such a -// move has more to do once the thread is quiet. A database that can't be -// read, and a rollout that can't be found, say nothing. +// ActiveWindow, or is held open by a Codex (its writer lock), which a +// move of p's threads leaves where it is: such a move has more to do once +// the thread is quiet and let go. The Codex app holds the lock of every +// thread it has loaded, the chat on screen among them, for as long as it +// keeps it (codex-rs rollout recorder, writer_lock.rs), however long ago +// it was written to. A database that can't be read, and a rollout that +// can't be found, say nothing. func CodexThreadsBusyOn(home, p string) bool { now := time.Now() + locked := codexLockedIDs(home) for _, path := range codexStateDBs(home) { u := url.URL{Scheme: "file", Path: filepath.ToSlash(path), RawQuery: "mode=ro&_pragma=busy_timeout(2000)"} if len(u.Path) >= 2 && u.Path[1] == ':' { @@ -550,11 +555,18 @@ func CodexThreadsBusyOn(home, p string) bool { continue } var paths []string - rows, err := db.Query(`SELECT rollout_path FROM threads WHERE model_provider = ?`, p) + var held bool + rows, err := db.Query(`SELECT id, rollout_path FROM threads WHERE model_provider = ?`, p) if err == nil { for rows.Next() { - var r string - if rows.Scan(&r) == nil && r != "" { + var id, r string + if rows.Scan(&id, &r) != nil { + continue + } + if locked[strings.ToLower(id)] { + held = true + } + if r != "" { paths = append(paths, r) } } @@ -566,10 +578,60 @@ func CodexThreadsBusyOn(home, p string) bool { return true } } + if held { + return true + } } return false } +// codexLockedIDs are the threads of a Codex home a Codex holds open now: +// those whose lock file in thread-writer-locks is locked, as +// holdCodexThread finds them, by lower-case id. Each lock is tried under +// the home's coordination lock and let go at once, so a Codex taking one +// meanwhile waits on the coordination lock rather than being turned away; +// no lock file is made or taken away. A home without thread-writer-locks, +// or with none held, has none. +func codexLockedIDs(home string) map[string]bool { + if home == "" { + return nil + } + locks := filepath.Join(home, "thread-writer-locks") + ents, err := os.ReadDir(locks) + if err != nil { + return nil + } + var ids []string + for _, e := range ents { + if id, ok := strings.CutSuffix(e.Name(), ".lock"); ok && !e.IsDir() && safeID.MatchString(id) { + ids = append(ids, id) + } + } + if len(ids) == 0 { + return nil + } + unlock, ok := filelock.Lock(filepath.Join(locks, ".coordination.lock"), filelock.Wait) + if !ok { + return nil + } + defer unlock() + out := map[string]bool{} + for _, id := range ids { + f, err := os.OpenFile(filepath.Join(locks, id+".lock"), os.O_RDWR, 0) + if err != nil { + continue + } + got, err := filelock.TryLock(f) + if got { + filelock.Unlock(f) + } else if err == nil { + out[strings.ToLower(id)] = true + } + f.Close() + } + return out +} + // MoveCodexThreads moves every thread of a Codex folder its state database // keeps on the provider from to the provider to, each as MoveCodexProvider // moves one: its files' session_meta and its row, a copy of the files kept