Skip to content

fix(codex): keep persistent panes logged in after home routing - #11720

Merged
brennanb2025 merged 15 commits into
mainfrom
brennanb2025/fix-codex-login-screen
Aug 1, 2026
Merged

brennanb2025 merged 15 commits into
mainfrom
brennanb2025/fix-codex-login-screen

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Follow up on fix(codex): prevent transient managed-auth onboarding #11731 for the separate retained-PTY case: daemon-backed shells can survive an app restart with the legacy shared CODEX_HOME baked into their environment.
  • Refresh that retired shared home one-way from canonical system auth and config, with durable ownership provenance and guarded generation replacement so retained Codex writes win races.
  • Recover interrupted guarded auth operations before migration or sync, and fence ambiguous or concurrent credential generations instead of adopting them.
  • Record real/shared/per-account home routing for persistent panes so route changes use the existing restart prompt even when the account ID is unchanged.
  • Track only re-derivable process-wide custom-home overrides; pane-local, SSH, WSL, and folder-workspace contexts remain isolated.

Screenshots

No visual layout change. The existing restart prompt uses route-specific copy when the account is unchanged.

Testing

  • Full Node, CLI, and web typecheck
  • Native Oxlint
  • Type-aware Oxlint
  • Oxfmt check on all changed files
  • Max-lines ratchet
  • git diff --check
  • 713 focused Vitest tests across 17 files
  • CI shard 7/16: 250 files, 2,356 passed, 2 skipped
  • Added regression coverage for process-wide and pane-local overrides, managed-transition provenance, interrupted-operation recovery, and concurrent auth/config replacement

AI Review Report

An independent agent audited the final revision across auth ownership transitions, crash recovery, conditional replacement, custom-home provenance, restart prompting, Windows retries and ACLs, WSL isolation, SSH, and folder workspaces. Its final verdict was SHIP with no concrete correctness or regression findings.

Security Audit

  • Credential contents are copied only from canonical selected storage into Orca-managed storage, written with owner-only permissions, and never logged.
  • Ambiguous, malformed, interrupted, or concurrently replaced auth generations fail closed.
  • Compatibility config sync is one-way, so retained pane settings cannot overwrite canonical config.
  • Guarded writes publish atomically on supported local filesystems and fail before moving the canonical target when hard-link publication is unsupported.
  • No new command execution, dependency, network request, secret exposure, or renderer authority is introduced.

Landing order

Land after #11731. That PR handles transient managed-auth reads during startup; this PR handles persistent shells retaining the legacy shared home.

@greptile-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR adds compatibility infrastructure so daemon-backed PTY sessions that survived a real-home rollout continue to function correctly. It introduces durable provenance tracking for the shared runtime auth.json, guarded compare-and-swap file operations for atomic ownership transitions, and a route-aware restart prompt so panes with a stale baked CODEX_HOME are asked to restart even when the account ID hasn't changed.

  • Provenance-tracked auth writes: writeRuntimeAuth now records whether the shared home's auth.json is owned by the system-default user or a managed account, using a pending → committed two-phase write with hard-link CAS to survive crashes mid-transition.
  • Legacy shared-home compatibility sync: syncLegacySharedSystemDefaultAuthForRetainedPanes and syncSystemConfigIntoLegacySharedCodexHome refresh the retired shared runtime home one-way from canonical system auth/config, guarded by provenance and ownership checks so retained Codex writes win races.
  • Home-route tracking in the pane registry: CodexPaneAccountRecord gains homeRoute, shellStartupHomeOverride, and environmentHomeOverride; listStaleCodexPanes detects route changes and emits a distinct reason: 'home-route-change' pane, and the renderer shows route-specific copy in the restart chip when appropriate.

Confidence Score: 5/5

Safe to merge. The CAS, provenance tracking, and crash-recovery paths are carefully designed and well-tested; no correctness or data-loss paths were found.

The provenance two-phase write (pending → committed), hard-link CAS, and fenced-state logic all handle concurrent writes conservatively and correctly. Route tracking in the pane registry correctly degrades pane-local overrides to 'custom-home' to exclude them from route-change comparisons, and the A→B→A collapse suppression for homeRouteChanged notices is correctly gated. The one style observation (comma expression) has no behavioral impact.

Files Needing Attention: No files require special attention. runtime-home-service.ts is the most complex file in the diff but its provenance and CAS logic is covered by the 713 test cases cited in the PR description.

Important Files Changed

Filename Overview
src/main/codex-accounts/runtime-home-service.ts Core of this PR: adds provenance-tracked auth writes, guarded CAS logic, and syncLegacySharedSystemDefaultAuthForRetainedPanes. Very large and complex change; logic is carefully designed with correct two-phase pending→committed provenance updates and fencing on races.
src/main/codex-accounts/fs-utils.ts Adds writeFileAtomicallyIfUnchanged, removeFileAtomicallyIfUnchanged, and recoverInterruptedGuardedFileOperation using hard-link CAS with .orca-guarded staging. Crash recovery is sound; hard-link probe creation and cleanup looks correct.
src/main/codex/codex-pane-account-registry.ts Adds homeRoute, shellStartupHomeOverride, and environmentHomeOverride to pane records; bumps registry version to 2; adds hasRecordedLegacySharedCodexPane and reconcileCodexPaneAccountsWithLivePtys. Old-version records are correctly accepted without invented provenance.
src/main/codex/codex-real-home-path.ts Extracts getCustomCodexHomeOverrideForLaunch with source tagging (environment vs shell-startup) and adds equality helpers. CODEX_HOME! assertion in environment path is safe because hasCustomCodexHomeOverride only returns true when CODEX_HOME is non-empty.
src/main/codex/codex-stale-pane-accounts.ts Adds homeRouteChanged detection with activeHostHomeRoute param; correctly excludes custom-home and pre-route records from comparison; account-change takes precedence when both conditions fire simultaneously.
src/main/codex/codex-pane-launch-account.ts Wires homeRoute, shellStartupHomeOverride, and environmentHomeOverride into pane records; recordComparableHomeRoute logic correctly degrades pane-local overrides to 'custom-home' to exclude them from route-change comparison.
src/main/ipc/pty.ts Passes launchEnv to recordCodexPaneAccountForSpawn and classifies environment vs shell-startup overrides as recheckable only if they match the process-wide override. Non-recheckable (pane-local) overrides correctly suppress route comparison.
src/renderer/src/lib/codex-session-restart.ts Adds re-check of restored route-change notices via listStalePanes IPC before re-marking; correctly clears notices for panes that are no longer stale and converts route-change to account-change when main reports a different reason.
src/main/codex/codex-config-mirror.ts Adds syncSystemConfigIntoLegacySharedCodexHome using writeFileAtomicallyIfUnchanged so retained Codex trust writes win; one-way sync is deliberate to prevent retained pane settings from overwriting canonical config.
src/renderer/src/store/slices/terminals.ts Adds homeRouteChanged flag to CodexRestartNotice and preserves it correctly when re-marking; A→B→A collapse is correctly skipped for route-change notices; explicit homeRouteChanged: false re-enables collapse after re-check.
src/main/index.ts Adds post-daemon-init reconcileCodexPaneAccountsWithLivePtys to drop leaked records, then immediately calls reconcileLegacySharedHomeForRetainedPanes; graceful null guard when daemon inventory is unavailable.
src/renderer/src/components/CodexRestartChip.tsx Adds route-specific UI copy (header, body, dismiss label) gated on homeRouteChanged; uses correct i18n keys that are also added to en.json.

Sequence Diagram

sequenceDiagram
    participant PTY as Retained PTY (daemon-backed)
    participant RHS as CodexRuntimeHomeService
    participant FS as Filesystem (shared home)
    participant Prov as ProvenanceFile

    Note over PTY,Prov: On real-home pane spawn (flag ON, system-default)
    PTY->>RHS: prepareForCodexLaunch(launchEnv)
    RHS->>RHS: isHostSystemDefaultRealHome() → true
    RHS->>RHS: reconcileLegacySharedHomeForRetainedPanes()
    RHS->>Prov: resolveSharedRuntimeAuthProvenanceStatus()
    alt "provenance = managed"
        RHS->>RHS: restoreUntouchedSystemDefaultProvenance()
    end
    alt "provenance = system-default or missing"
        RHS->>FS: writeFileAtomicallyIfUnchanged(auth.json, expected, systemAuth)
        FS-->>RHS: replaced: boolean
        RHS->>Prov: persistSharedRuntimeAuthProvenance(committed/fenced)
    end
    RHS->>FS: syncSystemConfigIntoLegacySharedCodexHome()

    Note over PTY,Prov: Account switches managed to real-home
    PTY->>RHS: syncForCurrentSelection(target, launchEnv)
    RHS->>RHS: markSharedRuntimeAuthManaged(accountId)
    RHS->>Prov: write pending managed provenance
    RHS->>FS: "writeRuntimeAuth(managedAuth, owner=managed)"
    RHS->>Prov: write committed managed provenance

    Note over PTY,Prov: Renderer restart prompt lifecycle
    PTY->>PTY: markRestoredStaleCodexSessionsForRestart()
    PTY->>PTY: listStalePanes with activeHostHomeRoute
    PTY->>PTY: "reason = home-route-change or account-change"
    PTY->>PTY: CodexRestartChip shows route-specific copy
Loading

Reviews (3): Last reviewed commit: "fix(codex): seed pane override fallbacks" | Re-trigger Greptile

Comment on lines +41 to +48
accountId: getSelectedCodexAccountIdForTarget(args.settings, args.target),
...(homeRoute ? { homeRoute } : {})
}
}
const accountId = resolveCodexHomeOwnerAccountId(args)
return accountId === undefined ? null : { selectionKey, accountId }
return accountId === undefined
? null
: { selectionKey, accountId, ...(homeRoute ? { homeRoute } : {}) }

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 The spread uses truthiness (homeRoute ?) rather than an explicit homeRoute !== undefined check. All current CodexPaneHomeRoute values are non-empty strings so this is correct today, but a future empty-string route literal would be silently dropped even when intentionally set. Explicit undefined-check matches the stated intent ("omit when not computed") more precisely.

Suggested change
accountId: getSelectedCodexAccountIdForTarget(args.settings, args.target),
...(homeRoute ? { homeRoute } : {})
}
}
const accountId = resolveCodexHomeOwnerAccountId(args)
return accountId === undefined ? null : { selectionKey, accountId }
return accountId === undefined
? null
: { selectionKey, accountId, ...(homeRoute ? { homeRoute } : {}) }
accountId: getSelectedCodexAccountIdForTarget(args.settings, args.target),
...(homeRoute !== undefined ? { homeRoute } : {})
}
}
const accountId = resolveCodexHomeOwnerAccountId(args)
return accountId === undefined
? null
: { selectionKey, accountId, ...(homeRoute !== undefined ? { homeRoute } : {}) }

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!

@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds Codex home-route provenance and custom-home override tracking across launch resolution, pane records, PTY attribution, and stale-pane detection. Runtime authentication now persists ownership and pending-operation provenance, performs guarded compare-and-swap updates, and recovers interrupted operations. Legacy shared-home configuration synchronization preserves runtime changes. Renderer restart notices distinguish home-route changes from account changes and retain route-specific notices.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 35.90% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: keeping persistent Codex panes logged in after home-routing changes.
Description check ✅ Passed The description covers the summary, screenshots, testing, AI review, security audit, and landing order with detailed implementation and risk information.
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 💡 1
📝 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.

@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.

Actionable comments posted: 4

🧹 Nitpick comments (6)
src/main/codex-accounts/fs-utils.ts (1)

49-57: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Unguarded grantDirAcl calls replace the original Windows permission error. Both new retry paths call grantDirAcl outside a try/catch. If icacls fails, callers receive an opaque icacls error instead of the EPERM or EACCES that triggered the repair. writeFileAtomically already handles this correctly at Lines 35-37.

  • src/main/codex-accounts/fs-utils.ts#L49-L57: wrap the grantDirAcl(dirname(targetPath)) call in writeFileAtomicallyIfUnchanged and rethrow the caught error when it fails.
  • src/main/codex-accounts/fs-utils.ts#L172-L176: wrap the grantDirAcl(dirname(targetPath)) call in publishFileWithoutOverwrite and rethrow the original error when it fails.
src/main/codex-accounts/fs-utils.test.ts (1)

193-206: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a case for a target that is already absent.

removeFileAtomicallyIfUnchanged documents an ENOENT result as false (fs-utils.ts Lines 70-72), but no test covers it. That case is also where the hard-link probe ordering defect appears.

💚 Proposed test
       expect(removeFileAtomicallyIfUnchanged(target, 'baseline')).toBe(true)
       expect(existsSync(target)).toBe(false)
+      expect(removeFileAtomicallyIfUnchanged(target, 'baseline')).toBe(false)
     } finally {
src/main/codex-accounts/runtime-home-service.test.ts (3)

1208-1222: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the repeated managed-account fixture.

Lines 1208-1222, 1255-1269, 1293-1307, and 1358-1372 repeat the same managed-account literal with only id, email, and the account identifiers changed. A small factory beside createSettings would remove the duplication and keep new cases short.

♻️ Proposed helper
function createManagedAccountSettings(args: {
  id: string
  email: string
  managedHomePath: string
  providerAccountId: string
}): GlobalSettings {
  return createSettings({
    codexManagedAccounts: [
      {
        ...args,
        workspaceLabel: null,
        workspaceAccountId: args.providerAccountId,
        createdAt: 1,
        updatedAt: 1,
        lastAuthenticatedAt: 1
      }
    ]
  })
}

1381-1384: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use getSharedRuntimeAuthProvenancePath() here.

This block rebuilds the provenance path inline. The helper added at Lines 204-206 already returns it, and the other new tests use the helper.

♻️ Proposed change
     writeFileSync(
-      join(testState.userDataDir, 'codex-runtime-home', 'shared-runtime-auth-provenance.json'),
+      getSharedRuntimeAuthProvenancePath(),
       `${JSON.stringify({ owner: 'system-default', authJson: systemAuth })}\n`
     )

1477-1498: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

This case injects the pending record instead of producing one.

The test writes a pending record directly, so it verifies the fence but not the code path that creates a leaked pending record. Add a case where writeRuntimeAuth loses the compare-and-swap, then assert the resulting provenance state. That case would pin down the behavior questioned in runtime-home-service.ts Lines 1811-1830.

src/main/codex/codex-stale-pane-accounts.ts (1)

67-110: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document the hasOwnProperty distinction.

getCustomHomeChanged and customHomeOverrideChanged both use Object.prototype.hasOwnProperty.call(args, 'activeHostCustomHomeOverride') to distinguish "caller omitted the argument" (legacy path, reads process.env) from "caller explicitly passed a value, including null" (compares against the supplied value). This distinction is not obvious from the code and the string key is repeated with no compile-time check against a typo.

Add a short comment at the first hasOwnProperty check explaining why an omitted argument takes a different path from an explicit null. Optionally extract the check into one named helper so both call sites share the exact same key.

As per coding guidelines, **/*.{ts,tsx,js,jsx} requires "Comments must be concise, limited to non-obvious information, and preferably one line," which supports adding this clarification.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: fb8f77bf-90e1-4642-af11-3aadc4c6d599

📥 Commits

Reviewing files that changed from the base of the PR and between 6966da1 and 051f8d3.

📒 Files selected for processing (26)
  • src/main/codex-accounts/fs-utils.test.ts
  • src/main/codex-accounts/fs-utils.ts
  • src/main/codex-accounts/legacy-shared-config-compatibility.test.ts
  • src/main/codex-accounts/legacy-shared-config-compatibility.ts
  • src/main/codex-accounts/runtime-home-service.test.ts
  • src/main/codex-accounts/runtime-home-service.ts
  • src/main/codex/codex-config-mirror.ts
  • src/main/codex/codex-pane-account-registry.ts
  • src/main/codex/codex-pane-launch-account.ts
  • src/main/codex/codex-real-home-path.test.ts
  • src/main/codex/codex-real-home-path.ts
  • src/main/codex/codex-stale-pane-accounts.test.ts
  • src/main/codex/codex-stale-pane-accounts.ts
  • src/main/ipc/codex-accounts.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/CodexRestartChip.tsx
  • src/renderer/src/components/codex-restart-chip.test.ts
  • src/renderer/src/components/codex-restart-notice-key.test.ts
  • src/renderer/src/components/codex-restart-notice-key.ts
  • src/renderer/src/lib/codex-session-restart.test.ts
  • src/renderer/src/lib/codex-session-restart.ts
  • src/renderer/src/store/slices/codex-restart-notice-lifecycle.test.ts
  • src/renderer/src/store/slices/terminals.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/main/ipc/codex-accounts.ts
  • src/main/codex/codex-config-mirror.ts
  • src/main/codex/codex-pane-launch-account.ts
  • src/main/ipc/pty.ts

Comment on lines +64 to +74
const heldPath = getGuardedOperationHeldPath(targetPath)
recoverInterruptedGuardedOperation(heldPath, targetPath)
assertHardLinkPublicationSupported(targetPath, targetPath)
try {
renameFileWithWindowsRetry(targetPath, heldPath)
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return false
}
throw error
}

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

The hard-link probe makes the missing-target path throw instead of returning false.

Line 66 probes with targetPath as the link source. If targetPath does not exist, linkSync fails with ENOENT. publishFileWithoutOverwrite rethrows that code, so removeFileAtomicallyIfUnchanged throws before the rename runs. The ENOENT branch at Lines 70-72, which exists to report "target already gone", becomes unreachable.

runtime-home-service.ts Line 1687 calls this after an existsSync check, so a retained Codex process that deletes auth.json inside that window turns an expected false into a logged failure and skips the provenance update.

Skip the probe when the target is absent, or run the probe after the rename using heldPath as the source.

🐛 Proposed fix
   const heldPath = getGuardedOperationHeldPath(targetPath)
   recoverInterruptedGuardedOperation(heldPath, targetPath)
+  if (!existsSync(targetPath)) {
+    return false
+  }
   assertHardLinkPublicationSupported(targetPath, targetPath)

Comment on lines +43 to +50
it('captures explicit environment provenance for restart comparison', () => {
const codexHome = join(process.cwd(), 'custom-codex-home')

expect(getCustomCodexHomeOverrideForLaunch({ CODEX_HOME: codexHome })).toEqual({
source: 'environment',
context: { codexHome }
})
})

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Tests depend on ambient process.env for CODEX_HOME/ORCA_CODEX_HOME.

Both new tests omit CODEX_HOME/ORCA_CODEX_HOME from the passed launchEnv object. getLaunchEnvValue falls back to process.env[key] whenever the key is absent from launchEnv. At line 46, getCustomCodexHomeOverrideForLaunch({ CODEX_HOME: codexHome }) implicitly resolves ORCA_CODEX_HOME from the real process.env.ORCA_CODEX_HOME. At line 59, hasCustomCodexHomeOverrideForLaunch({ HOME: paneHome, SHELL: '/bin/zsh' }) implicitly resolves CODEX_HOME and ORCA_CODEX_HOME from real process.env.

If the test runner's ambient environment happens to already export CODEX_HOME or ORCA_CODEX_HOME (for example when tests execute inside a Codex-managed terminal), these tests can pass or fail depending on the host environment rather than the code under test. Pass explicit values for all four keys, matching the pattern already used in pty.test.ts (CODEX_HOME: '', ORCA_CODEX_HOME: '').

🧪 Proposed fix for explicit env isolation
   it('captures explicit environment provenance for restart comparison', () => {
     const codexHome = join(process.cwd(), 'custom-codex-home')

-    expect(getCustomCodexHomeOverrideForLaunch({ CODEX_HOME: codexHome })).toEqual({
+    expect(
+      getCustomCodexHomeOverrideForLaunch({ CODEX_HOME: codexHome, ORCA_CODEX_HOME: '' })
+    ).toEqual({
       source: 'environment',
       context: { codexHome }
     })
   })
-      expect(hasCustomCodexHomeOverrideForLaunch({ HOME: paneHome, SHELL: '/bin/zsh' })).toBe(true)
-      const override = getCustomCodexHomeOverrideForLaunch({
-        HOME: paneHome,
-        SHELL: '/bin/zsh'
-      })
+      expect(
+        hasCustomCodexHomeOverrideForLaunch({
+          CODEX_HOME: '',
+          ORCA_CODEX_HOME: '',
+          HOME: paneHome,
+          SHELL: '/bin/zsh'
+        })
+      ).toBe(true)
+      const override = getCustomCodexHomeOverrideForLaunch({
+        CODEX_HOME: '',
+        ORCA_CODEX_HOME: '',
+        HOME: paneHome,
+        SHELL: '/bin/zsh'
+      })

Also applies to: 52-77

Comment on lines +78 to +95
export function shellStartupCodexHomeOverrideMatches(
context: CodexShellStartupHomeOverride,
currentContext: CodexShellStartupHomeOverride = context
): boolean {
if (!shellStartupCodexHomeOverrideContextsEqual(context, currentContext)) {
return false
}
const currentCodexHome = readShellStartupEnvVar(
'CODEX_HOME',
currentContext.home,
currentContext.shell
)
return Boolean(
currentCodexHome &&
hasCustomCodexHomeOverride({ CODEX_HOME: currentCodexHome }) &&
normalizePathForComparison(currentCodexHome) === normalizePathForComparison(context.codexHome)
)
}

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
# Inspect the full shell-startup-env.ts cache implementation for any invalidation logic
# (e.g., mtime checks) not shown in the provided context.
cat -n src/main/pty/shell-startup-env.ts
rg -n 'cache' src/main/pty/shell-startup-env.ts -C3
rg -n 'shellStartupCodexHomeOverrideMatches|__resetShellStartupEnvCache' --type=ts -C3

Repository: stablyai/orca

Length of output: 9419


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the reported file and related calls in codex-real-home-path.ts without executing repository code.
cat -n src/main/codex/codex-real-home-path.ts | sed -n '1,140p'

# Locate related invocations/import points to confirm cache usage path and whether callers reset cache around rechecks.
rg -n 'shellStartupCodexHomeOverrideMatches|getCustomCodexHomeOverrideForLaunch|readShellStartupEnvVar|__resetShellStartupEnvCache|ShellStartupEnv' src/main -C 2

Repository: stablyai/orca

Length of output: 33129


Avoid memoizing shell-startup env reads beyond initial lookup or cache the startup files behind a stale-file check.

readShellStartupEnvVar stores values for the process lifetime in src/main/pty/shell-startup-env.ts, and production call sites do not invalidate it. shellStartupCodexHomeOverrideMatches will compare against that first-panes value, and getCustomCodexHomeOverrideForLaunch will reuse it for later shell-startup overrides, so edited shell startup files after initial detection are not picked up.

@brennanb2025
brennanb2025 force-pushed the brennanb2025/fix-codex-login-screen branch from 1394036 to 4f6d50a Compare August 1, 2026 01:15

@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.

Actionable comments posted: 2

🧹 Nitpick comments (7)
src/main/startup/desktop-startup-ordering.test.ts (1)

105-117: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Assert that the live inventory is consumed before home reconciliation.

The test anchors on await listLiveDaemonPtyIds() but does not assert reconcileCodexPaneAccountsWithLivePtys(livePtyIds). If that call is removed or moved after reconcileLegacySharedHomeForRetainedPanes(), this test still passes. Add an index assertion that places the inventory reconciliation between inventoryIndex and reconciliationIndex.

Proposed assertion
     const inventoryIndex = source.indexOf('await listLiveDaemonPtyIds()', daemonInitIndex)
+    const livePtyReconciliationIndex = source.indexOf(
+      'reconcileCodexPaneAccountsWithLivePtys(livePtyIds)',
+      inventoryIndex
+    )
     const reconciliation = 'codexRuntimeHome?.reconcileLegacySharedHomeForRetainedPanes()'
     const reconciliationIndex = source.indexOf(reconciliation, inventoryIndex)
...
     expect(inventoryIndex).toBeGreaterThan(routeGateIndex)
+    expect(livePtyReconciliationIndex).toBeGreaterThan(inventoryIndex)
     expect(reconciliationIndex).toBeGreaterThan(inventoryIndex)
+    expect(reconciliationIndex).toBeGreaterThan(livePtyReconciliationIndex)
src/main/codex/codex-stale-pane-accounts.test.ts (1)

333-365: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

These two tests assert the same behavior with the same inputs.

Both records use homeRoute: 'shared-home' with an environmentHomeOverride.codexHome value, and both calls pass activeHostHomeRoute: 'shared-home'. Only the override string differs, and listStaleCodexPanes never reads environmentHomeOverride. The first title also promises a "spelling change" that the test never applies. Merge them into one case, or change one case so the recorded override and the active route actually diverge.

src/main/codex/codex-stale-pane-accounts.ts (1)

35-48: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Document why custom-home never counts as a route change.

The record.homeRoute !== 'custom-home' guard encodes a policy decision: a pane-local CODEX_HOME is not comparable with the selected host route. That intent is not derivable from the code. Add one short Why: line, matching the comment style already used in parseSelectionLaneKey.

♻️ Proposed comment
+    // Why: a pane-local custom CODEX_HOME is not comparable with the host route.
     const homeRouteChanged =
       record.selectionKey === 'host' &&
src/main/daemon/daemon-init.ts (1)

845-847: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Log the rejected inventory before returning null.

The rejection reason is discarded here, and the caller in src/main/index.ts silently skips reconciliation. A permanently failing adapter then leaks pane records with no diagnostic trail. Other daemon inventory paths already warn on failure.

♻️ Proposed change
-  if (inventories.some((inventory) => inventory.status === 'rejected')) {
-    return null
-  }
+  const rejected = inventories.filter(
+    (inventory): inventory is PromiseRejectedResult => inventory.status === 'rejected'
+  )
+  if (rejected.length > 0) {
+    console.warn('[daemon] Failed to list live daemon PTYs', rejected[0].reason)
+    return null
+  }
src/main/codex-accounts/runtime-home-service.test.ts (3)

1321-1323: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Document why the reconciliation needs two polls.

Several new tests call prepareForRateLimitFetch() twice and only assert after the second call (also at Lines 1367-1369 and Lines 1745-1747). A reader cannot tell whether the second call is required by the reconciliation contract or is incidental. Add a one-line comment that states the first poll fences or records provenance and the second poll applies it.


1503-1506: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use the new provenance-path helper here.

This block rebuilds the provenance path literally. getSharedRuntimeAuthProvenancePath() was added at Lines 205-207 for this purpose. The literal will drift if the filename changes.

♻️ Proposed change
     writeFileSync(
-      join(testState.userDataDir, 'codex-runtime-home', 'shared-runtime-auth-provenance.json'),
+      getSharedRuntimeAuthProvenancePath(),
       `${JSON.stringify({ owner: 'system-default', authJson: systemAuth })}\n`
     )

1435-1442: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use a precise file-identity check on Windows.

Windows exposes a 64-bit file index. Use statSync(provenancePath, { bigint: true }).ino so distinct file IDs cannot be rounded to the same JavaScript number.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4b63962a-e886-4260-9437-8ff4fb66bbba

📥 Commits

Reviewing files that changed from the base of the PR and between 051f8d3 and 4f6d50a.

📒 Files selected for processing (27)
  • src/main/codex-accounts/fs-utils.test.ts
  • src/main/codex-accounts/fs-utils.ts
  • src/main/codex-accounts/legacy-shared-config-compatibility.test.ts
  • src/main/codex-accounts/legacy-shared-config-compatibility.ts
  • src/main/codex-accounts/runtime-home-service.test.ts
  • src/main/codex-accounts/runtime-home-service.ts
  • src/main/codex/codex-config-mirror.test.ts
  • src/main/codex/codex-config-mirror.ts
  • src/main/codex/codex-pane-account-registry.ts
  • src/main/codex/codex-pane-launch-account.test.ts
  • src/main/codex/codex-pane-launch-account.ts
  • src/main/codex/codex-real-home-path.test.ts
  • src/main/codex/codex-real-home-path.ts
  • src/main/codex/codex-stale-pane-accounts.test.ts
  • src/main/codex/codex-stale-pane-accounts.ts
  • src/main/daemon/daemon-init.ts
  • src/main/index.ts
  • src/main/ipc/codex-accounts.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/startup/desktop-startup-ordering.test.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/CodexRestartChip.tsx
  • src/renderer/src/components/codex-restart-chip.test.ts
  • src/renderer/src/components/codex-restart-notice-key.test.ts
  • src/renderer/src/components/codex-restart-notice-key.ts
🚧 Files skipped from review as they are similar to previous changes (18)
  • src/renderer/src/components/CodexRestartChip.tsx
  • src/main/codex/codex-real-home-path.ts
  • src/main/codex/codex-pane-launch-account.test.ts
  • src/main/codex/codex-pane-launch-account.ts
  • src/main/codex-accounts/fs-utils.ts
  • src/main/codex-accounts/fs-utils.test.ts
  • src/main/codex/codex-config-mirror.ts
  • src/main/codex/codex-pane-account-registry.ts
  • src/renderer/src/components/codex-restart-chip.test.ts
  • src/main/codex-accounts/runtime-home-service.ts
  • src/renderer/src/components/codex-restart-notice-key.ts
  • src/main/codex/codex-real-home-path.test.ts
  • src/renderer/src/components/codex-restart-notice-key.test.ts
  • src/main/codex-accounts/legacy-shared-config-compatibility.ts
  • src/main/ipc/pty.ts
  • src/preload/api-types.ts
  • src/main/codex-accounts/legacy-shared-config-compatibility.test.ts
  • src/preload/index.ts

Comment on lines +391 to +435
it.skipIf(process.platform === 'win32')(
'reports a retained pane after its shell startup CODEX_HOME is removed',
() => {
const paneHome = join(userDataPath, 'pane-home')
mkdirSync(paneHome, { recursive: true })
const startupPath = join(paneHome, '.zshrc')
const customHome = join(paneHome, 'custom-codex-home')
writeFileSync(startupPath, 'export CODEX_HOME="$HOME/custom-codex-home"\n')
recordCodexPaneAccount('pty-1', {
selectionKey: 'host',
accountId: null,
homeRoute: 'shared-home',
shellStartupHomeOverride: {
home: paneHome,
shell: '/bin/zsh',
codexHome: customHome
}
})

expect(
listStaleCodexPanes({
ptyIds: ['pty-1'],
settings: settingsWithSelection(null),
activeHostHomeRoute: 'shared-home'
})
).toEqual([])

writeFileSync(startupPath, '')
__resetShellStartupEnvCache()
expect(
listStaleCodexPanes({
ptyIds: ['pty-1'],
settings: settingsWithSelection(null),
activeHostHomeRoute: 'real-home'
})
).toEqual([
{
ptyId: 'pty-1',
launchAccountId: null,
activeAccountId: null,
reason: 'home-route-change'
}
])
}
)

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
echo "--- listStaleCodexPanes implementation ---"
ast-grep run --pattern 'export function listStaleCodexPanes($$$) { $$$ }' --lang typescript src/main/codex/codex-stale-pane-accounts.ts
echo "--- any shell startup override reads in stale detection ---"
rg -n 'shellStartupHomeOverride|shell-startup-env|environmentHomeOverride' src/main/codex src/main/pty -S

Repository: stablyai/orca

Length of output: 194


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "--- candidate files ---"
git ls-files 'src/main/codex/*' 'src/main/pty/*' | sed -n '1,120p'

echo "--- stale-pane symbols and relevant fields ---"
rg -n -C 5 'listStaleCodexPanes|recordCodexPaneAccount|shellStartupHomeOverride|__resetShellStartupEnvCache|activeHostHomeRoute|homeRoute' \
  src/main/codex src/main/pty -S || true

echo "--- implementation outline ---"
ast-grep outline src/main/codex/codex-stale-pane-accounts.ts

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "--- stale-pane implementation ---"
cat -n src/main/codex/codex-stale-pane-accounts.ts | sed -n '1,130p'

echo "--- relevant test ---"
cat -n src/main/codex/codex-stale-pane-accounts.test.ts | sed -n '340,455p'

echo "--- home-route resolution and shell-startup matching ---"
rg -n -C 8 'shellStartupCodexHomeOverrideMatches|getCustomCodexHomeOverrideForLaunch|activeHostHomeRoute|listStaleCodexPanes' \
  src/main/codex src/main -g '*.ts' -S | sed -n '1,260p'

Repository: stablyai/orca

Length of output: 27813


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "--- all stale-pane call sites ---"
rg -n -C 12 'listStaleCodexPanes\(' src -g '*.ts' -S

echo "--- all override comparison call sites ---"
rg -n -C 12 'shellStartupCodexHomeOverrideMatches|environmentCodexHomeOverrideContextsEqual|shellStartupHomeOverride' \
  src/main -g '*.ts' -S | sed -n '1,320p'

echo "--- route and override types ---"
cat -n src/main/codex/codex-real-home-path.ts | sed -n '1,125p'
cat -n src/main/codex/codex-pane-account-registry.ts | sed -n '1,225p'

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "--- runtime host route service ---"
rg -n -C 14 'getSelectedHostCodexHomeRoute|selectedHostCodexHomeRoute|CodexHomeRoute' \
  src/main/codex src/main/codex-accounts src/main -g '*.ts' -S | sed -n '1,300p'

echo "--- PTY recording and launch provenance ---"
rg -n -C 18 'resolveCodexPaneLaunchAccount|recordCodexPaneAccount|getCustomCodexHomeOverrideForLaunch|shellStartupCodexHomeOverrideContextsEqual' \
  src/main/ipc/pty.ts -S | sed -n '1,360p'

echo "--- complete shell-startup comparison implementation ---"
cat -n src/main/codex/codex-real-home-path.ts | sed -n '70,115p'

Repository: stablyai/orca

Length of output: 27694


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path

source = Path("src/main/codex/codex-stale-pane-accounts.ts").read_text()
body = source[source.index("export function listStaleCodexPanes"):source.index("\n}\n\n/**", source.index("export function listStaleCodexPanes"))]

assert "shellStartupHomeOverride" not in body
assert "environmentHomeOverride" not in body

def stale(record, active_route):
    active_account = None
    route_changed = (
        record["selectionKey"] == "host"
        and record.get("homeRoute") is not None
        and record["homeRoute"] != "custom-home"
        and active_route is not None
        and record["homeRoute"] != active_route
    )
    account_changed = record["accountId"] != active_account
    return account_changed or route_changed

base = {
    "selectionKey": "host",
    "accountId": None,
    "homeRoute": "shared-home",
}
with_override = {
    **base,
    "shellStartupHomeOverride": {
        "home": "/pane-home",
        "shell": "/bin/zsh",
        "codexHome": "/pane-home/custom-codex-home",
    },
}
assert stale(base, "shared-home") == stale(with_override, "shared-home") == False
assert stale(base, "real-home") == stale(with_override, "real-home") == True
print("The fixture fields are absent from listStaleCodexPanes and do not change either assertion result.")
PY

Repository: stablyai/orca

Length of output: 249


Make this test exercise shell-startup CODEX_HOME removal. listStaleCodexPanes only compares record.homeRoute with activeHostHomeRoute; it does not inspect record.shellStartupHomeOverride. Both assertions pass when the shell-startup fixture is removed. Add the override check or remove the fixture and rename the test.

Comment on lines +838 to +844
const adapters =
adapter instanceof DaemonPtyRouter || adapter instanceof DegradedDaemonPtyProvider
? adapter.getAllAdapters()
: [adapter]
const inventories = await Promise.allSettled(
adapters.map((daemonAdapter) => daemonAdapter.listProcesses())
)

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
echo "--- getAllAdapters declarations ---"
rg -nP '\b(getAllAdapters|allAdapters|allDaemonAdapters)\s*\(' src/main/daemon -S
echo "--- listProcesses implementations and timeout handling ---"
rg -nP -C 8 '\blistProcesses\s*\(' src/main/daemon -S | rg -n -C 4 'timeout|deadline|AbortSignal|setTimeout|race' -S || true

Repository: stablyai/orca

Length of output: 7446


🏁 Script executed:

#!/bin/bash
set -euo pipefail
echo "--- daemon-init call site ---"
sed -n '790,855p' src/main/daemon/daemon-init.ts
echo "--- startup service and listLiveDaemonPtyIds ---"
rg -n -C 12 'listLiveDaemonPtyIds|startup milestone|startup service' src/main/index.ts src/main -g '*.ts'
echo "--- adapter timeout helpers and listProcesses ---"
sed -n '1260,1365p' src/main/daemon/daemon-pty-adapter.ts
rg -n -C 5 'remainingRequestTimeoutMs|DEFAULT.*TIMEOUT|requestTimeout|deadlineMs' src/main/daemon -g '*.ts'
echo "--- relevant tests ---"
rg -n -C 8 'listLiveDaemonPtyIds|listProcesses.*deadline|deadlineMs.*listProcesses|getAllAdapters' src/main/daemon src/main/index.ts -g '*.ts'

Repository: stablyai/orca

Length of output: 50369


Use an explicit startup deadline for listLiveDaemonPtyIds().

getAllAdapters() is public on both classes. listProcesses() uses the client’s 30-second default when no deadlineMs is supplied, so a wedged socket can delay first-window startup for up to 30 seconds.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Electron validation completed on exact pushed SHA 4f6d50a from the PR checkout.\n\n- Initial launch used the legacy shared-home route. The real Orca window showed the authenticated OpenAI Codex v0.146.0 composer in the PR workspace.\n- After a graceful app quit and relaunch of the same isolated profile with real-home routing enabled, Orca reattached the same retained local daemon PTY (…@@3a5df3bf). The foreground process remained codex and the authenticated composer stayed usable; I chose “Keep current session” on the expected setup-change notice to prove the retained session itself survived.\n- The app identity reported /Users/brennanbenson/orca/workspaces/orca/pr-11720-persistent-codex-review and branch brennanb2025/pr-11720-persistent-codex-review.\n\nBefore relaunch:\nAuthenticated Codex before relaunch\n\nAfter same-PTY reattach:\nAuthenticated Codex after reattach\n\nValidation: exact Node 24 focused suite passed 14 files / 715 tests; full typecheck, full lint, changed-file Oxfmt, and git diff checks passed. Fresh inherited-model review of the exact pushed SHA returned CLEAN with no mutation.

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