Skip to content

fix(mobile): keep closed sessions empty - #11251

Merged
brennanb2025 merged 5 commits into
mainfrom
brennanb2025/mobile-9717-dup-sessions
Jul 30, 2026
Merged

brennanb2025 merged 5 commits into
mainfrom
brennanb2025/mobile-9717-dup-sessions

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closing the last terminal tab on mobile immediately spawned a brand-new one, and it recurred on every visit to the workspace.

The session route treated "zero session tabs" as "this workspace has never had anything" and auto-created a terminal. But handleCloseSessionTab prunes the tab locally and nulls activeHandle, which produces exactly that state — so the close was followed by an unsolicited spawn. The guard was also re-armed by the route's worktree-change reset, so leaving and returning made it happen again.

This gates the auto-create on whether the route has ever published a non-empty tab list for the workspace. A cold hydrate still gets its first terminal; an emptied list now gets the empty state and its Create Tab button.

Scope note: #9717 bundles two mechanisms. The "which session do I want to resume" half was already fixed on main by #10647 and is in this PR's baseline. This is the other half. It is not a duplicate of #10486, which is a same-content mirror tab (a renderer ptyIdsByTabId ownership miss, fixed as #11259); #9717's extra sessions are fresh processes.

Screenshots

No visual change to any component. The behavioral change is which state the route lands in after the final close: previously a new terminal, now the pre-existing empty state with its Create Tab button. Device validation is in Testing below.

Testing

  • pnpm lint — mobile oxlint, 0 findings; root oxlint, 0 warnings / 0 errors
  • pnpm typecheck — mobile tsc --noEmit clean
  • pnpm test — mobile suite 357 files / 2621 passed, 2 skipped, against my own parent baseline 0349cb6bdb of 355 / 2606, 2 skipped (+2 files, +15 tests)
  • pnpm build — not run. mobile/ is an Expo app with no build script, and this PR touches only mobile/src/session/** + the session route. The root Electron build is unaffected; root typecheck is green in CI.
  • Added or updated high-quality tests that would catch regressions

Non-vacuity was proven by mutation, re-verified on current main:

  • Replacing the gate's return !input.sawSessionTabs with return true turns 2 tests red — the close repro and the host-drops-every-tab case.
  • Reverting the hook's useEffectEvent wiring to a render-time ref write turns the mobile-session-startup-source pin red.

Also ran the gates that PR Checks' static analysis job silently skipped on the previous push (React Doctor is step 5 of ~17, and an early failure skips the rest): max-lines ratchet, localization catalog, localization coverage, Zustand selector fan-out, reliability gate manifest, changed-code quality. All pass. No max-lines disable or per-file bump was added.

AI Review Report

Reviewed for: whether the guard can strand a genuinely empty workspace with no terminal; per-route and per-worktree state leakage across reused routes; and the SSH and folder-workspace paths.

Flagged and fixed:

  • React Doctor, blocking: "Ref mutated during render" ×2. The hook kept both callbacks out of the effect deps by writing latest-refs during render. React can replay or discard a render, so the write can leak from UI that never commits. This failed PR Checks. Replaced with useEffectEvent (React 19.2, already used in SourceControl.tsx) — same stable-callback-outside-deps behavior, no render-time mutation. CodeRabbit independently flagged the same lines.
  • Retired the deprecated MutableRefObject for RefObject in the impl and its test (CodeRabbit).
  • Added docstrings to the two exported helpers, both of which exist for a non-obvious per-route reset contract (CodeRabbit docstring coverage).

Cross-platform: explicitly checked. This is React Native code with no keyboard shortcuts, no shortcut labels, no path handling, no shell invocation, and no Electron platform branches. The gate is pure, client-side, and workspace-kind agnostic — it has no react-native imports at all. Folder workspaces take the same route and snapshot path as git worktrees. An unreachable SSH host leaves connState !== 'connected', which already blocked auto-create and still does.

Security Audit

No new input handling, command execution, path handling, auth, secrets, dependency, or IPC surface. The change only removes a condition under which the client issues a terminal-create RPC, so it strictly narrows what the phone can cause the host to spawn — the direction that reduces risk. No new dependencies; mobile/pnpm-lock.yaml is unchanged. No follow-up needed.

Notes

Merge ordering: land this before or together with #11240. #11240 (the #6927 close-path fix) correctly routes more terminal closes through the authoritative session-tab close path, which feeds more closes into the path fixed here and makes the unsolicited spawn easier to hit. The branches combine cleanly and do not need an atomic merge, but #11240 should not land first.

Two residuals found during this investigation, deliberately left unfixed as out of scope:

  1. The host conflates "unpublished" with "empty." getMobileSessionTabsForWorktree answers "I hold no snapshot for this worktree" with { tabs: [], publicationEpoch: 'none', snapshotVersion: 0 } — wire-identical to a genuinely empty workspace — and acceptSessionSnapshot accepts a new epoch unconditionally, so mobile applies a pre-publication read as authoritative. The sibling fetchTerminals already defends against this class by requiring two consecutive empties before trusting zero; applySessionTabs has no such guard and sets terminalsLoaded = true on any accepted snapshot. Fixing this properly needs a distinct sentinel and a protocol decision, not a mobile-only change.

  2. View-driven materialize can relaunch a dead agent tab in place. shouldMaterializePendingTerminal spawns a fresh PTY for any mobile activation of a non-ready tab, and mobile auto-activates any active pending terminal tab. A desktop tab whose agent process has exited is published pending-handle, so merely opening that workspace on the phone can relaunch the agent — and because the tab keeps its id, this replaces a finished session rather than adding one, matching the "too many sessions instead of the original sessions" report. This is the same principle Stop relaunching creation-time agents on workspace activation #10647 settled for desktop (navigation is not consent to start a process), still live on the mobile side.

Suggested issue hygiene: keep #9717 open and split it. The resume-picker half is closed by #10647; the remaining half is this PR plus residual 2.

There is also one non-blocking React Doctor warning left on a line this PR adds — "Ref initializer runs on every render" at [worktreeId].tsx:1040, for useRef(createInitialSessionAutoCreateState()). Left as-is deliberately: the three adjacent pre-existing ref declarations use the same eager-init idiom, and the null-guarded lazy alternative would push a nullable state type through the hook's signature for one small object allocation.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Device-validated on an iPhone 17 Pro simulator: closing the final terminal left the workspace at 0 tabs, and navigating away/reopening preserved the empty state without spawning a replacement. Merge-order note: please land this before or with #11240; landing #11240 first routes more closes into this path and makes the unsolicited spawn easier to hit.

@greptile-apps

greptile-apps Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a mobile bug (#9717 / #7345) where closing the last terminal tab immediately spawned a new one, recurring on every return visit. The root cause was the auto-create guard treating "zero tabs after a close" as "cold empty workspace."

  • Introduces shouldAutoCreateInitialSessionTerminal (pure, no React imports) gated on a new sawSessionTabs one-way ratchet — once the route has published any non-empty tab list the auto-create is permanently disarmed for that route mount.
  • Replaces the old inline useEffect with useInitialSessionTerminalAutoCreate (fixes two "ref mutated during render" React Doctor violations via useEffectEvent) and useWorktreeSessionTabsLoaded.
  • Ships 15 new targeted tests covering cold-hydrate, post-close guard, host-drops-all-tabs, route-reuse stale state, and connection-absent deferral.

Confidence Score: 5/5

Safe to merge; the change only removes a condition under which the client issues a terminal-create RPC, strictly narrowing what the phone can cause the host to spawn.

The gate logic is pure and exhaustively unit-tested. The sawSessionTabs ratchet is set synchronously before setTerminalsLoaded(true) is dispatched, so the effect always reads a consistent value. The reset effect order ensures sawSessionTabs is cleared before the new worktree subscription fires. The useEffectEvent wrapping correctly removes render-time ref mutations without changing semantics.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
mobile/src/session/initial-session-terminal.ts New pure gate function — sawSessionTabs ratchet is the core bug fix, no React imports keeps it directly unit-testable
mobile/src/session/use-initial-session-terminal-autocreate.ts New hook wrapping the gate using useEffectEvent for callbacks; deps array is correct and the two-phase logic does not conflict
mobile/app/h/[hostId]/session/[worktreeId].tsx Route wires useWorktreeSessionTabsLoaded and useInitialSessionTerminalAutoCreate in place of the old inline effect; mutation order is correct
mobile/src/session/initial-session-terminal.test.ts New unit tests cover cold-hydrate, post-close guard, host-drops-all-tabs, and route-reuse cases
mobile/src/session/use-initial-session-terminal-autocreate.test.ts Integration tests cover route-reuse stale-state, populated-creation-route consumption, and connection/client-absent guards
mobile/src/session/mobile-session-startup-source.test.ts Updated structural pins align with the new hook call-site and the sawSessionTabs mutation

Reviews (3): Last reviewed commit: "fix(mobile): preserve terminal creation ..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Replaces the session screen’s local empty-session auto-creation effect with dedicated gating and React hooks. The new logic tracks auto-creation and observed session tabs, consumes the creation route, scopes tab-loading state by worktree, and resets state on route changes. Pure gating and hook behavior are covered by new lifecycle tests, while existing startup source tests now validate the hook wiring and observed-tab guard.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.86% 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 matches the main change: preventing mobile from auto-spawning a terminal after a session is closed.
Description check ✅ Passed The description follows the template and covers summary, screenshots, testing, AI review, security, and notes with relevant detail.
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.

🧹 Nitpick comments (2)
mobile/src/session/use-initial-session-terminal-autocreate.ts (2)

45-49: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider useEffectEvent instead of the manual latest-ref pairs.

consumeCreationRouteRef/createTerminalRef reimplement the "latest ref" pattern that React 19.2's useEffectEvent was built to replace, and it's duplicated twice here. Since the project is already on React 19.2.6, this is a good candidate to simplify.

♻️ Proposed refactor using `useEffectEvent`
-import { useEffect, useReducer, useRef, type MutableRefObject } from 'react'
+import { useEffect, useEffectEvent, useReducer, type RefObject } from 'react'
 import { shouldAutoCreateInitialSessionTerminal } from './initial-session-terminal'
...
 export function useInitialSessionTerminalAutoCreate(
   args: InitialSessionTerminalAutoCreateArgs
 ): void {
   const {
     client,
     newlyCreatedWorkspace,
     connState,
     terminalsLoaded,
     visibleTabCount,
     activeHandle,
     createInFlight,
     stateRef,
     worktreeId
   } = args
-  const consumeCreationRouteRef = useRef(args.consumeCreationRoute)
-  consumeCreationRouteRef.current = args.consumeCreationRoute
-  // Why: the route re-creates `createTerminal` every render; a ref keeps it out of the deps.
-  const createTerminalRef = useRef(args.createTerminal)
-  createTerminalRef.current = args.createTerminal
+  const consumeCreationRoute = useEffectEvent(args.consumeCreationRoute)
+  const createTerminal = useEffectEvent(args.createTerminal)

   useEffect(() => {
     if (newlyCreatedWorkspace && terminalsLoaded) {
-      consumeCreationRouteRef.current()
+      consumeCreationRoute()
     }
     if (
       !client ||
       !shouldAutoCreateInitialSessionTerminal({ ... })
     ) {
       return
     }
     stateRef.current.autoCreatedForWorktree = worktreeId
-    createTerminalRef.current()
+    createTerminal()
   }, [ ...same deps... ])
 }

1-1: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

MutableRefObject is deprecated in React 19; both files import it for the same ref shape. React 19's types unified MutableRefObject into RefObject<T> (mutable .current by default); the type still compiles today but is worth retiring together in one pass since both usages describe the same InitialSessionTerminalAutoCreateState ref shape.

  • mobile/src/session/use-initial-session-terminal-autocreate.ts#L1-L1: replace the MutableRefObject import/usage (also used at line 21 in InitialSessionTerminalAutoCreateArgs) with RefObject.
  • mobile/src/session/use-initial-session-terminal-autocreate.test.ts#L1-L1: replace the MutableRefObject import/usage (also used at lines 18-21 for the local stateRef variable) with RefObject.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 226a5556-7f83-4765-bee5-238044235d17

📥 Commits

Reviewing files that changed from the base of the PR and between a721125 and 979f8f0.

📒 Files selected for processing (6)
  • mobile/app/h/[hostId]/session/[worktreeId].tsx
  • mobile/src/session/initial-session-terminal.test.ts
  • mobile/src/session/initial-session-terminal.ts
  • mobile/src/session/mobile-session-startup-source.test.ts
  • mobile/src/session/use-initial-session-terminal-autocreate.test.ts
  • mobile/src/session/use-initial-session-terminal-autocreate.ts

…pties

The session route treated "zero session tabs" as "this workspace has never
had anything" and auto-created a terminal. Closing the last tab prunes
sessionTabs and nulls activeHandle locally, which is exactly that state, so
the close was immediately followed by a brand-new terminal — and the guard
re-arms on every route mount, so it recurs across visits (#9717, #7345).

Gate the auto-create on whether this route has ever published a non-empty tab
list for the workspace. A cold hydrate still gets its first terminal; an
emptied list gets the empty state and its create button.

Extracted to a hook because the route file sits at its max-lines cap; the
call site is 4 counted lines smaller than the effect it replaces.
…f write

The hook kept `consumeCreationRoute`/`createTerminal` out of the effect deps by
writing latest-refs during render. React can replay or discard a render, so the
write can leak from UI that never commits — React Doctor flags it as a blocking
"Ref mutated during render" error, which failed PR Checks' static analysis.

useEffectEvent (React 19.2, already used in SourceControl.tsx) gives the same
stable-callback-outside-deps behaviour with no render-time mutation. Retire the
deprecated `MutableRefObject` for `RefObject` in the same pass.

Retargets the source pin at the new wiring; test counts unchanged.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/mobile-9717-dup-sessions branch from 979f8f0 to c0beda0 Compare July 29, 2026 23:29
Both exported helpers exist for a non-obvious reason — they must be re-created or
re-derived per worktree, or a reused route inherits the previous workspace's
hydration state and the resurrection guard silently disarms.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Addressed all bot feedback on this push.

CodeRabbit nitpick 1 — useEffectEvent instead of the manual latest-ref pairs: fixed, and this was not a nitpick. The same two lines were a blocking React Doctor error ("Ref mutated during render" ×2) that failed PR Checks' static analysis job on the previous push. Both callbacks now go through useEffectEvent, which gives the same stable-callback-outside-deps behavior with no render-time mutation. Thanks — the suggestion was the correct fix for the CI failure, not just a style improvement.

CodeRabbit nitpick 2 — deprecated MutableRefObject: fixed in both files, retired for RefObject (mutable .current in React 19 types, so no call-site changes needed).

CodeRabbit pre-merge "Description check": fixed — the description now follows .github/pull_request_template.md with all required sections.

CodeRabbit pre-merge "Docstring Coverage 33.33%": fixed. Added docstrings to the two exported helpers that lacked them. Both document a genuinely non-obvious per-route reset contract rather than restating the signature, per this repo's AGENTS.md comment-style rule.

Greptile: 5/5, no actionable findings — no changes needed.

One React Doctor finding is deliberately not fixed: the non-blocking Performance warning "Ref initializer runs on every render" at [worktreeId].tsx:1040. The three adjacent pre-existing ref declarations use the same eager-init idiom, and the null-guarded lazy alternative would push a nullable state type through the hook's signature to save one small object allocation per render. Rationale is in the PR description.

Verification after these changes: mobile suite 357 files / 2621 passed, 2 skipped (own parent baseline 0349cb6bdb: 355 / 2606); mobile typecheck, lint, and oxfmt --check clean; React Doctor changed-lines now exits 0. I also ran the gates that static analysis silently skipped when it failed at step 5 of ~17 — max-lines ratchet, localization catalog and coverage, Zustand selector fan-out, reliability gate manifest, and changed-code quality — all pass.

Branch was rebased onto current main and re-verified there; the mutation tests proving the guard is non-vacuous were re-run post-rebase.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

Both nitpicks from the previous review are addressed (useEffectEvent replacing the render-time ref writes, and MutableRefObject → RefObject), and both failing pre-merge checks are fixed — the description now follows the repo PR template, and the two previously-undocumented exported helpers have docstrings. Please re-run against 216f1d49a4.

@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

@brennanb2025: Re-running the review against 216f1d49a4, including the updated hook/ref handling and documentation changes.

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 330cc869-c1e2-4beb-9d93-18f57bc0b57a

📥 Commits

Reviewing files that changed from the base of the PR and between 979f8f0 and c0beda0.

📒 Files selected for processing (6)
  • mobile/app/h/[hostId]/session/[worktreeId].tsx
  • mobile/src/session/initial-session-terminal.test.ts
  • mobile/src/session/initial-session-terminal.ts
  • mobile/src/session/mobile-session-startup-source.test.ts
  • mobile/src/session/use-initial-session-terminal-autocreate.test.ts
  • mobile/src/session/use-initial-session-terminal-autocreate.ts

@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)
mobile/src/session/use-initial-session-terminal-autocreate.test.ts (1)

27-40: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Cover the non-null activeHandle path.

The production effect accepts visibleTabCount === 0 when activeHandle !== null, but Harness always passes activeHandle: null. Add a test case for this branch so the new route-consumption behavior cannot regress unnoticed.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ad49d974-7e4d-4364-a5a3-97a95b7004a3

📥 Commits

Reviewing files that changed from the base of the PR and between 216f1d4 and e04db51.

📒 Files selected for processing (3)
  • mobile/src/session/mobile-session-startup-source.test.ts
  • mobile/src/session/use-initial-session-terminal-autocreate.test.ts
  • mobile/src/session/use-initial-session-terminal-autocreate.ts

@brennanb2025
brennanb2025 merged commit 292626e into main Jul 30, 2026
42 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* fix(mobile): stop re-creating a terminal when the session tab list empties

The session route treated "zero session tabs" as "this workspace has never
had anything" and auto-created a terminal. Closing the last tab prunes
sessionTabs and nulls activeHandle locally, which is exactly that state, so
the close was immediately followed by a brand-new terminal — and the guard
re-arms on every route mount, so it recurs across visits (stablyai#9717, stablyai#7345).

Gate the auto-create on whether this route has ever published a non-empty tab
list for the workspace. A cold hydrate still gets its first terminal; an
emptied list gets the empty state and its create button.

Extracted to a hook because the route file sits at its max-lines cap; the
call site is 4 counted lines smaller than the effect it replaces.

* fix(mobile): keep emptied workspaces empty across visits

* fix(mobile): reach the auto-create callbacks without a render-time ref write

The hook kept `consumeCreationRoute`/`createTerminal` out of the effect deps by
writing latest-refs during render. React can replay or discard a render, so the
write can leak from UI that never commits — React Doctor flags it as a blocking
"Ref mutated during render" error, which failed PR Checks' static analysis.

useEffectEvent (React 19.2, already used in SourceControl.tsx) gives the same
stable-callback-outside-deps behaviour with no render-time mutation. Retire the
deprecated `MutableRefObject` for `RefObject` in the same pass.

Retargets the source pin at the new wiring; test counts unchanged.

* docs(mobile): document the two per-route reset contracts

Both exported helpers exist for a non-obvious reason — they must be re-created or
re-derived per worktree, or a reused route inherits the previous workspace's
hydration state and the resurrection guard silently disarms.

* fix(mobile): preserve terminal creation through reconnect
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