From 10bef5fe095e9e06126d28daa19fa593f7610650 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 10 Nov 2026 21:04:11 +0800 Subject: [PATCH] codex: every account shares one list of the Codex app's projects, removals remembered (Michael25651150 on X) The reporter wants the Codex app's projects kept however magpie switches ChatGPT accounts. v0.1.3559 (15acba534) copied the longest list only to an identity with no list yet, so an account with a list of its own (an empty one too) never got the others' projects, and a project added on one account never reached an account that had any. Now, while the app is closed (the same moments as before: the 3s loop once the state file or logins changed, and between a reopen's quit and open), shareCodexProjects gives every identity the file has and every saved Codex login one list: each identity's local-projects together, the signed-in identity's copy first, with the ties the other codexProjectKeys have to them (thread-project-assignments, project-order, pins, appearances, the app-server id maps one level down). A folder is one project: the app gives a new project a random id per account (randomUUID in 26.1103's bundle), so a project of a folder an identity already has maps onto that one, its threads renamed to it. Removals: codex-projects.json (beside logins.json) keeps each identity's project ids and folders as the last look left them. A project a look saw on an identity that the next doesn't have was removed there; it goes from every identity with every tie, as do other projects of its folders, unless the user added that project or folder again since. No record yet removes nothing. A record that can't be read or parsed means what was removed is unknown: nothing is written. The record is written after the state file, and not when the app's start overtook the write, so that look is taken again. The state file is still written through temp + rename, only when it is byte-for-byte what was read, with the first-write backup beside it. Checked against ChatGPT.app 26.1103.60933's own bundle (downloaded from its appcast into a scratch dir, unpacked there): the renderer state schema {owner, inactive:{:{atoms, globals}}}, selectRendererOwner parking/loading Object.values of the global-state key table (the account-scoped keys, codexProjectKeys among them), the local project schema (id, name, rootPaths, backings, createdAt, updatedAt) and randomUUID ids for new projects. The live ~/.codex was not touched. Run (mote refused ssh all session, kex reset; so on xiaomi-gpu): - wsl-run go vet -tags nogui, GOOS=darwin CGO_ENABLED=0 go vet and GOOS=windows go vet of ./internal/provider: ok - wsl-run go test -tags nogui ./internal/provider: ok (281s) - wsl-run go test -run 'TestCodexProjects|TestCodexRendererOwner| TestCodexApp' ./internal/provider ./internal/agent: ok - win-run go test -run 'TestCodexProjects|TestCodexRendererOwner' ./internal/provider: ok - gofmt -l: clean. Red on the old code (origin/main's codex_projects.go with a 3-arg shim): TestCodexProjectsShared (shared with 1, want 2), TestCodexProjectsRemovalRemembered (0, want 3), TestCodexProjectsRecordUnreadable (written). Broken by hand: removals never gone -> RemovalRemembered red; no folder dedupe -> Shared red; no graft of ties -> FollowASwitch and Shared red; a tie not renamed to the folder's project -> Shared red; no MkdirAll for the record -> StepWaitsForTheAppToClose red. Not tried: the real Codex app switching real accounts (it would share Electron's userData with the user's running app); the switch is played by the tests' Go port of 26.1103's selectRendererOwner. No macOS run (mote down). The first look after this release has no record, so a project the user removed on one account before it comes back there. --- docs/subsystems/agent-wiring.md | 2 +- internal/provider/codex_projects.go | 604 ++++++++++++++++++----- internal/provider/codex_projects_test.go | 159 +++++- 3 files changed, 618 insertions(+), 147 deletions(-) diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 56147b23f..de0b6f3fe 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -116,7 +116,7 @@ something else shows up as drift. - A line magpie writes into an agent's TOML, YAML or dotenv config gets a comment line of its own just above it, `# magpie: ; ` (`edit.Mark`, set to `agent.lineNote` by the CLI's `run` in [`mark.go`](../../internal/agent/mark.go); the edit side in [`internal/edit/mark.go`](../../internal/edit/mark.go)). Jevik_AI on X deleted magpie's folders by hand, and Codex's `config.toml` kept `openai_base_url` on the gateway with nothing in it naming magpie: every turn was a 502. Only a one-line scalar that points at the gateway or names magpie's model list gets one, and only when the write adds or changes that line, or it had a note already; a line of the user's own that magpie leaves as it is gets none. The note is never on the value's line: Grok App's `providers.rs` reads the rest of a line as the value. Every write takes the notes out first and puts them back over the lines that still need one, so a note goes with its line and a Disconnect leaves none. A YAML note that would change what the file reads as isn't added (`sameYAMLValue`). JSON has no comments and gets none. Tests set no `Mark`, so their exact bytes stay; `TestMarkedLinesEveryAgent` connects every agent with notes on and checks each gateway line has one, a second sync writes nothing, and Disconnect leaves none; `TestCodexMarkedLines`, `internal/edit`'s `TestMark*`. - Codex signed in to ChatGPT stays beside its sign-in (`openai_base_url`) unless the user picks magpie API. magpie becomes its provider only while the Codex app holds the active account, which it sends nothing for: `/wham/usage` says it isn't allowed, and it has no credits and isn't a workspace still within its overage (`codexHeld`, read by `provider.CodexUsedUp`). With Codex switched off or removed in magpie (`leftAlone`), whose allowance magpie otherwise reads nothing of, the active account is still read for this alone while Codex takes magpie's models beside its sign-in or magpie is its provider for the held account (`Agent.HoldMatters`, through the `provider.CodexHoldMatters` hook; `codexHoldReading`): once a minute at most, with the token as Codex keeps it, never renewed or written (`codexTokenAsKept`), and nothing shown on the Usage page. Before, turning Codex off in magpie after its allowance ran out left the Codex app greying Send for magpie's models through restarts, and one already moved was put back on the held account (sherlock_23333 on X; `TestCodexHoldReadLeftAlone`, `TestCodexHoldMatters`). Where the app goes by what usage can't show (an experiment's gate, a reserve, a Team plan's overage under the reserve experiment), it counts as held: a wrong move costs ChatGPT extras, a missed one every turn. A saved reading kept through a failed read stops saying held once its used-up window has started again; a hold with no window used up stays till a fresh read. The app then loses its ChatGPT state (durable threads, remote control), so a window at 100% alone, which credits get past, doesn't move it (with no credits it does when the backend says `allowed` false, and only then: `codexAtLimit`. The app's composer gate greys Send on that alone, in ChatGPT.app 26.1029 as in 26.1021, and keeps a window of an allowed account at 1% or more, so allowed not said or allowed with a window at 100% is an account it still sends for. A used-up 5h window with the week open is held through it: the backend says allowed false there, as the real Team reply in testdata does with its 5h at 100% and its week at 63%; xiaoq6285 on Discord) (`codex.out` marks the move, and Sync undoes it once the account has room). The same holds on one of Codex's own models joined beside the sign-in (MasterYi on Discord: the Codex app greyed Send for every model on a used-up account): Sync makes magpie the provider on that model as magpie serves it (`codexOwnViaMagpie`, `codex/`), keeps the model picked in `codex.out_own`, and once the account has room puts Codex back joined on it; a model the user picked meanwhile stays theirs. With no ChatGPT account in magpie to serve it, Codex is left as it is (`TestCodexOwnModelGoesThroughMagpieWhileUsedUp`, `TestCodexOwnModelKeptOnChatGPT`). Where magpie would serve that model on the same used-up account alone (no fallback on the Codex subscription and no other ChatGPT account not known out: `provider.CodexServesWhileOut` false), every turn on it would be refused too, but the Codex app greys Send for every model while the account is out, so keeping the account's menu costs a grey Send (shamen, chenhan and xiaoq6285 on Discord). Sync then makes magpie the provider on a stand-in model of magpie's that is on no ChatGPT account (`codexOtherModel`, kept in `codex.out_stand` beside `codex.out_own`), once per held/unheld transition: on the stand-in the model is magpie's, so the branch isn't met again and a steady held state writes nothing and ends no app-server. At the reset Codex is put back joined on its own model; another model picked meanwhile stays theirs (the stand-in itself picked can't be told from staying on it, and gives way to the own model). This reverses f37742e14, which left Codex on its sign-in to keep the account's menu and usage (the app-server restarts it cost, #4550, are the two the takeover makes). With nothing else in magpie to offer (no stand-in) Codex stays on its sign-in, as no takeover could send (`TestCodexOwnModelOneSpentAccountStaysOnItsSignIn`, `TestCodexOwnModelOneSpentAccountTakenOverForOtherModels`, `TestCodexServesWhileOut`). The account is read again at once when a reply says it may be out (a `usage_limit_reached` rest, or an `x-codex-*` window heard at 100%; `provider.CodexMayBeUsedUp`, at most every 20s, the active account only), not only on the five-minute look. A turn relayed to Codex's own sign-in, the one account on (`codexUpstreamOn` with no account, the gateway's `codexRelayedAccount`), is heard the same way: its `x-codex-*` windows and `codex.rate_limits` event kept as the sign-in's usage (`heardCodexLimits`), and a `usage_limit_reached` refusal reading it again. Before, only turns served through magpie's accounts were, so with one account magpie learned the account was out only at the next look, minutes on, and the Codex app kept Send greyed until it was restarted (unsplashz on Discord; `TestCodexUsedUpRelayedAsksAtOnce`, `TestCodexRelayedWindowsHeard`). A Codex started before magpie became its provider keeps sending its own model's turns to its built-in provider; while the sign-in is known out (`provider.CodexUsedUpKnown`) and the request signs as it, those go through routing as `codex/` (`codexAccounts`), as a restarted Codex's do (`TestCodexHeldSignInServedWithoutRestart`). The Codex app greys Send for every model, magpie's too, while its `authMethod` is `chatgpt` and its rate limit says not allowed (its composer's gate in ChatGPT.app 26.1013), and reads `authMethod` from its app-server's `account/read` only as the app-server starts; with magpie the provider (`requires_openai_auth` false) that answers no account, so the gate lifts. So the gateway process restarts the app's own app-server each time magpie becomes Codex's provider for the used-up account (`Agent.AppOut`) and again when Codex is put back on the account after its reset, and likewise whenever what the app-server reads as it starts and magpie writes changes, which is where its requests go (`model_provider`, `openai_base_url` and the magpie table's `base_url`, and its `requires_openai_auth` while that table is Codex's `model_provider`: beside the sign-in the app-server reads the built-in provider's account, so the key following the account out and back is nothing it reads; `codexAppRoute`, through the `provider.CodexAppRoute` hook): a Disconnect, a Connect, failover written or taken out. The model list is not part of it: neither `model_catalog_json` nor what the catalog holds. The catalog follows magpie's names and the effort new sessions start at, which the Codex app saves on each pick, and the ChatGPT app takes an ended app-server as a crash and relaunches, so a route that hashed the catalog (from lucis0116 on X until #4550) ended the app every few minutes (indekkusu141209 on X). A new list is read at the app's next launch or on the Agents row's Restart (`StaleCopies`) A list that drops a model and has it back at the next fetch, the same list in another order, and a catalog read half-written leave the route as it was (`TestCodexEffortPickKeepsTheAppRunning`, `TestCodexAppRouteIgnoresARename`, `TestCodexAppRouteKeepsThroughListFlaps`). Before this an app-server started while Codex was connected kept sending to the gateway after Disconnect until the app was restarted (JiangLiuer222 on X). At the watcher's first look only a used-up account's app-servers are ended, since what the others read before magpie started isn't known. What magpie changes by itself that the app works without waits for the user, though, unless they ticked Restart the Codex app when magpie switches its account back (`Provider.RestartApp`, `provider/restartapp`, off by default, this computer's own like KeepLogin): its switch back once the account it moved off has room (`SwitchWhenSpent` → `switchLoginBy(…, true)`, `codexApp.auto`) and giving Codex its account back at the reset. A switch the user makes between accounts with room waits too: the app keeps its sidebar projects per ChatGPT identity, so a restart onto the new account showed none and every thread under Recent (Michael25651150 and ykj5353 on X, `TestCodexAppLeftRunningForMagpiesOwnChanges`). Those leave the app-server running, log why, and the switch notice's Restart is the way to follow; a user's switch off a used-up account (`codexAppSpentSwitch`), a Connect, a Disconnect and failover written or taken out still restart it, and so does the takeover turned off by the user rather than ended by the reset: its sign-in set to Always ChatGPT (the takeover note's Keep on ChatGPT) or Codex disconnected while magpie stood in (`Agent.AppOutOff` through `provider.CodexTakeoverOff`, asked only as `out` goes false). The app-server the takeover started answers `account/read` with no account, so the app kept its ChatGPT projects and chats hidden after the user turned the takeover off to have them back, and the Windows app has no Restart of its own (Herzz____ on X, `TestCodexAppRestartedWhenTheTakeoverIsTurnedOff`). So does whatever leaves the app-server on a used-up account, tick or not: the takeover in, the first look on one, and magpie's switch off one (`needed` in `codexAppStep`), since the app greys Send there and reads the account only as its app-server starts, so with the tick off a takeover at the limit left Send grey and the fallback unreachable (v0.1.2826 to its fix). An app-server left running on the account magpie switched Codex back off is restarted too once that account is read held (`restartCodexAppLeftOnSpent`, on each full look of `KeepOnAnAccountWithRoom`, once per app-server left): it keeps the account it started on (`CodexAppStale`), so when that ran out the app greyed Send for every model while the account Codex is signed in to had room and nothing else read the old one (nb5p on Discord: B first in magpie, the app still on A; `TestCodexAppLeftOnASpentAccountIsRestarted`). atom0964 on Discord had both sign-in ticks off and the ChatGPT app relaunched at every switch between two Plus accounts (`TestCodexAppLeftRunningForMagpiesOwnChanges`, `TestCodexAppFirstLookOnAUsedUpAccountRestarts`, `restart-app.test.cjs`). It runs on every system (`KeepCodexAppOnItsProvider`, every 3s; Ethereal499 and Isdavexxx on X, MasterYi on Discord, #540: the earlier once-only reopen ran on macOS from the GUI process only, so Windows, Linux, a GUI-less magpie and the switch back stayed greyed). It ends only app-servers on magpie's Codex home (`codexAppHomeIs`: the process's `CODEX_HOME`, else `HOME/.codex`, read by `proc.EnvOf`; Windows can't tell and counts every one), only once no Codex request is in flight through the gateway nor ended in the last 10s (`Server.CodexBusy`) and no session under the Codex home has a turn started and not ended (`codexTurnOpen`), and with a clean exit (`proc.End`: SIGTERM, `TerminateProcess` with code 0), since the app shows any other exit as a crash. Each end is logged with what made the app-server stale: the account switched, the route changed, or the used-up takeover (`codex: ended the Codex app's app-server [pid] for the app to start another: `), so a crash a user reports can be put down to one of them (#4550, `TestCodexAppEndSaysWhy`). The app starts another app-server at once and keeps its window, threads and drafts (tried in the real app in a sandbox `CODEX_HOME`, both ways). An app-server that outlives three ends, or may not be ended, leaves the row saying to quit and reopen the app (`CodexAppStuck`). An ended app-server's pid gone doesn't mean the app has another: the Windows app (MSIX `OpenAI.Codex`, stdio) starts one only once the old one's stdout closes, and a child it left (an MCP server, a tool command) holds that pipe open, so the app answered "Codex app-server process is not available" until it was restarted (蛋仔 on Discord). The watcher waits `codexAppBackWait` (30s) for another app-server; when none came and the app is still open (`CodexAppOpen`), it quits and opens the app as the Agents row's Restart does (`CodexAppReopen`, Windows only), else the row says to (`CodexAppStuck`). `RestartCodexApp`, uninstall's `RestartCodexAppWhenIdle` and the switch notice's Restart (`RestartSwitchedCodexApp`) wait for it the same way and reopen or say so alike, and `recheckLeft` keeps the record while the app is open with no app-server. A signed-in ChatGPT app (26.1021) can still fail on the app-server it starts next ("Hosted AppServerManager identity is not ready") and show "ChatGPT hit a snag" until it is quit and opened again (ysm119 on Discord, #4550), a fault in the app the clean end can't avoid. So for `codexAppCrashWait` (60s) after each of these ends ([`codex_app_crash.go`](../../internal/provider/codex_app_crash.go)) the app's own logs are read (`CodexAppCrashed`, [`agent/codex_app_crash.go`](../../internal/agent/codex_app_crash.go): `~/Library/Logs/com.openai.codex`, `%LOCALAPPDATA%\Codex\Logs` and the Store package's, `$XDG_STATE_HOME/codex/logs`) for a whole `fatal_error_broadcasted` line stamped after the end. When the page shows and no request has gone through magpie or been in flight since, and no Codex turn has opened since, the app is quit and opened once (`CodexAppRelaunch`: ⌘Q's quit and `open` on macOS, never forced, ChatGPT.app by its bundle id only; `CodexAppReopen` on Windows), but only with Restart the Codex app ticked (`codexRestartsApp`): unasked, the quit read as magpie force-restarting the user's app whenever quota ran out (Michael25651150 on X, `TestCodexAppNotQuitUnasked`), and the same tick gates the Windows reopen when no app-server came back (`codexAppGotNone`). The app-server's own restart at the takeover isn't gated: the app reads its account only as its app-server starts, so without it Send stays grey on the used-up account. Where the tick is off or that can't be done (Linux, an app that didn't quit) the Agents row says to quit and reopen it (`CodexAppSnagged`, `appSnag`) until the app-servers seen then are gone or the app is closed. Logs that can't be read reopen nothing (`TestCodexAppReopenedWhenItShowsItsErrorPage`, `TestCodexAppInUseAfterItsErrorPageIsLeft`, `TestCodexAppCrashedReadsItsOwnLogs`, `TestCodexAppRelaunchOnlyTheCodexApp`, `codex-app-snag.test.cjs`). A turn left open in Codex's sessions holds the restart for up to `codexTurnWindow` (30m), except where the app-server is on a used-up account: after a switch off one (`SwitchWhenSpent` → `codexAppSpentSwitch`, or a switch by hand off an account last read held, `codexHeldKnown` in `noteCodexSwitch`) and when magpie becomes Codex's provider for one (`codexAppStep`'s `into`; xiaoq6285 on Discord: quota out, then another account or provider picked, and Send stayed grey; `TestCodexAppServerRestartedPastATurnStuckWhenMagpieTakesOver`, `TestCodexHandSwitchOffAHeldAccountIsSpent`). There a turn that has written no session file and sent nothing through magpie for `codexTurnStuckAfter` (2m) counts stuck and the app-server is restarted past it, since its next request would be refused on that account (蛋仔 on Discord: quota ran out mid-task and the app hung till restarted; `TestCodexAppServerRestartedPastATurnStuckOnTheSpentAccount`). An account switch restarts nothing, and neither the app nor the background daemon is said to be left on the old account (`CodexAppStale`, `CodexDaemonStale`, the CLI's switch line), while the provider Codex's config.toml names takes no ChatGPT account (`provider.CodexNoAccount`, `codexNoAccount` in [`agents.go`](../../internal/agent/agents.go)): a top-level `model_provider` other than `openai` whose `[model_providers]` table doesn't say `requires_openai_auth = true`, such as magpie's with the user's own `false` (danzi002 on Discord). Codex then sends the table's key and its app-server reads no account (codex-rs `account_state`, `resolve_provider_auth`); tried with codex-cli 0.165.0 in a sandbox `CODEX_HOME`: `account/read` and `getAuthStatus` said no account before and after auth.json was switched, and `codex exec` sent `Bearer` the table's key on both accounts. A route change still restarts it, and so does a switch under a profile, the built-in provider, a provider with no table or a config that can't be read (`TestCodexNoAccountSwitchRestartsNothing`, `TestCodexNoAccountOfEachConfig`, `TestCodexNoAccountFollowsRequiresOpenAIAuth`). Until the reset the app's ChatGPT side is off (cloud tasks, its usage meter, Log out); the Agents row says so with the reset's time (`appOut` in `/api/state`, `CodexOutUntil`), and it all comes back at the reset. While the active account is held or a window is at 90% or more, its usage is read every minute rather than every five (`codexLookEvery`). `TestCodexAppServerRestartedEachWay`, `TestCodexAppServerRestartedOnDisconnect`, `TestCodexAppRouteFollowsConnectAndDisconnect`, `TestCodexEffortPickKeepsTheAppRunning`, `TestCodexAppRouteIgnoresARename`, `TestCodexAppServerUnknown`, `TestCodexAppServerStuck`, `TestCodexAppServersOnHome`, `TestCodexTurnOpen`, `TestCodexBusy`, `codex-app-out.test.cjs`. -- The Codex app (ChatGPT.app 26.1103 and on) keeps its sidebar's projects per ChatGPT identity in `$CODEX_HOME/.codex-global-state.json`, under `electron-account-renderer-state-v1` (`{owner, inactive: {: {atoms, globals}}}`, the hash the sha256 hex of `JSON.stringify([chatgpt_user_id, chatgpt_account_id])`): on an account change it parks the old identity's account-scoped globals and loads the new one's, so a switch to an account that never had the app open showed no projects (Michael25651150 on X; #5497, #5602, #5702, #5874). The app reads the file only as it starts and writes its memory over it, so magpie writes it only while the app is closed ([`codex_projects.go`](../../internal/provider/codex_projects.go)): `codexProjectsStep` in `codexAppStep`, once the file, auth.json or logins.json changed (at most every 30s while the app may be open, since `CodexAppOpen` lists processes), and `CodexAppClosed` between the quit and the open of every reopen (`appQuitDone` in [`apprestart.go`](../../internal/agent/apprestart.go)). Each identity of auth.json and magpie's saved Codex logins whose snapshot has no `local-projects` key gets the project keys (`codexProjectKeys`) of the identity with the most; a list of its own, an emptied one too, is left. A ChatGPT project's mirror (`g-p-` ids, and every tie to one) isn't carried, and a backing naming another account is dropped, since the app refuses to act on a project "belongs to a different ChatGPT account". A file without the key (an older app) or that doesn't parse is left as it is; before its first write the file as it was is kept beside it (`.magpie-before-projects`). Projects added while the app runs reach the other accounts once it is closed. With no account (the takeover, `requires_openai_auth` false) the app shows no projects by its own rule, and they come back with the account (`TestCodexProjectsFollowASwitch`, `TestCodexProjectsOwnListKept`, `TestCodexProjectsUnknownFileLeft`, `TestCodexProjectsStepWaitsForTheAppToClose`). +- The Codex app (ChatGPT.app 26.1103 and on) keeps its sidebar's projects per ChatGPT identity in `$CODEX_HOME/.codex-global-state.json`, under `electron-account-renderer-state-v1` (`{owner, inactive: {: {atoms, globals}}}`, the hash the sha256 hex of `JSON.stringify([chatgpt_user_id, chatgpt_account_id])`): on an account change it parks the old identity's account-scoped globals and loads the new one's, so a switch to an account that never had the app open showed no projects (Michael25651150 on X; #5497, #5602, #5702, #5874). The app reads the file only as it starts and writes its memory over it, so magpie writes it only while the app is closed ([`codex_projects.go`](../../internal/provider/codex_projects.go)): `codexProjectsStep` in `codexAppStep`, once the file, auth.json or logins.json changed (at most every 30s while the app may be open, since `CodexAppOpen` lists processes), and `CodexAppClosed` between the quit and the open of every reopen (`appQuitDone` in [`apprestart.go`](../../internal/agent/apprestart.go)). Every identity, those of auth.json and magpie's saved Codex logins and those the file has, gets one list (`shareCodexProjects`, Michael25651150 on X again): each identity's `local-projects` together, the signed-in identity's copy first, with the ties the other project keys (`codexProjectKeys`) have to them, one or two levels down (`codexGraft`). A folder is one project (`codexRootKey`): the app gives a project a random id on each account, so a project of a folder an identity has already is that one, its threads renamed to it. What the user removed is remembered: `codex-projects.json` beside logins.json keeps each identity's project ids and folders as the last look left them, and a project a look saw on an identity that the next doesn't have was removed there, so it goes from every identity with every tie to it (`codexPrune`), as do other projects of its folders, unless the user added that project or folder again on some identity since. A record that can't be read or parsed means what was removed is unknown, and nothing is written. The first look, with no record, removes nothing. A ChatGPT project's mirror (`g-p-` ids, and every tie to one) isn't shared, and a backing naming another account is dropped (`projectFor`), since the app refuses to act on a project "belongs to a different ChatGPT account". The record is written only after the state file is, so a look the app's own start overtook is taken again. A file without the key (an older app) or that doesn't parse is left as it is; before its first write the file as it was is kept beside it (`.magpie-before-projects`). Projects added or removed while the app runs reach the other accounts once it is closed. With no account (the takeover, `requires_openai_auth` false) the app shows no projects by its own rule, and they come back with the account (`TestCodexProjectsFollowASwitch`, `TestCodexProjectsShared`, `TestCodexProjectsRemovalRemembered`, `TestCodexProjectsRecordUnreadable`, `TestCodexProjectsUnknownFileLeft`, `TestCodexProjectsStepWaitsForTheAppToClose`). - Moving a field from one of magpie's models to another (the agent's own picker) is not drift. Moving it off magpie is. - Claude Desktop applying a configLibrary profile other than magpie's is not drift when that profile is a gateway profile for this magpie's gateway (`desktopAppliedGateway` in [`claudedesktop.go`](../../internal/agent/claudedesktop.go)): Desktop's "Import configuration" adds a file exported on another computer, magpie's profile there with the user's connectors (`managedMcpServers`), as a new entry under a random id (aa86222 on Discord). magpie keeps it applied on Reconnect and through Sync, and writes in it only `inferenceGatewayApiKey` (with a missing auth scheme) when the gateway would refuse its key (`desktopKeyApplied`; magpie's own keys count as taken, `desktopKeyTaken`). A profile for another gateway, CC Switch's among them, is still drift, and Reconnect applies magpie's. The first switch-on still starts magpie's profile from an applied one (#2035). `TestClaudeDesktopImportedProfileIsOnMagpie`. - Claude Desktop 4.4212 (10-29) seals the secrets of its configLibrary profiles at rest: at every start it writes `inferenceGatewayApiKey` (and every other string secret its schema drops on export) back as `__sealed__:v1:` + base64 of `{"configLibrary":{"key":…,"value":…}}` behind `anthropic.claude.crossProfileSecret.v1:`, protected with the user's DPAPI on Windows (entropy `anthropic.claude.crossProfileSecret.v1`, claude-native's `userDpapiProtect`) and Electron's safeStorage (the Keychain) on macOS, and it sends the gateway the key as it was. `desktopOpen` ([`desktopseal.go`](../../internal/agent/desktopseal.go)) reads the key as Desktop does: on Windows it opens the seal (`desktopUnprotect`, `CryptUnprotectData`, never prompting) and judges what is in it; a seal it can't open (macOS, another user's) is unknown, so Check doesn't call it changed and `desktopKeyApplied` doesn't write over it. Before this the key read as changed after every Desktop start and Reconnect only wrote it in the clear for Desktop to seal again (a Windows user on Discord). A key in the clear that isn't one the gateway takes, a missing key and another address are still drift (`TestClaudeDesktopSealedKeyIsNotChanged`, `TestClaudeDesktopImportedSealedKeyStays`, `TestClaudeDesktopSealedKeyOpened` on Windows). diff --git a/internal/provider/codex_projects.go b/internal/provider/codex_projects.go index d0dbbbae8..b6ffe71e0 100644 --- a/internal/provider/codex_projects.go +++ b/internal/provider/codex_projects.go @@ -7,6 +7,7 @@ import ( "encoding/hex" "encoding/json" "errors" + "fmt" "log" "maps" "os" @@ -16,6 +17,7 @@ import ( "sync" "time" + "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/steady" ) @@ -34,11 +36,15 @@ import ( // // The app reads the file only as it starts and holds it in memory, so a // write while it runs is lost (it writes its own over it). So while the -// app is closed magpie gives each identity of its saved Codex logins that -// has no projects of its own the projects of the one that has the most -// (carryCodexProjects); the app then loads them on its next switch to -// that account. An identity that has projects, an emptied list included, -// is left alone. With no account at all (magpie's takeover, when Codex's +// app is closed magpie gives every identity, those of its saved Codex +// logins and those the file has, one list (shareCodexProjects): each +// identity's projects together, a folder once, less what the user +// removed. A project a look saw on an identity and the next look doesn't +// was removed there, and goes from every identity rather than coming +// back from another (codex-projects.json keeps what was seen). The app +// then loads the list on its next switch to any account. Projects added +// or removed while the app runs reach the other accounts once it is +// closed. With no account at all (magpie's takeover, when Codex's // provider takes no ChatGPT account) the app shows no projects, by its // own rule; they come back with the account. @@ -130,12 +136,89 @@ func codexGlobalStatePath(home string) string { // nothing is written to it. var errCodexStateUnknown = errors.New("the Codex app's state file isn't the shape magpie knows") -// carryCodexProjects gives every identity in auths (auth.json bytes) that -// has no projects in the Codex app's state file at home the projects of -// the identity that has the most, and says how many it gave them to. The -// app must be closed: it writes its own over the file. A file that can't -// be read or parsed, or has no per-identity state, is left as it is. -func carryCodexProjects(home string, auths [][]byte) (int, error) { +// codexProjectsRecordPath is what shareCodexProjects last saw of each +// identity's projects, so a project the user removed is told apart from +// one an account never had. +func codexProjectsRecordPath() string { + return appdir.Join(filepath.Dir(Path()), "codex-projects.json") +} + +// codexProjectsRecord is that file: per identity hash, each of its local +// projects' id and the folders it is (codexRootKey). +type codexProjectsRecord struct { + Identities map[string]map[string]string `json:"identities"` +} + +// readCodexProjectsRecord is the record at p; none yet is an empty one, +// and one that can't be read or parsed is an error: what was removed is +// unknown then, so nothing is written. +func readCodexProjectsRecord(p string) (map[string]map[string]string, []byte, error) { + b, err := os.ReadFile(p) + if errors.Is(err, os.ErrNotExist) { + return map[string]map[string]string{}, nil, nil + } + if err != nil { + return nil, nil, err + } + var r codexProjectsRecord + if err := json.Unmarshal(b, &r); err != nil { + return nil, nil, fmt.Errorf("%s: %w", p, err) + } + if r.Identities == nil { + r.Identities = map[string]map[string]string{} + } + return r.Identities, b, nil +} + +// codexRootKey is the folders a local project is, "" for none: two +// projects of one folder are one project to the user, whatever their ids +// (the app gives a new project a random id on each account). +func codexRootKey(p json.RawMessage) string { + var v struct { + RootPaths []string `json:"rootPaths"` + } + if json.Unmarshal(p, &v) != nil || len(v.RootPaths) == 0 { + return "" + } + rs := slices.Clone(v.RootPaths) + for i, r := range rs { + rs[i] = filepath.Clean(r) + } + slices.Sort(rs) + return strings.Join(rs, "\x00") +} + +// codexLocalProjects is the local projects of globals g by id, the +// ChatGPT projects' mirrors left out; has is whether g has a list at all. +func codexLocalProjects(g map[string]json.RawMessage) (lp map[string]json.RawMessage, has bool, err error) { + v, ok := g["local-projects"] + if !ok { + return nil, false, nil + } + var all map[string]json.RawMessage + if json.Unmarshal(v, &all) != nil { + return nil, true, errCodexStateUnknown + } + lp = map[string]json.RawMessage{} + for id, p := range all { + if !strings.HasPrefix(id, codexChatGPTProject) { + lp[id] = p + } + } + return lp, true, nil +} + +// shareCodexProjects gives every Codex identity in the Codex app's state +// file at home, and every one of auths (auth.json bytes), one list of +// projects: every identity's, less those the user removed. A project the +// record (at recordPath) saw on an identity that no longer has it was +// removed there, and goes from every identity, as do other projects of +// its folders, unless the user added it again on some identity since. It +// says how many identities it changed. The app must be closed: it writes +// its own over the file. A file that can't be read or parsed, or has no +// per-identity state, is left as it is, as is everything when the record +// can't be read. +func shareCodexProjects(home string, auths [][]byte, recordPath string) (int, error) { path := codexGlobalStatePath(home) raw, err := os.ReadFile(path) if err != nil { @@ -163,6 +246,10 @@ func carryCodexProjects(home string, auths [][]byte) (int, error) { if json.Unmarshal(rs, &keep) != nil { return 0, errCodexStateUnknown } + prev, prevRaw, err := readCodexProjectsRecord(recordPath) + if err != nil { + return 0, err + } owner := "" if r.Owner != nil { owner = *r.Owner @@ -171,7 +258,7 @@ func carryCodexProjects(home string, auths [][]byte) (int, error) { parked := map[string]map[string]json.RawMessage{} for h, v := range r.Inactive { var s map[string]json.RawMessage - if json.Unmarshal(v, &s) != nil { + if json.Unmarshal(v, &s) != nil || s == nil { return 0, errCodexStateUnknown } var g map[string]json.RawMessage @@ -183,82 +270,158 @@ func carryCodexProjects(home string, auths [][]byte) (int, error) { if owner != "" { snaps[owner] = top // the owner's globals are the file's own } - // the source: the identity with the most projects, the owner first - src, most := "", 0 - count := func(g map[string]json.RawMessage) int { - var lp map[string]json.RawMessage - if json.Unmarshal(g["local-projects"], &lp) != nil { - return 0 - } - n := 0 - for id := range lp { - if !strings.HasPrefix(id, codexChatGPTProject) { - n++ - } - } - return n - } + // every identity, the one signed in first: its copy of a project wins + ident := map[string]codexIdentity{} + var order []string if owner != "" { - src, most = owner, count(top) + order = append(order, owner) } - hashes := slices.Sorted(maps.Keys(parked)) - for _, h := range hashes { - if n := count(snaps[h]); n > most { - src, most = h, n + for _, h := range slices.Sorted(maps.Keys(parked)) { + if h != owner { + order = append(order, h) } } - if most == 0 { - return 0, nil - } - given := 0 - seen := map[string]bool{} - for _, auth := range auths { - h := codexRendererOwner(auth) - if h == "" || seen[h] || h == src { + for _, a := range auths { + h := codexRendererOwner(a) + if h == "" { + continue + } + if _, ok := ident[h]; !ok { + ident[h] = codexIdentityOf(a) + } + if !slices.Contains(order, h) { + order = append(order, h) + } + } + + // what the user removed since the record, and added + cur := map[string]map[string]json.RawMessage{} + for _, h := range order { + lp, has, err := codexLocalProjects(snaps[h]) + if err != nil { + return 0, err + } + if has { + cur[h] = lp + } + } + removedIDs, removedRoots := map[string]bool{}, map[string]bool{} + addedIDs, addedRoots := map[string]bool{}, map[string]bool{} + for h, lp := range cur { + was, ok := prev[h] + if !ok { + continue // never seen: nothing it has was added or removed + } + for id, root := range was { + if _, still := lp[id]; !still { + removedIDs[id] = true + if root != "" { + removedRoots[root] = true + } + } + } + for id, p := range lp { + if _, had := was[id]; !had { + addedIDs[id] = true + if k := codexRootKey(p); k != "" { + addedRoots[k] = true + } + } + } + } + gone := func(id string, p json.RawMessage) bool { + if addedIDs[id] { + return false // added again since: the user's latest word + } + k := codexRootKey(p) + if k != "" && addedRoots[k] { + return false + } + return removedIDs[id] || (k != "" && removedRoots[k]) + } + + // the shared list, in the order the identities show them + union := map[string]json.RawMessage{} + var seq []string + for _, h := range order { + lp := cur[h] + var po []string + _ = json.Unmarshal(snaps[h]["project-order"], &po) + ids := slices.Clone(po) + ids = append(ids, slices.Sorted(maps.Keys(lp))...) + for _, id := range ids { + p, ok := lp[id] + if !ok || gone(id, p) { + continue + } + if _, ok := union[id]; !ok { + union[id] = p + seq = append(seq, id) + } + } + } + + changed := 0 + after := map[string]map[string]string{} // the record to keep + for _, h := range order { + if h == "" { continue } - seen[h] = true g := snaps[h] - if _, has := g["local-projects"]; has { - continue // its own list, an emptied one too + ng, did, err := sharedGlobals(g, h, ident[h], union, seq, gone, order, snaps) + if err != nil { + return 0, err } - carried := carriedProjects(snaps[src], codexIdentityOf(auth)) - if len(carried) == 0 { + if lp, has, _ := codexLocalProjects(ng); has { + rec := map[string]string{} + for id, p := range lp { + rec[id] = codexRootKey(p) + } + after[h] = rec + } + if !did { continue } + changed++ if h == owner { - for k, v := range carried { - top[k] = v + maps.Copy(top, ng) + for k := range top { + if _, ok := ng[k]; !ok && slices.Contains(codexProjectKeys, k) { + delete(top, k) + } } - } else { - s := parked[h] - if s == nil { - s = map[string]json.RawMessage{"atoms": json.RawMessage("{}")} - } - if g == nil { - g = map[string]json.RawMessage{} - } - for k, v := range carried { - g[k] = v - } - gb, err := json.Marshal(g) - if err != nil { - return 0, err - } - s["globals"] = gb - sb, err := json.Marshal(s) - if err != nil { - return 0, err - } - if r.Inactive == nil { - r.Inactive = map[string]json.RawMessage{} - } - r.Inactive[h] = sb + continue } - given++ + s := parked[h] + if s == nil { + s = map[string]json.RawMessage{"atoms": json.RawMessage("{}")} + } + gb, err := json.Marshal(ng) + if err != nil { + return 0, err + } + s["globals"] = gb + sb, err := json.Marshal(s) + if err != nil { + return 0, err + } + if r.Inactive == nil { + r.Inactive = map[string]json.RawMessage{} + } + r.Inactive[h] = sb } - if given == 0 { - return 0, nil + saveRecord := func() error { + b, err := json.Marshal(codexProjectsRecord{Identities: after}) + if err != nil || bytes.Equal(b, prevRaw) { + return err + } + if err := os.MkdirAll(filepath.Dir(recordPath), 0o700); err != nil { + return err + } + return steady.WriteFile(recordPath, b, 0o600) + } + if changed == 0 { + return 0, saveRecord() } ib, err := json.Marshal(r.Inactive) if err != nil { @@ -289,79 +452,272 @@ func carryCodexProjects(home string, auths [][]byte) (int, error) { return 0, err } } - // the app opened meanwhile: its own state wins + // the app opened meanwhile: its own state wins, and the record waits + // for the next look if now, err := os.ReadFile(target); err != nil || !bytes.Equal(now, raw) { return 0, nil } if err := steady.WriteFile(target, out, mode); err != nil { return 0, err } - return given, nil + return changed, saveRecord() } -// carriedProjects is the project keys of globals g as an identity id gets -// them: a ChatGPT project's mirror and every tie to one left out, and a -// project's ties to another ChatGPT account's own project dropped. -func carriedProjects(g map[string]json.RawMessage, id codexIdentity) map[string]json.RawMessage { - out := map[string]json.RawMessage{} - for _, k := range codexProjectKeys { - v, ok := g[k] - if !ok { +// sharedGlobals is globals g of identity h (who: its ChatGPT identity, +// zero when magpie has no login for it) with the shared list: its own +// projects that are gone dropped with every tie to them, and each project +// of union it hasn't got added with the ties the other identities have +// to it. A project of a folder it has already is that one. did is whether +// anything changed; g itself is not. +func sharedGlobals(g map[string]json.RawMessage, h string, who codexIdentity, union map[string]json.RawMessage, seq []string, gone func(string, json.RawMessage) bool, order []string, snaps map[string]map[string]json.RawMessage) (map[string]json.RawMessage, bool, error) { + var all map[string]json.RawMessage // its own, ChatGPT mirrors too + if v, ok := g["local-projects"]; ok && json.Unmarshal(v, &all) != nil { + return nil, false, errCodexStateUnknown + } + if all == nil { + all = map[string]json.RawMessage{} + } + removed := map[string]bool{} + roots := map[string]string{} // folders → its project + for id, p := range all { + if strings.HasPrefix(id, codexChatGPTProject) { continue } + if gone(id, p) { + removed[id] = true + delete(all, id) + continue + } + if k := codexRootKey(p); k != "" { + roots[k] = id + } + } + as := map[string]string{} // another identity's project id → its own here + for _, id := range seq { + if _, ok := all[id]; ok { + continue + } + p := union[id] + if k := codexRootKey(p); k != "" { + if mine, ok := roots[k]; ok { + as[id] = mine + continue + } + roots[k] = id + } + all[id] = projectFor(p, who) + as[id] = id + } + added := 0 + for id, to := range as { + if id == to { + added++ + } + } + if len(removed) == 0 && added == 0 { + return g, false, nil + } + out := maps.Clone(g) + if out == nil { + out = map[string]json.RawMessage{} + } + lb, err := json.Marshal(all) + if err != nil { + return nil, false, err + } + out["local-projects"] = lb + for _, k := range codexProjectKeys { if k == "local-projects" { - v = ownLocalProjects(v, id) - } else { - v = withoutChatGPTProjects(v) + continue } - if v != nil { - out[k] = v + var v any + if raw, ok := g[k]; ok && json.Unmarshal(raw, &v) != nil { + continue // a value this doesn't read stays as it is + } + had := v != nil + v = codexPrune(v, removed, 0) + for _, s := range order { + if s == h { + continue + } + raw, ok := snaps[s][k] + if !ok { + continue + } + var sv any + if json.Unmarshal(withoutChatGPTProjects(raw), &sv) != nil { + continue + } + v = codexGraft(v, sv, as, 0) + } + switch { + case v == nil && had: + delete(out, k) + case v != nil: + b, err := json.Marshal(v) + if err != nil { + return nil, false, err + } + out[k] = b } } - if _, ok := out["local-projects"]; !ok { - return nil - } - return out + return out, true, nil } // codexBackings are a local project's ties to a ChatGPT account's project. var codexBackings = []string{"chatGptBacking", "retiredChatGptBacking", "chatGptBackingCreation"} -func ownLocalProjects(v json.RawMessage, id codexIdentity) json.RawMessage { - var lp map[string]map[string]json.RawMessage - if json.Unmarshal(v, &lp) != nil { - return nil +// projectFor is project p as identity id gets it: a tie to another +// ChatGPT account's own project dropped (the app refuses one: "belongs to +// a different ChatGPT account"). +func projectFor(p json.RawMessage, id codexIdentity) json.RawMessage { + var m map[string]json.RawMessage + if json.Unmarshal(p, &m) != nil { + return p } - for pid, p := range lp { - if strings.HasPrefix(pid, codexChatGPTProject) { - delete(lp, pid) - continue + dropped := false + for _, b := range codexBackings { + var who struct { + AccountID string `json:"accountId"` + UserID string `json:"userId"` } - dropped := false - for _, b := range codexBackings { - var who struct { - AccountID string `json:"accountId"` - UserID string `json:"userId"` - } - if bv, ok := p[b]; ok && (json.Unmarshal(bv, &who) != nil || who.AccountID != id.account || who.UserID != id.user) { - delete(p, b) - dropped = true - } - } - if dropped { - delete(p, "chatGptBackingRecoveryPending") + if bv, ok := m[b]; ok && (json.Unmarshal(bv, &who) != nil || who.AccountID == "" || who.AccountID != id.account || who.UserID != id.user) { + delete(m, b) + dropped = true } } - if len(lp) == 0 { - return nil + if !dropped { + return p } - b, err := json.Marshal(lp) + delete(m, "chatGptBackingRecoveryPending") + b, err := json.Marshal(m) if err != nil { - return nil + return p } return b } +// codexPrune drops every mention of a removed project from v: an id in a +// list, an entry keyed by one or naming one, one level down too, and v +// itself when it names one. +func codexPrune(v any, removed map[string]bool, depth int) any { + if len(removed) == 0 { + return v + } + switch t := v.(type) { + case string: + if removed[t] { + return nil + } + case []any: + out := []any{} + for _, e := range t { + if s, ok := e.(string); ok && removed[s] { + continue + } + out = append(out, e) + } + return out + case map[string]any: + out := map[string]any{} + for k, e := range t { + if s, ok := e.(string); removed[k] || (ok && removed[s]) { + continue + } + if depth == 0 { + if m, ok := e.(map[string]any); ok { + e = codexPrune(m, removed, 1) + } + } + out[k] = e + } + return out + } + return v +} + +// codexGraft adds to v what src says of the projects in as (another +// identity's id → this one's): an id in a list, an entry keyed by one or +// naming one, one level down too. What v says already stays. +func codexGraft(v, src any, as map[string]string, depth int) any { + switch s := src.(type) { + case []any: + d, ok := v.([]any) + if v != nil && !ok { + return v + } + for _, e := range s { + id, ok := e.(string) + to, mapped := as[id] + if !ok || !mapped || slices.Contains(d, any(to)) { + continue + } + d = append(d, to) + } + if d == nil { + return v + } + return d + case map[string]any: + d, ok := v.(map[string]any) + if v != nil && !ok { + return v + } + out := maps.Clone(d) + if out == nil { + out = map[string]any{} + } + for k, e := range s { + if to, ok := as[k]; ok { + if _, has := out[to]; !has { + out[to] = codexRename(e, as) + } + continue + } + if id, ok := e.(string); ok { + if to, ok := as[id]; ok { + if _, has := out[k]; !has { + out[k] = to + } + } + continue + } + if m, ok := e.(map[string]any); ok && depth == 0 { + sub, _ := out[k].(map[string]any) + if _, has := out[k]; has && sub == nil { + continue + } + if g, _ := codexGraft(sub, m, as, 1).(map[string]any); len(g) > 0 { + out[k] = g + } + } + } + if v == nil && len(out) == 0 { + return nil + } + return out + } + return v +} + +// codexRename is e with a project id in as, or a list of them, named as +// this identity names it. +func codexRename(e any, as map[string]string) any { + switch t := e.(type) { + case string: + if to, ok := as[t]; ok { + return to + } + case []any: + out := make([]any, len(t)) + for i, x := range t { + out[i] = codexRename(x, as) + } + return out + } + return e +} + // withoutChatGPTProjects drops a ChatGPT project's id from a list, and an // entry keyed by one or naming one from a record, one level down. func withoutChatGPTProjects(v json.RawMessage) json.RawMessage { @@ -411,16 +767,16 @@ func codexProjectAuths() [][]byte { return out } -// CodexAppClosed carries the user's projects to each of Codex's accounts -// that has none in the Codex app (carryCodexProjects); the caller knows -// the app is closed: the agent package between its quit and its open. +// CodexAppClosed gives all of Codex's accounts one list of projects in +// the Codex app (shareCodexProjects); the caller knows the app is closed: +// the agent package between its quit and its open. func CodexAppClosed() { - n, err := carryCodexProjects(codexHome(), codexProjectAuths()) + n, err := shareCodexProjects(codexHome(), codexProjectAuths(), codexProjectsRecordPath()) switch { case err != nil: - log.Printf("codex: carrying the Codex app's projects to its other accounts: %v", err) + log.Printf("codex: sharing the Codex app's projects between its accounts: %v", err) case n > 0: - log.Printf("codex: gave %d of Codex's accounts the Codex app's projects", n) + log.Printf("codex: shared the Codex app's projects with %d of Codex's accounts", n) } codexProjects.Lock() codexProjects.last = codexProjectsMark() diff --git a/internal/provider/codex_projects_test.go b/internal/provider/codex_projects_test.go index 6ac6ea622..701ebae8b 100644 --- a/internal/provider/codex_projects_test.go +++ b/internal/provider/codex_projects_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "os" + "path/filepath" "slices" "testing" "time" @@ -158,10 +159,11 @@ func codexStateFixture(t *testing.T, home string, a []byte, b []byte) string { // switched as magpie switches it, shows them on every account. func TestCodexProjectsFollowASwitch(t *testing.T) { home := t.TempDir() + rec := filepath.Join(t.TempDir(), "codex-projects.json") a, b, c := codexTestAuth("user-a", "acct-a"), codexTestAuth("user-b", "acct-b"), codexTestAuth("user-c", "acct-c") path := codexStateFixture(t, home, a, b) - n, err := carryCodexProjects(home, [][]byte{a, b, c}) + n, err := shareCodexProjects(home, [][]byte{a, b, c}, rec) if err != nil || n != 2 { t.Fatalf("carried to %d (%v), want b and c", n, err) } @@ -206,39 +208,148 @@ func TestCodexProjectsFollowASwitch(t *testing.T) { t.Fatalf("no backup: %v", err) } // once more: nothing to do - if n, err := carryCodexProjects(home, [][]byte{a, b, c}); n != 0 || err != nil { + if n, err := shareCodexProjects(home, [][]byte{a, b, c}, rec); n != 0 || err != nil { t.Fatalf("carried again to %d (%v)", n, err) } } -// A project the user added or removed on an account is that account's: -// an identity with a list of its own, an emptied one too, is left alone, -// and the source can be a parked identity when the owner has none. -func TestCodexProjectsOwnListKept(t *testing.T) { +// add is the user adding a folder as a project in the app's sidebar. +func (s *codexAppSim) add(id, root string) { + lp, _ := s.state["local-projects"].(map[string]any) + if lp == nil { + lp = map[string]any{} + } + lp[id] = map[string]any{"id": id, "name": filepath.Base(root), "rootPaths": []any{root}, "createdAt": 3, "updatedAt": 3} + s.state["local-projects"] = lp + po, _ := s.state["project-order"].([]any) + s.state["project-order"] = append(po, id) +} + +// remove is the user removing a project from the sidebar. +func (s *codexAppSim) remove(id string) { + lp, _ := s.state["local-projects"].(map[string]any) + delete(lp, id) + var po []any + for _, e := range anyStrings(s.state["project-order"]) { + if e != id { + po = append(po, e) + } + } + s.state["project-order"] = po +} + +func shareOnce(t *testing.T, home, rec string, want int, auths ...[]byte) { + t.Helper() + if n, err := shareCodexProjects(home, auths, rec); n != want || err != nil { + t.Fatalf("shared with %d (%v), want %d", n, err, want) + } +} + +func shows(t *testing.T, path string, who []byte, want ...string) *codexAppSim { + t.Helper() + app := codexAppLaunch(t, path) + app.signIn(who) + if got := app.projects(); !slices.Equal(got, want) { + t.Fatalf("%s's account shows %v, want %v", codexIdentityOf(who).user, got, want) + } + return app +} + +// Michael25651150 on X: projects are kept however accounts are switched. +// Every account shows every account's projects, even one that has a list +// of its own, and a folder added on two accounts is one project, its +// threads with it. +func TestCodexProjectsShared(t *testing.T) { home := t.TempDir() - a, b := codexTestAuth("user-a", "acct-a"), codexTestAuth("user-b", "acct-b") + rec := filepath.Join(t.TempDir(), "codex-projects.json") + a, b, c := codexTestAuth("user-a", "acct-a"), codexTestAuth("user-b", "acct-b"), codexTestAuth("user-c", "acct-c") path := codexStateFixture(t, home, a, b) app := codexAppLaunch(t, path) app.signIn(a) - app.signIn(b) - app.state["local-projects"] = map[string]any{} // b removed them all - app.save(t, path) + app.signIn(b) // a switch with the app open: b's own list + app.add("p-b", "/Users/me/b") + app.add("p-dup", "/Users/me/site/") // a's p-site, added again on b + app.state["thread-project-assignments"] = map[string]any{"t5": "p-b"} + app.save(t, path) // the app quit + + shareOnce(t, home, rec, 2, a, b, c) // a and c; b has them all + app = shows(t, path, a, "g-p-1", "p-b", "p-site") + if got := app.state["thread-project-assignments"].(map[string]any); got["t5"] != "p-b" || got["t1"] != "p-site" { + t.Fatalf("a's thread-project-assignments %v", got) + } + shows(t, path, b, "p-b", "p-dup") + app = shows(t, path, c, "p-b", "p-dup") + if got := app.state["thread-project-assignments"].(map[string]any); got["t1"] != "p-dup" || got["t5"] != "p-b" || len(got) != 2 { + t.Fatalf("c's thread-project-assignments %v: a's thread in site, under c's id for it", got) + } + // once more: nothing to do, nothing written before, _ := os.ReadFile(path) - if n, err := carryCodexProjects(home, [][]byte{a, b}); n != 0 || err != nil { - t.Fatalf("carried to %d (%v)", n, err) - } + shareOnce(t, home, rec, 0, a, b, c) if after, _ := os.ReadFile(path); string(after) != string(before) { - t.Fatal("the file was written with nothing to carry") + t.Fatal("the file was written with nothing to share") } - // c, new, gets a's parked projects - c := codexTestAuth("user-c", "acct-c") - if n, err := carryCodexProjects(home, [][]byte{a, b, c}); n != 1 || err != nil { - t.Fatalf("carried to %d (%v), want c", n, err) +} + +// A project the user removes on one account is removed from every +// account, not given back from another, and comes back only when the +// user adds it again. +func TestCodexProjectsRemovalRemembered(t *testing.T) { + home := t.TempDir() + rec := filepath.Join(t.TempDir(), "codex-projects.json") + a, b, c := codexTestAuth("user-a", "acct-a"), codexTestAuth("user-b", "acct-b"), codexTestAuth("user-c", "acct-c") + path := codexStateFixture(t, home, a, b) + shareOnce(t, home, rec, 2, a, b, c) + + app := codexAppLaunch(t, path) + app.signIn(a) + app.add("p-new", "/Users/me/new") // added on a + app.signIn(b) + if got := app.projects(); !slices.Equal(got, []string{"p-site"}) { + t.Fatalf("b shows %v", got) } + app.remove("p-site") // removed on b + app.save(t, path) + + shareOnce(t, home, rec, 3, a, b, c) + for range 2 { + app = shows(t, path, a, "g-p-1", "p-new") + if got := anyStrings(app.state["project-order"]); slices.Contains(got, "p-site") { + t.Fatalf("a's project-order %v", got) + } + if got := app.state["thread-project-assignments"].(map[string]any); got["t1"] != nil { + t.Fatalf("a's thread-project-assignments %v", got) + } + shows(t, path, b, "p-new") + shows(t, path, c, "p-new") + shareOnce(t, home, rec, 0, a, b, c) // and it stays gone + } + + // added again on c, under a new id: back on every account app = codexAppLaunch(t, path) app.signIn(c) - if got := app.projects(); !slices.Equal(got, []string{"p-site"}) { - t.Fatalf("c shows %v", got) + app.add("p-site2", "/Users/me/site") + app.save(t, path) + shareOnce(t, home, rec, 2, a, b, c) + shows(t, path, a, "g-p-1", "p-new", "p-site2") + shows(t, path, b, "p-new", "p-site2") +} + +// What was removed is unknown when magpie's record can't be read: the +// file isn't written then. +func TestCodexProjectsRecordUnreadable(t *testing.T) { + home := t.TempDir() + rec := filepath.Join(t.TempDir(), "codex-projects.json") + if err := os.WriteFile(rec, []byte(`{"identities":`), 0o600); err != nil { + t.Fatal(err) + } + a, b := codexTestAuth("user-a", "acct-a"), codexTestAuth("user-b", "acct-b") + path := codexStateFixture(t, home, a, b) + before, _ := os.ReadFile(path) + if n, err := shareCodexProjects(home, [][]byte{a, b}, rec); n != 0 || err == nil { + t.Fatalf("shared with %d (%v)", n, err) + } + if after, _ := os.ReadFile(path); string(after) != string(before) { + t.Fatal("written without knowing what was removed") } } @@ -252,11 +363,12 @@ func TestCodexProjectsUnknownFileLeft(t *testing.T) { "odd shape": `{"electron-account-renderer-state-v1":{"owner":1,"inactive":[]}}`, } { home := t.TempDir() + rec := filepath.Join(t.TempDir(), "codex-projects.json") path := codexGlobalStatePath(home) if err := os.WriteFile(path, []byte(body), 0o644); err != nil { t.Fatal(err) } - n, _ := carryCodexProjects(home, [][]byte{a, b}) + n, _ := shareCodexProjects(home, [][]byte{a, b}, rec) if got, _ := os.ReadFile(path); n != 0 || string(got) != body { t.Fatalf("%s: carried to %d, file %s", name, n, got) } @@ -264,7 +376,7 @@ func TestCodexProjectsUnknownFileLeft(t *testing.T) { t.Fatalf("%s: a backup written", name) } } - if n, err := carryCodexProjects(t.TempDir(), [][]byte{a}); n != 0 || err != nil { + if n, err := shareCodexProjects(t.TempDir(), [][]byte{a}, filepath.Join(t.TempDir(), "rec.json")); n != 0 || err != nil { t.Fatalf("no file: %d %v", n, err) } } @@ -314,6 +426,9 @@ func TestCodexProjectsStepWaitsForTheAppToClose(t *testing.T) { if got := app.projects(); !slices.Equal(got, []string{"p-site"}) { t.Fatalf("b, signed in now, shows %v once the app closed", got) } + if _, err := os.Stat(codexProjectsRecordPath()); err != nil { + t.Fatalf("no record of what each account has: %v", err) + } } func anyStrings(v any) []string {