Skip to content

fix(ai-vault): resume a bridged Codex session under the selected account's home - #11224

Merged
brennanb2025 merged 2 commits into
mainfrom
brennanb2025/vault-resume-selected-codex-account
Jul 28, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennanb2025/vault-resume-selected-codex-account

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

Problem

The Codex account session bridge (#10770) hardlinks every rollout into each per-account CODEX_HOME at the identical relative path, so the AI Vault sees the same physical rollout under several codex-accounts/<uuid>/home roots. Pre-parse dedup collapses those aliases by hardlink identity and — with both roots ranked equally — keeps the lexicographically smallest path (codex-session-root-dedup.ts:103). The surviving row's codexHome becomes an inline CODEX_HOME='…' prefix on the resume command, which overrides the pane's correctly-resolved env.

Net effect: with two or more managed accounts, Resume / Copy resume command / drag-drop resume can run a session under a peer account's auth.json and quota, decided by UUID sort order, silently. Nothing on the resume path corrected it — the existing preparation only covered the legacy shared home.

Fix (resume-time repin, no dedup changes)

At resume time, the owning host substitutes the selected account's home when it verifiably holds the same rollout at the same sessions-relative path (resolveSelectedAccountCodexHomeForResume in codex-legacy-session-resume.ts). Selected-account-over-path-order is the same product decision rankTrustedCodexHomesForRescan already documents for the pane-restore path — once a rollout sits in several homes, the path no longer names an account, and the selected account is what the user asked for.

Every uncertain branch declines and resume behaves exactly as today:

  • no account selected (system default), or selection equals the row's home
  • rollout not yet bridged into the selected home (the bridge is async)
  • transcript outside the dated rollout layout
  • non-local session (executionHostId gate on both requester and host)
  • older host (result field absent → clients no-op)

The result contract grows an optional substituteCodexHome; the runtime-RPC zod schema is extended so it is not silently stripped (zod drops unknown keys).

Surfaces

  • Copy resume command / Resume in tab: already awaited preparation; now apply the substitute home.
  • Drag & drop: the drag payload's prebuilt command pins the recorded home, so the drop layer now rebuilds the startup from a new optional sessionCwd payload field; payloads without it (older windows) fall back to the prebuilt command.
  • Mobile: gets the repin — the RPC executes on the serving desktop, which owns the account selection. Old desktops degrade cleanly (absent field / method-unavailable). prepareMobileAiVaultSessionResume moved to mobile/src/session/ai-vault-resume-preparation.ts (the launch file crossed the max-lines limit, which must not be bumped).
  • Out of scope, unchanged: dedup ranking and codexSessionRootRank; the pane-restore resolveVerifiedResumeHome path; runtime-hosted and SSH sessions.

Tests

Fail-first (verified red on origin/main 70c81c4b32, green here): two per-account homes with controlled UUIDs, a real rollout recorded under the larger UUID, a real hardlink bridged into the smaller at the identical relative path, run through the real dedupeCodexRolloutFileAliases in both discovery orders — the dedup pick is asserted (peer alias wins), then prepare must repin to the selected home:

× repins the surviving vault row to the selected account, discovered recorded rollout first
× repins the surviving vault row to the selected account, discovered bridged alias first
AssertionError: expected { useRealCodexHome: false } to deeply equal { useRealCodexHome: false, …(1) }
-   "substituteCodexHome": ".../codex-accounts/99999999-…/home"

Regression guards: selected == row home (single-account), system-default selection, unbridged rollout, non-local host, stray transcript layout, legacy materialization with a selection present, zod strip-catcher for the runtime result, renderer local/remote gating, drag payload round-trip, and 5 mobile preparation cases.

typecheck (fresh, tsbuildinfo removed), oxlint + both code-quality configs, max-lines ratchet, reliability gates: all green. ai-vault + codex suites: 1155 passed (3 unrelated load flakes — a benchmark budget and two app-server deadline tests — pass clean at --maxWorkers=2, no overlap with this change). Mobile suite (own vitest config): 34 passed.

…unt's home

The account session bridge hardlinks every rollout into each per-account
CODEX_HOME, and vault dedup keeps the lexicographically-smallest alias, so
Resume could pin an inline CODEX_HOME naming a peer account — running the
session under that account's auth.json and quota. At resume time the owning
host now substitutes the selected account's home when it holds the same
rollout at the same sessions-relative path, declining on any uncertainty so
resume degrades to today's behavior instead of failing.
Comment on lines +118 to +125
const candidatePath = join(selectedCodexHome, 'sessions', relativePath)
try {
const candidateStat = await lstat(candidatePath)
// Why: the bridge is async, so an unbridged rollout is a real state — decline rather than pin a home codex cannot resume from.
return candidateStat.isFile() && !candidateStat.isSymbolicLink() ? selectedCodexHome : null
} catch {
return null
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Existence check does not verify hardlink identity

resolveSelectedAccountCodexHomeForResume confirms that a file with the same sessions-relative path exists in the selected home, but it does not verify that the candidate is actually a hardlink of args.filePath (same dev/ino). The PR's stated invariant is "the selected account's home holds the same rollout," but the runtime check only confirms "some file with that name is there." UUID-based filenames make a false positive essentially impossible in practice, and the bridge exclusively creates hardlinks rather than copies, so the check is functionally correct today. But if a future code path (e.g., an export/import tool) could place a different file at the same relative path, the repin would silently redirect a session to the wrong account's home — the exact bug being fixed. Comparing dev/ino between lstat(args.filePath) and lstat(candidatePath) would make the "same rollout" invariant explicit and match how dedupeCodexRolloutFileAliases itself identifies aliases.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@greptile-apps

greptile-apps Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a multi-account Codex session resume bug: when two or more managed accounts exist, the AI Vault dedup step keeps the lexicographically-smallest hardlink alias, whose codexHome could belong to a peer account. All resume surfaces (sidebar, copy command, drag-drop, mobile) would then run the session under the wrong account's auth.json and quota.

The fix adds a resume-time repin step: at preparation time the owning host checks whether the currently-selected account's home contains the same rollout at the same sessions-relative path, and if so substitutes that home into the resume command. Every uncertain branch (no account selected, unbridged rollout, stale layout, non-local host) declines gracefully, so the behavior degrades to the pre-fix state rather than failing.

  • Shared contract (AiVaultPrepareSessionResumeResult) gains an optional substituteCodexHome; the runtime-RPC zod schema is extended so Zod does not silently strip it.
  • Drag-drop adds sessionCwd to the payload so the drop layer can rebuild a fresh command under the substituted home; payloads from older windows (absent key) surface a clear user-facing error instead of silently resuming under the peer's home.
  • Mobile preparation moved to a new file (ai-vault-resume-preparation.ts) to respect a max-lines limit, and extended to handle per-account sessions alongside the existing legacy-home path.

Confidence Score: 5/5

Safe to merge. All uncertain branches decline gracefully, the shared contract is backward-compatible, and the fix is guarded by real-hardlink integration tests that were verified red on origin/main.

The repin logic is tightly scoped to local per-account sessions, every early-return path leaves resume behavior unchanged from before the fix, and the new substituteCodexHome field is optional so older hosts degrade cleanly. Test coverage is thorough: fail-first integration tests with real hardlinks, round-trip drag payload tests, mobile preparation tests, and renderer gating tests all pass.

Files Needing Attention: mobile/src/session/ai-vault-resume-preparation.ts has a minor comment and fallback error message that still reference legacy in a code path now shared with per-account sessions.

Important Files Changed

Filename Overview
src/main/codex/codex-legacy-session-resume.ts Core repin logic added via resolveSelectedAccountCodexHomeForResume; early-returns cleanly for all non-per-account sessions; isLegacyRolloutRelativePath renamed to isDatedRolloutRelativePath and shared with the new path.
src/shared/ai-vault-resume-preparation.ts AiVaultPrepareSessionResumeResult extended with optional substituteCodexHome; new isPerAccountManagedCodexHome helper mirrors isLegacySharedCodexHome convention; backward-compatible (absent = keep own home).
src/renderer/src/lib/ai-vault-session-resume-preparation.ts Renderer preparation now handles per-account homes via aiVaultSessionNeedsResumePreparation; applies substituteCodexHome when returned; correctly gates per-account repin to local sessions only.
src/renderer/src/components/tab-group/AiVaultSessionDropLayer.tsx Drop path updated to call aiVaultSessionNeedsResumePreparation and invoke buildAiVaultDropRepinStartup when host signals a substitute home; correctly errors loudly when payload is from an older serializer lacking sessionCwd.
src/renderer/src/lib/ai-vault-resume-command.ts New buildAiVaultDropRepinStartup rebuilds a full startup from sessionCwd + substituteCodexHome; correctly declines (null) when sessionCwd is absent (older serializer), allowing the caller to surface a clear error.
src/renderer/src/lib/ai-vault-session-drag.ts sessionCwd added to drag payload type; round-trip serialization correctly distinguishes null (no cwd) from absent (old serializer); validation guard added to isSerializedPayload.
mobile/src/session/ai-vault-resume-preparation.ts New file splits prepareMobileAiVaultSessionResume out of the launch file; correctly handles both legacy and per-account sessions; minor inaccuracy in comment/fallback error message (see comment).
src/main/ai-vault/runtime-session-scanner.ts aiVaultPrepareSessionResumeResultSchema extended with substituteCodexHome to prevent zod from silently stripping the new field on the runtime host path.
src/main/index.ts Both prepareLegacySharedCodexSessionResume call sites wired with getSelectedHostAccountCodexHomePath; optional chaining ensures nil-safe fallback when codexRuntimeHome is absent.
src/renderer/src/components/right-sidebar/AiVaultSessionRow.tsx sessionCwd always written to drag payload (null when absent), enabling drop targets to distinguish 'no cwd' from 'old serializer' for the repin rebuild path.

Sequence Diagram

sequenceDiagram
    participant U as User
    participant R as Renderer
    participant M as Main Process
    participant FS as Filesystem

    Note over U,FS: Direct resume (sidebar / Copy resume command)
    U->>R: click Resume on peer-aliased session
    R->>R: aiVaultSessionNeedsResumePreparation()
    R->>M: "prepareSessionResume(agent, filePath, codexHome=peerHome, executionHostId)"
    M->>M: resolveSelectedAccountCodexHomeForResume()
    M->>FS: lstat(selectedHome/sessions/relativePath)
    FS-->>M: stat (file exists, is regular file)
    M-->>R: substituteCodexHome: selectedHome
    R->>R: "Build resume command with CODEX_HOME=selectedHome"

    Note over U,FS: Drag-drop resume
    U->>R: drag session (payload includes sessionCwd)
    U->>R: drop on pane
    R->>M: prepareSessionResume(...)
    M-->>R: substituteCodexHome: selectedHome
    R->>R: buildAiVaultDropRepinStartup()
    R->>R: Launch with rebuilt startup

    Note over U,FS: Mobile resume
    U->>R: tap Resume (mobile)
    R->>M: RPC aiVault.prepareSessionResume(...)
    M-->>R: substituteCodexHome: selectedHome
    R->>R: "session with codexHome=selectedHome"
Loading

Reviews (2): Last reviewed commit: "fix(ai-vault): repin dropped sessions wi..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds per-account Codex home detection and resume repinning across host, renderer, and mobile flows. Resume preparation results can now include a substitute Codex home, with runtime schema and shared types updated accordingly. Host logic validates compatible rollout files before selecting an account home. Renderer drag payloads preserve session working directories and use substituted homes during dropped-session startup. Mobile preparation moves into a dedicated module and handles legacy, per-account, unavailable, and error responses.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it does not follow the repository template and is missing required sections like Summary, Screenshots, AI Review Report, Security Audit, and Notes. Reformat the PR description to match the template and add the missing sections, including screenshots/status, testing checklist, AI review report, security audit, and notes.
Docstring Coverage ⚠️ Warning Docstring coverage is 8.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately describes the main change: resuming a bridged Codex session under the selected account's home.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

…ng under the wrong account

The drag payload only carried sessionCwd when session.cwd was truthy, so a
null-cwd codex session dropped onto a pane silently fell back to the prebuilt
command - which pins the wrong account's CODEX_HOME, the exact defect this PR
eliminates on the other resume surfaces.

- Serializer always sends sessionCwd (null when the session has no cwd), so
  absence now only means an older-serializer payload.
- The repin rebuild accepts a null cwd (the builders already omit the cd
  prefix), matching the sidebar Resume/Copy paths which repin regardless of cwd.
- An unrepinnable payload (absent sessionCwd) now fails loudly with guidance
  instead of silently resuming under the wrong account's home.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/renderer/src/lib/ai-vault-resume-command.drop-repin.test.ts (1)

84-93: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Cover the missing sessionFilePath branch.

The suite tests missing sessionCwd, but not the separate !args.payload.sessionFilePath rejection. Add a case with a valid sessionCwd and an absent sessionFilePath, asserting that the helper returns null.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b560788e-a021-4055-a7cc-ff7a6fa42320

📥 Commits

Reviewing files that changed from the base of the PR and between 191cfce and 7ba482f.

📒 Files selected for processing (6)
  • src/renderer/src/components/right-sidebar/AiVaultSessionRow.tsx
  • src/renderer/src/components/tab-group/AiVaultSessionDropLayer.tsx
  • src/renderer/src/lib/ai-vault-resume-command.drop-repin.test.ts
  • src/renderer/src/lib/ai-vault-resume-command.ts
  • src/renderer/src/lib/ai-vault-session-drag.test.ts
  • src/renderer/src/lib/ai-vault-session-drag.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/renderer/src/components/right-sidebar/AiVaultSessionRow.tsx
  • src/renderer/src/lib/ai-vault-session-drag.test.ts
  • src/renderer/src/components/tab-group/AiVaultSessionDropLayer.tsx
  • src/renderer/src/lib/ai-vault-session-drag.ts

@brennanb2025
brennanb2025 merged commit 50f4688 into main Jul 28, 2026
27 checks passed
zpyoung pushed a commit to zpyoung/orca that referenced this pull request Jul 29, 2026
…unt's home (stablyai#11224)

* fix(ai-vault): resume a bridged Codex session under the selected account's home

The account session bridge hardlinks every rollout into each per-account
CODEX_HOME, and vault dedup keeps the lexicographically-smallest alias, so
Resume could pin an inline CODEX_HOME naming a peer account — running the
session under that account's auth.json and quota. At resume time the owning
host now substitutes the selected account's home when it holds the same
rollout at the same sessions-relative path, declining on any uncertainty so
resume degrades to today's behavior instead of failing.

* fix(ai-vault): repin dropped sessions without a cwd instead of resuming under the wrong account

The drag payload only carried sessionCwd when session.cwd was truthy, so a
null-cwd codex session dropped onto a pane silently fell back to the prebuilt
command - which pins the wrong account's CODEX_HOME, the exact defect this PR
eliminates on the other resume surfaces.

- Serializer always sends sessionCwd (null when the session has no cwd), so
  absence now only means an older-serializer payload.
- The repin rebuild accepts a null cwd (the builders already omit the cd
  prefix), matching the sidebar Resume/Copy paths which repin regardless of cwd.
- An unrepinnable payload (absent sessionCwd) now fails loudly with guidance
  instead of silently resuming under the wrong account's home.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…unt's home (stablyai#11224)

* fix(ai-vault): resume a bridged Codex session under the selected account's home

The account session bridge hardlinks every rollout into each per-account
CODEX_HOME, and vault dedup keeps the lexicographically-smallest alias, so
Resume could pin an inline CODEX_HOME naming a peer account — running the
session under that account's auth.json and quota. At resume time the owning
host now substitutes the selected account's home when it holds the same
rollout at the same sessions-relative path, declining on any uncertainty so
resume degrades to today's behavior instead of failing.

* fix(ai-vault): repin dropped sessions without a cwd instead of resuming under the wrong account

The drag payload only carried sessionCwd when session.cwd was truthy, so a
null-cwd codex session dropped onto a pane silently fell back to the prebuilt
command - which pins the wrong account's CODEX_HOME, the exact defect this PR
eliminates on the other resume surfaces.

- Serializer always sends sessionCwd (null when the session has no cwd), so
  absence now only means an older-serializer payload.
- The repin rebuild accepts a null cwd (the builders already omit the cd
  prefix), matching the sidebar Resume/Copy paths which repin regardless of cwd.
- An unrepinnable payload (absent sessionCwd) now fails loudly with guidance
  instead of silently resuming under the wrong account's home.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant