Skip to content

fix(native-chat): make structured Codex launches race-resistant - #18251

Merged
brennanb2025 merged 15 commits into
mainfrom
brennanb2025/fix-codex-native-chat-race
Sep 3, 2026
Merged

brennanb2025 merged 15 commits into
mainfrom
brennanb2025/fix-codex-native-chat-race

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​443 $\color{#cf222e}{\Huge{\mathbf{−}}}$​31 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​412
Prod 27 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​487 $\color{#cf222e}{\Huge{\mathbf{−}}}$​106 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​381

What changed

Codex native-chat launch now has one coordinated lifecycle from click to host publication to renderer adoption. The host owns one monotonically versioned snapshot per worktree; publisher identity is separate from snapshot content, so creating and closing chats cannot permanently poison the next launch. The renderer completes from the live host frame and uses inventory only as bounded recovery when a frame or response is lost.

Before / after (user-facing)

Before

  • Clicking New tab → Codex could appear to do nothing.
  • Closing a chat and opening another could leave the workspace stuck or make old tabs appear later.
  • Restart or reconnect timing could leave the local chat list stale.

After

  • One click creates one chat identity; duplicate clicks are coalesced.
  • The new chat appears as soon as the host publishes it, without waiting for a second inventory round trip.
  • Closing a chat cannot be undone by a late launch response.
  • Runtime stream termination triggers one inventory refresh and a clean resubscription.
  • Repeated create → close → create cycles remain valid under the same publisher generation.

Implementation

  • Added a single host snapshot write funnel that stamps strictly increasing per-worktree versions.
  • Removed merge/content hashes from publicationEpoch; it now represents publisher generation only.
  • Replaced local structured-session adoption's shared retirement fence with a local (publicationEpoch, snapshotVersion) gate.
  • Simplified the launch coordinator to wait for the host-emitted renderer projection, with one bounded inventory recovery path and same-intent unknown-state reconciliation.
  • Added stream-end resubscription and focused regressions for host-frame completion, close races, repeated cycles, stale versions, and refusal handling.

Validation

  • 18 focused renderer tests passed (launch coordinator and local structured-session projection).
  • pnpm tc:web passed.
  • pnpm tc:node passed.
  • pnpm run check:code-quality:changed passed.
  • git diff --check passed.
  • Electron CDP attached to the intended taniwha @ brennanb2025/fix-codex-native-chat-race instance; the rendered workspace showed the existing Terminal and Codex Chat tabs with zero console errors. Full click-through was not claimed because this profile did not expose the structured-chat creation menu.

@coderabbitai

coderabbitai Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: f6d10b2c-8bbe-4fe9-95e5-9e6b2398f9a4

📥 Commits

Reviewing files that changed from the base of the PR and between 588c738 and 7a537d1.

📒 Files selected for processing (2)
  • src/renderer/src/runtime/local-structured-session-tabs-sync.test.ts
  • src/renderer/src/runtime/local-structured-session-tabs-sync.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

Structured Codex launches now expose pending and unknown status through a subscription hook. Quick Launch and tab creation actions show a disabled loading state during startup. Launch reconciliation waits for session-tab adoption and supports cancellation. Tab closure cancels active launches and abandons their intents. Session-tab freshness decisions compare renderer and headless-merge publication epochs by lineage. Host snapshot writes now use centralized versioning. Renderer subscriptions retry after termination, and tests cover launch recovery and snapshot lineage handling.

Merge Risk: 🟡 Moderate · up to 7a537

This change improves Codex launch coordination and session-tab recovery, but unresolved risks remain around preserving runtime-owned tabs, publishing concurrent close state, localization, and regression coverage for recovery races. These should be addressed before merge.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the implementation and validation, but it omits several required template sections, including ELI5, Why, a valid Linked Issue, Visual Proof, checklist confirmations, Review, N… Complete the required template sections. Add an ELI5 summary, explain why the approach solves the problem, provide a valid issue reference after "Fixes", attach before-and-after visual proof for the UI behavior, document manual testing and …
Docstring Coverage ⚠️ Warning Docstring coverage is 11.11% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 36 functions across 34 files. 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 clearly and concisely describes the main change: making structured Codex launches race-resistant.
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.
Full details: Description check

Explanation

The description explains the implementation and validation, but it omits several required template sections, including ELI5, Why, a valid Linked Issue, Visual Proof, checklist confirmations, Review, Notes, and Agent skill upstream boundary.

Resolution

Complete the required template sections. Add an ELI5 summary, explain why the approach solves the problem, provide a valid issue reference after "Fixes", attach before-and-after visual proof for the UI behavior, document manual testing and platforms, complete the AI Disclosure as applicable, and fill in Review, Agent skill upstream boundary, Notes, and Checklist items.

  • Fix all pre-merge checks with AI
✨ 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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: e8d6b4d9-8ad1-4a65-b7ce-c2a314bd8005

📥 Commits

Reviewing files that changed from the base of the PR and between 817827b and c52297d.

📒 Files selected for processing (8)
  • src/renderer/src/components/tab-bar/QuickLaunchButton.tsx
  • src/renderer/src/components/tab-bar/TabBarCreateEntry.tsx
  • src/renderer/src/components/tab-bar/TabBarCreateEntryRow.tsx
  • src/renderer/src/components/tab-group/useTabGroupTabCloseCommands.structured-session.test.ts
  • src/renderer/src/components/tab-group/useTabGroupTabCloseCommands.ts
  • src/renderer/src/lib/launch-agent-structured-chat-guard.test.ts
  • src/renderer/src/lib/structured-agent-session-launch.test.ts
  • src/renderer/src/lib/structured-agent-session-launch.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.

const label = entry?.label ?? agent
const isStructuredCodexPending =
agent === 'codex' && structuredCodexLaunchStatus === 'pending'
const menuLabel = isStructuredCodexPending ? 'Starting Codex chat…' : label

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

Localize the pending-state label.

'Starting Codex chat…' bypasses translate in both UI surfaces. Non-English users will see this new status in English.

  • src/renderer/src/components/tab-bar/QuickLaunchButton.tsx#L204-L204: derive the pending label from a dedicated translation key.
  • src/renderer/src/components/tab-bar/TabBarCreateEntry.tsx#L383-L383: pass the same translated pending label to labelOverride.
📍 Affects 2 files
  • src/renderer/src/components/tab-bar/QuickLaunchButton.tsx#L204-L204 (this comment)
  • src/renderer/src/components/tab-bar/TabBarCreateEntry.tsx#L383-L383

closeItem(AGENT_TAB.id)

await vi.waitFor(() => expect(order).toEqual(['agent-close', 'tab-close', 'local-remove']))
expect(mocks.cancelStructuredCodexLaunch).toHaveBeenCalledWith('wt-1', 'session-1')

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

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- repository conventions and learnings ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -maxdepth 2 -type f -name '*.md' -print
printf '%s\n' '--- target file outline ---'
ast-grep outline src/renderer/src/components/tab-group/useTabGroupTabCloseCommands.structured-session.test.ts
printf '%s\n' '--- target file relevant lines ---'
cat -n src/renderer/src/components/tab-group/useTabGroupTabCloseCommands.structured-session.test.ts | sed -n '1,180p'

Repository: stablyai/orca

Length of output: 8755


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- applicable repository conventions ---'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/repo-wide.md
printf '%s\n' '--- close command outline ---'
ast-grep outline src/renderer/src/components/tab-group/useTabGroupTabCloseCommands.ts
printf '%s\n' '--- close command implementation ---'
rg -n -A80 -B20 'cancelStructuredCodexLaunch|closeStructuredAgentSession|callRuntimeRpc|closeUnifiedTab|closeItem' src/renderer/src/components/tab-group/useTabGroupTabCloseCommands.ts

Repository: stablyai/orca

Length of output: 11591


Record cancellation in the ordering assertion.

The test records closeStructuredAgentSession, session.tabs.close, and closeUnifiedTab, but not cancelStructuredCodexLaunch. A cancellation that runs after owner disposal can therefore pass. Make the cancellation mock record its position and assert that it runs first.

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

ℹ️ No blocking issues — the launch coordinator itself is sound. Two localization rough edges inline.

Reviewed changes

  • structured-agent-session-launch.ts — new per-worktree launch coordinator with pending/unknown/idle states, useStructuredCodexLaunchStatus hook via useSyncExternalStore, cancellation through throwIfLaunchCancelled/cancelStructuredCodexLaunch, and a two-part verifyPublishedSession (host publication + renderer adoption).
  • QuickLaunchButton.tsx / TabBarCreateEntry.tsx / TabBarCreateEntryRow.tsx — pending spinner + "Starting Codex chat…" label and disabled state on both launch surfaces; new labelOverride prop.
  • useTabGroupTabCloseCommands.ts — cancels an in-flight launch before closing its owner in both single- and bulk-close paths.
  • Tests — close-race cancellation, response loss, duplicate-click coalescing, unknown recovery, refusal release, and adoption-lag assertions.

The race handling is correct: refreshLocalStructuredSessionTabs applies the snapshot into unifiedTabsByWorktree synchronously before resolving (via applyWebSessionTabsStorePatch → useAppStore.setState), so the adoption check reads a committed store; entityId is set to the session's sessionId (terminal-surfaces.ts:71), matching intent.sessionId, so cancelStructuredCodexLaunch keying is right; and every new test pins an exact assertion (toHaveBeenCalledOnce, toHaveBeenCalledTimes(2)) rather than a truthiness check, so each would fail if the underlying behavior regressed. The only findings are localized UI strings.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

onSelect={() => runLaunch(agent)}
className="gap-2 rounded-[7px] px-2 py-1.5 text-[12px] leading-5 font-medium"
title={translate(
'auto.components.tab.bar.QuickLaunchButton.ec2adf093e',

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.

The title reuses key ec2adf093e for a second fallback. translate returns the catalog value when the key exists, so while pending the tooltip resolves to the catalog's Launch {{value0}} in a new terminal with a literal, uninterpolated {{value0}} — not Starting Codex chat…. Give the pending string its own key (or gate the whole translate call on isStructuredCodexPending).

const label = entry?.label ?? agent
const isStructuredCodexPending =
agent === 'codex' && structuredCodexLaunchStatus === 'pending'
const menuLabel = isStructuredCodexPending ? 'Starting Codex chat…' : label

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.

menuLabel hardcodes Starting Codex chat… in English instead of routing through translate(), so non-English users see an untranslated label. The surrounding strings all use translate(...); this one should too.

option.kind === 'agent' &&
option.option.agent === 'codex' &&
structuredCodexLaunchStatus === 'pending'
? 'Starting Codex chat…'

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.

Same localization gap as the Quick Launch menu: Starting Codex chat… is hardcoded here rather than passed through translate(), so it never localizes.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Visual proof

Captured from the real Electron app via Playwright CDP on the brennanb2025/fix-codex-native-chat-race worktree.

Before: Codex entry ready to launch

Codex launch menu before

During: launch in progress

The Codex row now shows a spinner and Starting Codex chat…, while duplicate activation is disabled.

Codex launch pending

After: one unified Codex chat tab

Codex chat tab after launch

@brennanb2025

brennanb2025 commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Attachments

codex-after-freshness-fix.png
codex-after-freshness-fix.png

Electron CDP native Codex close/reopen race

01-before-native-chats.png 02-plus-menu-codex.png
01-before-native-chats.png 02-plus-menu-codex.png
03-first-codex-chat.png 04-several-codex-chats-open.png
03-first-codex-chat.png 04-several-codex-chats-open.png
05-after-close-all-codex-chats.png 06-after-reopen-codex-chats.png
05-after-close-all-codex-chats.png 06-after-reopen-codex-chats.png
07-final-after-close-reopen-race.png
07-final-after-close-reopen-race.png

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Follow-up fix for the reported permanently-bricked workspace case.

Before: the Codex host session could be created successfully, but renderer adoption was rejected after a host-side :headless-merge: publication retired the underlying renderer epoch. Subsequent inventory refreshes then looked stale, so repeated clicks could only end in Could not open Codex chat / structured session tab adoption unavailable.

After: merged and base publications are treated as one freshness lineage. Version ordering still rejects genuinely stale frames, while a newer base inventory can reconcile after a merge. This lets an existing host session be adopted and keeps retries bounded/cancelable when a tab closes mid-flight.

Validation: 29 focused tests pass, pnpm tc passes, changed-code quality reports 0 new findings, and the live Electron instance adopted the orphaned session and opened a fresh Codex tab. Full-window screenshot attached above.

@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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/renderer/src/lib/structured-agent-session-launch.test.ts (1)

74-76: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Keep publication and adoption fixtures independent.

publishedSnapshot mutates mocks.rendererTabs before verifyPublishedSession runs. Every successful verification test uses this helper, so an adoption-check regression can pass. Keep the renderer tab list empty during publication, then add the tab separately in at least one test.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 94df00d4-b54e-46dc-b998-25eca344a85d

📥 Commits

Reviewing files that changed from the base of the PR and between c52297d and cf60889.

📒 Files selected for processing (5)
  • src/renderer/src/lib/structured-agent-session-launch.test.ts
  • src/renderer/src/lib/structured-agent-session-launch.ts
  • src/renderer/src/runtime/web-session-tabs-sync.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync/publisher-identity-fences.ts
  • src/renderer/src/runtime/web-session-tabs-sync/tracking-decisions.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.

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

ℹ️ No new issues introduced by this increment. The three localization threads from the prior review (hardcoded Starting Codex chat… strings and the reused tooltip key) remain open and are not touched by these commits.

Reviewed changes

  • structured-agent-session-launch.ts — retrySameIntent now throws StructuredAgentSessionLaunchCancelledError when cancellation lands during the final verification retry, instead of parking the launch and toasting later.
  • publisher-identity-fences.ts — added sameSessionTabsPublicationLineage and isHeadlessMergeSessionTabsPublication so a base publication and its :headless-merge: sibling are treated as one ordering lineage.
  • tracking-decisions.ts — exempted same-lineage retired epochs from the OUTRANKED fence and gated the stale-version check behind comparePublicationVersions, so the mirror stops dropping a renderer base publication published after a host-side headless merge.
  • web-session-tabs-sync.test.ts — added base/merge-lineage and delayed-frame coverage.
  • structured-agent-session-launch.test.ts — added the close-races-final-verify test plus the abandonIntent and renderer-tabs mocks.
  • launch-agent-structured-chat-guard.test.ts — seeded unifiedTabsByWorktree for the adoption requirement and the second-intent path.

The cancellation check is correct: the final-verify retry now re-checks state.cancelled before parking, and the focused test pins exact assertions (toHaveBeenCalledTimes(2), no toast.error, abandonIntent called once). The lineage logic is also sound for its intended single-pairing scope — the host keeps base and merge snapshotVersion values in one monotonic counter inside a host process (orca-runtime-sync-mobile-session-tabs.ts:167-169), so the merge→base comparison in comparePublicationVersions does not cross counters, and the pairing-revision teardown (global-session-subscription.ts:97) resets mirror freshness across re-pairs.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@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: 3

🧹 Nitpick comments (2)
src/renderer/src/lib/structured-agent-session-launch.test.ts (2)

133-143: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Align this test with the inventory-recovery path it names, or rename it.

The body no longer reaches inventory recovery. cancelStructuredCodexLaunch runs before the launch promise resolves, so throwIfLaunchCancelled rejects at structured-agent-session-launch.ts Line 251 and recoverStructuredSessionFromInventory never runs. The test then duplicates the preceding "cancels a close-racing launch" test, and a regression in the cancellation check inside recoverStructuredSessionFromInventory would still pass here.

To cover the named path, make the launch reject so the flow enters recovery, then cancel while refreshLocalStructuredSessionTabs is pending.

♻️ Proposed test that exercises inventory recovery
   it('does not retry creation when close races inventory recovery', async () => {
     const worktreeId = 'wt-close-final-verify'
     const intent = launchIntent(worktreeId, 'session-close-final-verify')
     mocks.createIntent.mockReturnValueOnce(intent)
-    mocks.launch.mockResolvedValue(intent.sessionId)
+    mocks.launch.mockRejectedValue(new Error('response lost'))
+    let releaseRefresh: (value: RuntimeMobileSessionTabsResult[]) => void = () => {}
+    vi.mocked(refreshLocalStructuredSessionTabs).mockReturnValueOnce(
+      new Promise((resolve) => {
+        releaseRefresh = resolve
+      })
+    )
 
     startStructuredCodexLaunch(worktreeId)
+    await flushLaunchSettlement()
     expect(cancelStructuredCodexLaunch(worktreeId, intent.sessionId)).toBe(true)
+    releaseRefresh([publishedSnapshot(worktreeId, intent.sessionId)])
     await flushLaunchSettlement()
 
     expect(mocks.launch).toHaveBeenCalledOnce()
+    expect(toast.error).not.toHaveBeenCalled()
   })

This asserts that the cancellation check after the refresh await at structured-agent-session-launch.ts Line 170 prevents a stale success.


232-234: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

publishedSnapshot mutates the store eagerly, which diverts a test off the path it means to cover. publishedSnapshot writes mocks.rendererTabs in addition to returning a snapshot. When a test passes it as an argument to mockResolvedValueOnce, the renderer tab is adopted at mock-setup time, so waitForStructuredSessionAdoption takes the already-adopted fast path at structured-agent-session-launch.ts Line 115 and inventory recovery never runs.

  • src/renderer/src/lib/structured-agent-session-launch.test.ts#L232-L234: replace the eager mockResolvedValueOnce([publishedSnapshot(...)]) with mockImplementationOnce(async () => [publishedSnapshot(...)]) so the tab appears only after the first inventory listing returns empty, and the test actually enters recoverStructuredSessionFromInventory.
  • src/renderer/src/lib/structured-agent-session-launch.test.ts#L81-L83: separate the store mutation from the snapshot factory, for example an explicit adoptRendererTab(worktreeId, sessionId) helper, so no caller adopts a tab by evaluating an argument.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: a4bc5216-3111-4454-ba4d-947e8d14626d

📥 Commits

Reviewing files that changed from the base of the PR and between cf60889 and a06813e.

📒 Files selected for processing (24)
  • src/main/runtime/orca-runtime-apply-mobile-session-tab-navigation.ts
  • src/main/runtime/orca-runtime-close-headless-mobile-terminal-tab.ts
  • src/main/runtime/orca-runtime-close-structured-agent-session-tab.ts
  • src/main/runtime/orca-runtime-create-runtime-owned-mobile-session-terminal.ts
  • src/main/runtime/orca-runtime-has-exact-persisted-terminal-surface-identity.ts
  • src/main/runtime/orca-runtime-hydrate-headless-mobile-session-tabs-from-workspace-session.ts
  • src/main/runtime/orca-runtime-move-headless-mobile-session-tab.ts
  • src/main/runtime/orca-runtime-persist-headless-session-tab-props.ts
  • src/main/runtime/orca-runtime-persist-terminal-surface-retirements.ts
  • src/main/runtime/orca-runtime-publish-pty-backed-mobile-session-terminal.ts
  • src/main/runtime/orca-runtime-reconcile-headless-mobile-session-browser-tabs.ts
  • src/main/runtime/orca-runtime-restore-live-paired-renderer-session-owned-mobile-terminals.ts
  • src/main/runtime/orca-runtime-restore-structured-agent-session-tabs-once.ts
  • src/main/runtime/orca-runtime-runtime-id.ts
  • src/main/runtime/orca-runtime-stop-requested-pty-ids.ts
  • src/main/runtime/orca-runtime-stored-mobile-snapshot-has-stale-preserved-tab.ts
  • src/main/runtime/orca-runtime-sync-mobile-session-tabs.ts
  • src/main/runtime/orca-runtime-sync-window-graph.ts
  • src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-06.spec.ts
  • src/main/runtime/orca-runtime-touch-mobile-session-tabs-for-worktree.ts
  • src/renderer/src/lib/structured-agent-session-launch.test.ts
  • src/renderer/src/lib/structured-agent-session-launch.ts
  • src/renderer/src/runtime/local-structured-session-tabs-sync.test.ts
  • src/renderer/src/runtime/local-structured-session-tabs-sync.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

tabs: nextTabs
}
this.mobileSessionTabsByWorktree.set(worktreeId, nextSnapshot)
this.storeMobileSessionSnapshot(worktreeId, nextSnapshot)

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Rebase the close snapshot after the host await.

nextSnapshot can become stale while host.setSessionTabVisibility is pending. storeMobileSessionSnapshot then stamps that old tab list with a newer version and overwrites tabs added or updated in the meantime. The following emit still sends the unstamped version.

Read the current snapshot after the await, apply the tab removal to that snapshot, and emit the value returned by storeMobileSessionSnapshot. Add a regression for an intervening snapshot update.

// The epoch identifies the publisher generation, not the merged content.
// Content changes are ordered by snapshotVersion, so encoding a merge hash
// here would make the identity oscillate and permanently fence later rows.
return normalizedPublicationEpoch

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Keep merge state separate from freshness lineage.

Removing :headless-merge: at Line 124 makes a renderer-based merged snapshot indistinguishable from a pure renderer snapshot. Existing preservation and offscreen-browser checks use that discriminator. Runtime-owned browser tabs can then be treated as renderer-owned and removed during reconciliation.

Keep a stable, non-content merge marker for renderer-based merged snapshots. Compare normalized base lineages for freshness decisions.

  • src/main/runtime/orca-runtime-stored-mobile-snapshot-has-stale-preserved-tab.ts#L124-L124: retain a stable merge discriminator for renderer-based merged snapshots without restoring content hashing.
  • src/renderer/src/runtime/local-structured-session-tabs-sync.ts#L87-L87: compare normalized publication lineage instead of raw publicationEpoch.
  • src/renderer/src/runtime/local-structured-session-tabs-sync.test.ts#L153-L194: add frames that alternate between a renderer epoch and its merged epoch, including delayed lower-version frames from the same lineage.
📍 Affects 3 files
  • src/main/runtime/orca-runtime-stored-mobile-snapshot-has-stale-preserved-tab.ts#L124-L124 (this comment)
  • src/renderer/src/runtime/local-structured-session-tabs-sync.ts#L87-L87
  • src/renderer/src/runtime/local-structured-session-tabs-sync.test.ts#L153-L194

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

ℹ️ No new issues introduced by this increment. The three localization threads from the prior review (hardcoded Starting Codex chat… in QuickLaunchButton.tsx and TabBarCreateEntry.tsx, plus the reused tooltip key) remain open and are not touched by these commits.

Reviewed changes

  • Unified host snapshot versioning — added a single storeMobileSessionSnapshot write funnel that stamps strictly increasing per-worktree snapshotVersion values, routing every .set() call site through it.
  • De-hashed publicationEpoch — getMergedMobileSessionPublicationEpoch now returns the base epoch only, so the epoch encodes publisher generation and content ordering lives entirely in snapshotVersion.
  • Local adoption gate — replaced the shared decideWebSessionTabsSnapshot retirement fence in applyLocalStructuredSessionTabSnapshots with a local (publicationEpoch, snapshotVersion) gate.
  • Store-driven launch completion — the coordinator now completes from the host-emitted renderer projection via useAppStore.subscribe (waitForStructuredSessionAdoption), with one bounded inventory recovery path (recoverStructuredSessionFromInventory) and same-intent unknown reconciliation.
  • Stream-end resubscription — startLocalStructuredSessionTabsSync now reattaches on end with a single refresh so a runtime-restart boundary cannot strand stale tabs.
  • Tests — focused regressions for host-frame completion, close races, repeated cycles, stale versions, and refusal handling, each with exact assertions.

The versioning funnel is sound: every emit site bumps snapshotVersion before storing, so storeMobileSessionSnapshot restamps only on the sync path (which emits from the stored map, not the raw frame), keeping the emitted version strictly monotonic and consistent with what the client freshness gate expects (graph-sync-mobile-snapshot-gating.test.ts pins this). The local gate is correct for the single-host in-order stream — epochs are never reused, so "any new epoch wins" cannot accept a stale cross-epoch frame. The waitForStructuredSessionAdoption subscription is correctly torn down on settle/cancel and the cancellation waiter set is drained before abandoning the intent.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

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

ℹ️ No new issues introduced by this increment. The three localization threads from the prior review (hardcoded Starting Codex chat… in QuickLaunchButton.tsx and TabBarCreateEntry.tsx, plus the reused tooltip key) remain open and are not touched by this commit.

Reviewed changes

  • Replay unknown launches by intent — reconcileUnknownLaunch now, after a 1s adoption wait and an inventory miss, re-issues launchStructuredCodexSession(state.intent) with the same intent (stable sessionId and clientOperationId) before waiting for adoption, instead of only checking inventory. Added inventoryContainsIntent as a shared helper and a focused replays the same intent after an absent unknown outcome regression.

The re-launch is safe: the intent's clientOperationId is minted once at createStructuredCodexSessionLaunchIntent and reused verbatim, so the host's mutation-admission ledger dedupes the replay on operationId: envelope.clientOperationId (structured-agent-session-mutation-admission.ts:70) and either replays the prior outcome or runs it once — it cannot mint a second session for the same click. The retry remains bounded to one re-launch per reconcile, with recoverStructuredSessionFromInventory re-marking the state unknown on a second failure, and StructuredAgentSessionLaunchCancelledError / StructuredAgentSessionCreateRefusalError still short-circuit correctly.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Visual proof (Electron CDP, current PR worktree)

Captured from a launched taniwha @ brennanb2025/fix-codex-native-chat-race instance (CDP 9337 / renderer 127.0.0.1:5177). Isolated fresh profile; Chat UI + structured native chat enabled; local sample git workspace. Screenshots are uncropped full-app windows.

Scenario: New tab → Codex → pending Starting Codex chat… → Codex Chat tab → close tab → re-select workspace → New tab → Codex again.

Before: Codex ready in the New tab menu

before-codex-menu

During: launch pending (duplicate activation disabled)

during-starting-codex-chat

After: first structured Codex Chat tab

Session codex_975495f4_4578_4950_b7ea_a6c033cd75a2 adopted as contentType: agent-session. Native chat empty state visible. Console: 0 errors.

after-first-codex-chat

After close

Chat tab gone; workspace returned to empty/inactive.

after-close

After relaunch: new session, old id not restored

Second session codex_a6eed3bf_aad3_48c1_ba7b_e02434971b55. First session id did not reappear.

after-relaunch-codex-chat

Not visually triggered: unknown-state same-intent replay (needs a lost host frame). Search-omnibox Codex row and in-chat message send were not exercised.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: land after fixes

The same-model review/fix loop is CLEAN, and the final readiness checklist is PASS/CLEAN.

Fixes pushed to the PR branch:

  • Guarded Enter-key and other duplicate structured Codex launches while a launch is pending.
  • Added bounded, cancellable reconnect backoff with inventory refresh and rejection handling.
  • Restored bounded publication-epoch fencing so delayed predecessor frames cannot overwrite current tabs.
  • Pruned publisher cursors for deleted git and folder workspaces.
  • Added focused regressions for launch single-flight, stale epochs, reconnect behavior, and folder-workspace cleanup.

Validation:

  • 60 focused tests passed locally after the final fixes.
  • pnpm tc:web passed.
  • pnpm tc:node passed.
  • Changed-code quality: 0 findings across 34 files.
  • git diff --check passed.
  • Final readiness: no proven P0/P1/P2 issues across SSH/remote, retry/resource, security, performance, functional, mobile backcompat, cross-platform, or organization checks.
  • Electron CDP validation passed on the exact PR worktree: pending launch UI, single adopted Codex Chat tab, close, and fresh relaunch were verified with no console errors. Uncropped screenshots are attached in the existing visual-proof comments.
  • Mobile emulator QA is not applicable: no mobile source or session-tab wire fields changed.

Current GitHub checks are running for commit 588c738.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/renderer/src/components/tab-bar/TabBarCreateEntry.tsx (1)

386-386: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Localize both visible pending Codex labels.

When Codex launch status is pending, TabBarCreateEntry.tsx and QuickLaunchButton.tsx render Starting Codex chat… directly. Both components are mounted in current UI paths, so non-English users can see this English-only label. Add separate translate() calls for the labelOverride and menuLabel values; translating the QuickLaunch tooltip does not localize its visible label.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 9b679d46-7323-4e17-b904-0b09f20d003c

📥 Commits

Reviewing files that changed from the base of the PR and between a06813e and 588c738.

📒 Files selected for processing (5)
  • src/renderer/src/components/tab-bar/TabBarCreateEntry.keyboard.test.tsx
  • src/renderer/src/components/tab-bar/TabBarCreateEntry.tsx
  • src/renderer/src/lib/launch-agent-structured-chat-guard.test.ts
  • src/renderer/src/runtime/local-structured-session-tabs-sync.test.ts
  • src/renderer/src/runtime/local-structured-session-tabs-sync.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/lib/launch-agent-structured-chat-guard.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.

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

ℹ️ No critical issues — one minor suggestion inline.

Reviewed changes

  • Backed off structured-session resubscription — replaced the single refresh-and-reattach with an exponential-backoff retry loop (scheduleSubscribeRetry) guarded by a reconnect timer and a subscriptionGeneration staleness check, so a runtime-restart boundary can't strand stale tabs.
  • Fenced delayed local snapshots — added a per-worktree retired-epoch history plus sameSessionTabsPublicationLineage so a delayed frame from a superseded publisher generation can't roll the local projection back.
  • Cleaned up publisher cursors — dropped localStructuredSessionVersionByWorktree / epoch-history entries for worktrees and folder workspaces that no longer exist.
  • Guarded duplicate Codex launches — TabBarCreateEntry now drops a second launch while a structured launch is already pending, covered by a keyboard regression test.

The three localization threads from the prior review remain open and are not touched by this increment.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

return
}
const reconnectDelay = Math.min(250 * 2 ** reconnectAttempt, 5000)
reconnectAttempt += 1

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.

reconnectAttempt only ever increments, so after a few reconnect cycles the resync delay sits at the 5s cap for the rest of the renderer session — a later, unrelated runtime restart then waits ~5s before refreshing its tabs. Reset it when a subscribeCurrent succeeds (e.g. alongside activeHandle = handle at line 250) so each failure episode re-arms backoff from scratch.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Final review status: land after fixes

The review/fix loop is clean. One meaningful in-scope reliability issue was found and fixed in commit 7a537d1cbb: a failed structured-session subscription frame could leave the local session-tab stream stranded without resubscribing. The fix generation-fences the failed stream, cleans up its handle, and enters the existing bounded exponential-backoff refresh/reconnect path; a focused regression covers the error and late-frame cases.

Validation completed:

  • 46 focused native-chat launch, close, UI guard, and local sync tests passed.
  • Aggregate main runtime suite: 1,225 passed, 1 skipped.
  • pnpm tc:web and pnpm tc:node passed.
  • Changed-code quality passed with 0 new findings; git diff --check passed.
  • Performance/resource review found bounded backoff (250ms to 5s), capped epoch history, cleaned launch waiters/listeners, and no new hot-path scans or subprocess fanout.
  • Final Electron CDP test on the exact PR worktree opened four native Codex chats, closed all four, reopened several fresh sessions, and exercised close-as-soon-as-visible. The rendered UI showed native chat tabs only, closed sessions did not return, backing store IDs were fresh, and the renderer reported 0 native-chat console errors. Full-window screenshots are attached in the preceding comment.
  • No mobile source or wire-contract change, and no Windows/WSL/SSH-specific path changed, so those conditional QA lanes were not applicable.

Final readiness: PASS/CLEAN with no proven P0/P1/P2 findings. GitHub checks are still running for 7a537d1cbb; merge after required checks pass.

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

ℹ️ No new issues in this increment — the resubscription fix is correct. Approval remains blocked by four open Pullfrog threads that this commit does not address: three localization gaps (the hardcoded Starting Codex chat… in QuickLaunchButton.tsx and TabBarCreateEntry.tsx, and the reused tooltip key ec2adf093e) plus the reconnectAttempt backoff-reset nitpick in local-structured-session-tabs-sync.ts.

Reviewed changes

  • Error-response resubscription — startLocalStructuredSessionTabsSync now fences the current subscription generation and schedules a retry when the streaming RPC delivers an !response.ok response, instead of silently dropping it and leaving the stream dead.
  • Exported sync entrypoint — startLocalStructuredSessionTabsSync is now exported so the regression test can drive the sync lifecycle directly.
  • Focused regression — a new test pins the 250 ms first retry, single-retry-per-error behavior, unsubscribe ordering, and suppression of late errors from a fenced generation.

The fix is correct for the race it targets: the callback captures generation, so the top-of-callback stale check (generation !== subscriptionGeneration) drops both late errors and events from a superseded generation; the !response.ok branch increments the generation before scheduling, so a handle that resolves after the error is unsubscribed at the post-await guard rather than leaking; and scheduleSubscribeRetry's reconnectTimer !== null guard prevents overlapping retries when the subscribe promise also rejects.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@brennanb2025
brennanb2025 merged commit 21210aa into main Sep 3, 2026
32 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…lyai#18251)

* fix(native-chat): cancel close-racing structured launches

* fix(native-chat): make structured launches observable and recoverable

* fix(native-chat): reconcile merged session tab publications

* refactor(native-chat): unify host snapshot versioning

* refactor(native-chat): complete launches from host snapshots

* fix(native-chat): replay unknown launches by intent

* fix(native-chat): guard duplicate launches and bound sync recovery

* test(native-chat): type owner fixture

* test(native-chat): type owner fixture

* fix(native-chat): back off structured session resubscribe

* fix(native-chat): fence delayed local session snapshots

* fix(native-chat): retry initial session sync safely

* fix(native-chat): refresh before sync retry

* test(native-chat): cover folder sync cursor cleanup

* fix(native-chat): retry failed structured session subscriptions

---------

Co-authored-by: Merge Sim <sim@local>
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