Same email + different workspace login says 'Added account' but overwrites existing saved entry
Summary
When I add another account through codex-multi-auth login, the CLI reports Added account, but if the login is for a different workspace on the same email, the saved account count does not increase.
Instead, the existing saved entry for that email/account family appears to be refreshed or overwritten.
Actual behavior
I can reproduce this with multiple workspaces under the same email:
- Run
codex-multi-auth login - Choose
Open Browser (Easy)orManual / Incognito - Log into a different workspace using the same underlying email
- The CLI prints:
Added account. Total: 3
Next steps:
codex-multi-auth status
codex-multi-auth check
codex-multi-auth list
- After exiting the flow and running
codex-multi-auth status, the total is still3 - The newly added workspace did not become a separate saved slot; an existing entry appears to have been updated instead
Expected behavior
One of these should happen consistently:
- If workspace-scoped accounts are intended to be distinct, adding a different workspace on the same email should create a separate saved entry
- If same-email workspaces are intentionally merged, the login flow should not say
Added accountwhen it is actually updating/rebinding an existing saved entry
Right now the UX strongly suggests a new saved account was created, but local storage remains flat.
Local observations
On my machine, repeated browser logins for a different workspace on the same email updated existing saved identities instead of appending a new one.
The stored pool remained at 3 accounts even after successfully completing additional browser logins.
This seems related to deduplication/matching on save rather than a failed OAuth callback.
Why this is confusing
For users with:
- one email
- multiple ChatGPT/OpenAI workspaces
it looks like the tool supports adding another account/workspace, but the saved account count and final stored state do not reflect that mental model.
Suggested fix
At minimum, the login flow should distinguish between:
Added accountUpdated existing accountRebound workspace for existing account
If per-workspace saved entries are a supported goal, then same-email workspaces should be representable as distinct stored entries.
Environment
codex-multi-auth:2.2.2- Official Codex CLI in use through the multi-auth wrapper
- Reproduced on macOS
Additional context
I also observed that status and the dashboard can present slightly different-looking account ordering/state, which makes this even harder to understand during testing. The core bug here, though, is that the browser flow reports Added account while the stored account total does not increase for same-email different-workspace logins.
ndycode/codex-multi-auth#90 - fix: preserve business accounts that share a workspace accountId [merged]
ndycode/codex-multi-auth#122 - fix(quota): keep multi-workspace fallbacks distinct [merged]
ndycode/codex-multi-auth#132 - add manual login mode for headless auth flows [merged]
ndycode/codex-multi-auth#136 - feat: auto-rotate on disabled/expired workspace errors [merged]
ndycode/codex-multi-auth#493 - feat: support multiple workspaces for the same email (β οΈ Possible Duplicate Issue(s)
π Related PRs
#491) [merged]
π Issue Planner
Check the box below or use the @coderabbitai plan command to generate an implementation plan and prompts that you can use with your favorite coding assistant.
- [ ] Create Plan
π§ͺ Issue enrichment is currently in open beta.
To disable automatic issue enrichment, add the following to your .coderabbit.yaml:
issue_enrichment:
auto_enrich:
enabled: false
π¬ Have feedback or questions? Drop into our discord!
More real-world findings from testing on macOS:
- The small UX fix is valid:
- after patching locally, a same-email/same-workspace re-login now says
Updated existing account. Total: 3instead ofAdded account. Total: 3
- The deeper same-email multi-workspace path still does not work reliably in practice.
What I tested:
- normal browser flow
- manual/incognito flow
- explicit
login --org <org_id>flow - explicit
login --manual --org <org_id>flow
What still happens:
- no new distinct workspace becomes usable/saved
- stored account rows still have
workspaces: null workspace <account>is therefore unusable for the affected account
Important evidence:
~/.codex/auth.jsonfor the latest login contained two organizations in the token for the same email, e.g.:org-izb8024fENXhpMsfDt5A7gz3(Adithya workspace, default)org-r15LU9acpBzLqar9JQgqYqDH(Personal, non-default)
- but
~/.codex/multi-auth/openai-codex-accounts.jsonstill persisted the saved row without aworkspacesarray
That seems to contradict the intended #491 behavior:
- if one login returns both orgs, the account should persist tracked
workspaces - then
codex-multi-auth workspace <account>should handle switching
There is also a separate manual-mode UX bug:
codex-multi-auth login --manualcan printCancelled.after pasting a localhost callback URL- in code, the manual callback parser currently returns
nullfor parse/state mismatches, and the caller reports that asCancelled.instead of surfacing the real validation error
So I think there are actually 2 issues:
- same-email multi-workspace persistence/binding is still broken in some real accounts even when the token exposes multiple organizations
- manual callback entry misreports validation/state problems as
Cancelled.
If helpful, I can sanitize and attach the relevant auth.json / openai-codex-accounts.json snippets more formally.
One product/UX note from testing this in the real CLI:
Even if the intended post-#491 model is "one saved account row with multiple workspaces underneath it", that model is much harder to reason about in practice than a flat "one workspace = one row" model.
Why it feels confusing as a user:
- a new workspace does not show up like a new account entry
- routing is account-level, but workspace choice is nested under the account
- the user has to understand
workspace <account> <workspace>in addition toswitch <account> - when workspace persistence fails, the whole feature becomes hard to distinguish from "login just picked the wrong account"
From a user mental-model perspective, separate rows per workspace would be much easier to understand and debug, especially when different workspaces effectively represent different quota pools / identities for routing purposes.
Not saying the current nested-workspace model must be abandoned, but I wanted to call out that this design choice itself is contributing to the confusion here, independently of the persistence bug.
Both problems reported here are addressed in #513 (branched from and verified current with main).
1. "Added account" while the pool stayed flat + workspaces: null
Root cause: the codex-multi-auth login CLI used local copies of resolveAccountSelection / persistAccountPool in lib/codex-manager.ts that β unlike the workspace-aware versions added for #491 in lib/runtime/ (used only by the runtime proxy) β never populated/persisted workspaces and always printed Added account.
Fixed:
- workspaces are now surfaced from the token and persisted/merged (preserving per-workspace enabled/disabled state), so
workspace <account>is usable after login; - the flow reports
Added account/Updated existing account/Rebound workspace for existing accounthonestly, matching your suggested fix.
2. login --manual printing Cancelled. on a callback parse/state mismatch
Root cause: the manual-callback reader returned null for genuine cancel, malformed URL, and state mismatch alike, and the caller reported every null as Cancelled..
Fixed: the input is now classified code / cancelled / invalid / state-mismatch; validation failures surface a specific error (e.g. Login failed: OAuth state mismatchβ¦, exit 1) instead of Cancelled.. Genuine cancellation is unchanged.
Verification: full suite 4422 passed / 0 failing, including an end-to-end reproduction of the same-email multi-workspace scenario through the real dedup path, plus classifier coverage for the manual-callback case. typecheck and eslint clean.
Tracking via #513.
Coding Plan
Summary
- modify
persistAccountPoolatlib/codex-manager.ts:~2049to returnAccountPersistResult[]indicating insert vs update - update login flow at
lib/codex-manager.ts:3237to print "Added account" only on true inserts, "Updated existing account" otherwise - add regression tests for the new return value and messaging behavior
- defer workspace-scoped identity changes to a follow-up ticket; this fix addresses the ux confusion without changing storage semantics
Design Choices
Design Choice 1: should same-email different-workspace logins create separate stored entries or merge into one entry?
Options Considered:
- fix messaging only β keep current merge behavior, but distinguish "added" vs "updated" in cli output
- change identity key to include workspace/org β same-email different-workspace becomes separate stored accounts
- both β fix messaging now, add workspace-scoped entries later
Chosen Option: 1
Rationale: option 1: fix messaging only. this is the minimum viable fix the ticket requests ("at minimum... distinguish between added/updated"). changing identity semantics risks breaking existing storage and requires migration logic. can revisit workspace-scoped entries in a follow-up ticket.
π‘ User Tips
Regenerate the plan with different choices with @coderabbitai <feedback>.
Implementation Steps
Phase 1: Return Add/Update Status from Account Persistence
this phase makes persistAccountPool tell callers whether each account was newly inserted or updated in place.
Task 1: Define Persistence Result Type
introduce a result type that captures the outcome of each account persistence operation.
- add
AccountPersistResulttype inlib/codex-manager.tsor a newlib/types/account-persist.tswith fields:accountRef(email or accountId for identification),operation: "inserted" | "updated", optionalworkspacesChanged: boolean - keep it minimal β only what's needed to drive messaging
Task 2: Modify persistAccountPool to Track and Return Results
update the function to return an array of results instead of void.
- in
lib/codex-manager.ts:~2049, change signature fromPromise<void>toPromise<AccountPersistResult[]> - before the upsert loop, call
findMatchingAccountIndexand record whetherexistingIndex === undefined(insert) or not (update) - build result array with one entry per input account
- concurrency risk β if another process writes between match-check and persist, the result could be stale. acceptable for cli messaging purposes but flag in code comment.
Task 3: Update Callers of persistAccountPool
all call sites must handle the new return type.
- search for
persistAccountPool(calls inlib/codex-manager.tsandlib/runtime/account-pool.ts - most callers can ignore the result (assign to
_or void-cast) - the login flow caller at
lib/codex-manager.ts:~3230will use the result in phase 2
π€ Prompt for AI agents
this phase changes `persistAccountPool` at `lib/codex-manager.ts:2049` from
returning `Promise<void>` to `Promise<AccountPersistResult[]>` so callers can
distinguish inserts from updates.
- define `AccountPersistResult` type β either inline in `lib/codex-manager.ts`
or in a new `lib/types/account-persist.ts`. fields: `accountRef` (email or
accountId), `operation: "inserted" | "updated"`, optional `workspacesChanged:
boolean`. keep it minimal.
- in `lib/codex-manager.ts:~2049`, update the function signature from
`Promise<void>` to `Promise<AccountPersistResult[]>`
- before each upsert, call `findMatchingAccountIndex` and record whether
`existingIndex === undefined` (insert) or defined (update)
- build and return a result array with one `AccountPersistResult` entry per
input account
- add a code comment flagging the **concurrency risk**: another process writing
between match-check and persist could make the result stale β acceptable for cli
messaging but must be noted
- search all `persistAccountPool(` call sites in `lib/codex-manager.ts` and
`lib/runtime/account-pool.ts` β most callers can ignore the result via `_` or
void-cast. the login flow caller at `lib/codex-manager.ts:~3230` will be wired
up in phase 2.
Phase 2: Update Login Flow Messaging
this phase uses the persistence result to print accurate feedback.
Task 1: Replace Hardcoded "Added account" Message
change the unconditional message to reflect actual operation.
- at
lib/codex-manager.ts:3237, capture the result frompersistAccountPool - if
result[0].operation === "inserted", printAdded account. Total: ${count} - if
result[0].operation === "updated", printUpdated existing account. Total: ${count}(or similar) - consider a third variant for workspace-only changes if
workspacesChangedis tracked
Task 2: Handle Edge Cases in Multi-Account Batch Login
the login loop can add multiple accounts; each should get correct messaging.
- review the loop at
lib/codex-manager.ts:~3200-3260to ensure each iteration uses its own result - if batch persist is used (e.g.,
persistAccountPool([resolved1, resolved2], false)), iterate results and print per-account messages - windows edge case: ensure console output isn't garbled if multiple messages print in quick succession (not likely in interactive flow, but note it)
π€ Prompt for AI agents
this phase wires the `AccountPersistResult[]` returned from phase 1 into the
login flow at `lib/codex-manager.ts:3237` to replace the hardcoded "Added
account" message with accurate feedback.
- at `lib/codex-manager.ts:3237`, capture the return value from
`persistAccountPool`
- branch on `result[0].operation`:
- `"inserted"` β print `Added account. Total: ${count}`
- `"updated"` β print `Updated existing account. Total: ${count}` (or similar
wording)
- optionally handle a third variant if `workspacesChanged` is tracked on the
result
- review the login loop at `lib/codex-manager.ts:~3200-3260` β ensure each
iteration uses its own per-account result entry, not a shared reference
- if batch persist is used (e.g., `persistAccountPool([resolved1, resolved2],
false)`), iterate the results array and print one message per account
- flag **windows edge case**: note in a comment that rapid multi-message console
output in quick succession could interleave, though it is not likely in an
interactive flow
Phase 3: Add Regression Tests
no tests currently cover the add-vs-update message distinction. add explicit coverage.
Task 1: Unit Test persistAccountPool Return Value
verify the function returns correct operation status.
- add test file
test/persist-account-pool.test.tsor extendtest/accounts.test.ts - test case: persist new account β result is
{ operation: "inserted" } - test case: persist same account again β result is
{ operation: "updated" } - test case: persist same email, different accountId (if pool allows) β verify behavior matches current matching logic in
lib/storage.ts:1056-1080
Task 2: Integration Test for Login Flow Messaging
verify cli output changes based on operation type.
- if integration test harness exists, add scenario: login twice with same credentials, assert first prints "Added", second prints "Updated"
- if no harness, add manual test script in
scripts/or document in test file with skip annotation - flag: current test files
test/account-save.test.ts:83 linesandtest/account-save-entry.test.ts:25 linesdo not cover this β confirm no existing tests break
π€ Prompt for AI agents
this phase adds regression coverage for the new add-vs-update behavior. no
existing tests in `test/account-save.test.ts:83` or
`test/account-save-entry.test.ts:25` cover this β flag that explicitly.
- create `test/persist-account-pool.test.ts` or extend `test/accounts.test.ts`
with unit tests for `persistAccountPool`:
- persist a new account β assert result contains `{ operation: "inserted" }`
- persist the same account again β assert result contains `{ operation:
"updated" }`
- persist same email with a different accountId β assert behavior matches the
matching waterfall in `lib/storage.ts:1056-1080`
- add an integration test (or skip-annotated test with manual script in
`scripts/`) for the login flow:
- login twice with same credentials, assert first message prints "Added", second
prints "Updated"
- confirm existing tests in `test/account-save.test.ts` and
`test/account-save-entry.test.ts` still pass with no regressions
Research
account identity is keyed by accountId + email composite in lib/storage/identity.ts:61-76. the matching waterfall in lib/storage.ts:1056-1080 tries composite β safe-email β refresh-token β unique-accountId. workspace data lives on ManagedAccount.workspaces[] but is not part of the identity key. persistAccountPool at lib/codex-manager.ts:2049 returns Promise<void> with no add/update signal. the hardcoded message at lib/codex-manager.ts:3237 always fires regardless of whether the operation was an insert or update.
π Next Steps
π€ All AI agent prompts combined
Task: 1
this phase changes `persistAccountPool` at `lib/codex-manager.ts:2049` from
returning `Promise<void>` to `Promise<AccountPersistResult[]>` so callers can
distinguish inserts from updates.
- define `AccountPersistResult` type β either inline in `lib/codex-manager.ts`
or in a new `lib/types/account-persist.ts`. fields: `accountRef` (email or
accountId), `operation: "inserted" | "updated"`, optional `workspacesChanged:
boolean`. keep it minimal.
- in `lib/codex-manager.ts:~2049`, update the function signature from
`Promise<void>` to `Promise<AccountPersistResult[]>`
- before each upsert, call `findMatchingAccountIndex` and record whether
`existingIndex === undefined` (insert) or defined (update)
- build and return a result array with one `AccountPersistResult` entry per
input account
- add a code comment flagging the **concurrency risk**: another process writing
between match-check and persist could make the result stale β acceptable for cli
messaging but must be noted
- search all `persistAccountPool(` call sites in `lib/codex-manager.ts` and
`lib/runtime/account-pool.ts` β most callers can ignore the result via `_` or
void-cast. the login flow caller at `lib/codex-manager.ts:~3230` will be wired
up in phase 2.
===============================================================================
Task: 2
this phase wires the `AccountPersistResult[]` returned from phase 1 into the
login flow at `lib/codex-manager.ts:3237` to replace the hardcoded "Added
account" message with accurate feedback.
- at `lib/codex-manager.ts:3237`, capture the return value from
`persistAccountPool`
- branch on `result[0].operation`:
- `"inserted"` β print `Added account. Total: ${count}`
- `"updated"` β print `Updated existing account. Total: ${count}` (or similar
wording)
- optionally handle a third variant if `workspacesChanged` is tracked on the
result
- review the login loop at `lib/codex-manager.ts:~3200-3260` β ensure each
iteration uses its own per-account result entry, not a shared reference
- if batch persist is used (e.g., `persistAccountPool([resolved1, resolved2],
false)`), iterate the results array and print one message per account
- flag **windows edge case**: note in a comment that rapid multi-message console
output in quick succession could interleave, though it is not likely in an
interactive flow
===============================================================================
Task: 3
this phase adds regression coverage for the new add-vs-update behavior. no
existing tests in `test/account-save.test.ts:83` or
`test/account-save-entry.test.ts:25` cover this β flag that explicitly.
- create `test/persist-account-pool.test.ts` or extend `test/accounts.test.ts`
with unit tests for `persistAccountPool`:
- persist a new account β assert result contains `{ operation: "inserted" }`
- persist the same account again β assert result contains `{ operation:
"updated" }`
- persist same email with a different accountId β assert behavior matches the
matching waterfall in `lib/storage.ts:1056-1080`
- add an integration test (or skip-annotated test with manual script in
`scripts/`) for the login flow:
- login twice with same credentials, assert first message prints "Added", second
prints "Updated"
- confirm existing tests in `test/account-save.test.ts` and
`test/account-save-entry.test.ts` still pass with no regressions
π‘ Iterate on the plan with:
`@coderabbitai` <feedback>
Example Feedback
- `@coderabbitai` You can skip phase 3. Add a simple unit test case for phase 2.
- `@coderabbitai` For design choice 1 go ahead with option 3 and replan.
π¬ Have feedback or questions? Drop into our discord!
Fix is out in 2.3.0-beta.1. Give it a try and let me know if it actually solves it on your end:
npm i -g codex-multi-auth@beta
Then re-run your same-email multi-workspace login β you should now see Updated existing account / Rebound workspaceβ¦ instead of a misleading Added account, the saved row should keep its workspaces (no more null), and codex-multi-auth workspace <account> should work. login --manual will also show the real error now instead of Cancelled. on a bad callback URL.
Would appreciate confirmation from a real two-workspace account before I cut this to stable. π