Repository navigation
fix(mobile): keep closed sessions empty - #11251
Conversation
|
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 SummaryThis 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."
Confidence Score: 5/5Safe 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.
|
| 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
📝 WalkthroughWalkthroughReplaces 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)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
mobile/src/session/use-initial-session-terminal-autocreate.ts (2)
45-49: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider
useEffectEventinstead of the manual latest-ref pairs.
consumeCreationRouteRef/createTerminalRefreimplement the "latest ref" pattern that React 19.2'suseEffectEventwas 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
MutableRefObjectis deprecated in React 19; both files import it for the same ref shape. React 19's types unifiedMutableRefObjectintoRefObject<T>(mutable.currentby default); the type still compiles today but is worth retiring together in one pass since both usages describe the sameInitialSessionTerminalAutoCreateStateref shape.
mobile/src/session/use-initial-session-terminal-autocreate.ts#L1-L1: replace theMutableRefObjectimport/usage (also used at line 21 inInitialSessionTerminalAutoCreateArgs) withRefObject.mobile/src/session/use-initial-session-terminal-autocreate.test.ts#L1-L1: replace theMutableRefObjectimport/usage (also used at lines 18-21 for the localstateRefvariable) withRefObject.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 226a5556-7f83-4765-bee5-238044235d17
📒 Files selected for processing (6)
mobile/app/h/[hostId]/session/[worktreeId].tsxmobile/src/session/initial-session-terminal.test.tsmobile/src/session/initial-session-terminal.tsmobile/src/session/mobile-session-startup-source.test.tsmobile/src/session/use-initial-session-terminal-autocreate.test.tsmobile/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.
979f8f0 to
c0beda0
Compare
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.
|
Addressed all bot feedback on this push. CodeRabbit nitpick 1 — CodeRabbit nitpick 2 — deprecated CodeRabbit pre-merge "Description check": fixed — the description now follows 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 Greptile: 5/5, no actionable findings — no changes needed. One React Doctor finding is deliberately not fixed: the non-blocking Verification after these changes: mobile suite 357 files / 2621 passed, 2 skipped (own parent baseline Branch was rebased onto current |
|
@coderabbitai review Both nitpicks from the previous review are addressed ( |
|
✅ Action performedReview finished.
|
There was a problem hiding this comment.
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
📒 Files selected for processing (6)
mobile/app/h/[hostId]/session/[worktreeId].tsxmobile/src/session/initial-session-terminal.test.tsmobile/src/session/initial-session-terminal.tsmobile/src/session/mobile-session-startup-source.test.tsmobile/src/session/use-initial-session-terminal-autocreate.test.tsmobile/src/session/use-initial-session-terminal-autocreate.ts
There was a problem hiding this comment.
🧹 Nitpick comments (1)
mobile/src/session/use-initial-session-terminal-autocreate.test.ts (1)
27-40: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winCover the non-null
activeHandlepath.The production effect accepts
visibleTabCount === 0whenactiveHandle !== null, butHarnessalways passesactiveHandle: 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
📒 Files selected for processing (3)
mobile/src/session/mobile-session-startup-source.test.tsmobile/src/session/use-initial-session-terminal-autocreate.test.tsmobile/src/session/use-initial-session-terminal-autocreate.ts
* 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
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
handleCloseSessionTabprunes the tab locally and nullsactiveHandle, 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
mainby #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 rendererptyIdsByTabIdownership 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— mobileoxlint, 0 findings; rootoxlint, 0 warnings / 0 errorspnpm typecheck— mobiletsc --noEmitcleanpnpm test— mobile suite 357 files / 2621 passed, 2 skipped, against my own parent baseline0349cb6bdbof 355 / 2606, 2 skipped (+2 files, +15 tests)pnpm build— not run.mobile/is an Expo app with nobuildscript, and this PR touches onlymobile/src/session/**+ the session route. The root Electron build is unaffected; roottypecheckis green in CI.Non-vacuity was proven by mutation, re-verified on current
main:return !input.sawSessionTabswithreturn trueturns 2 tests red — the close repro and the host-drops-every-tab case.useEffectEventwiring to a render-time ref write turns themobile-session-startup-sourcepin red.Also ran the gates that PR Checks'
static analysisjob 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. Nomax-linesdisable 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:
useEffectEvent(React 19.2, already used inSourceControl.tsx) — same stable-callback-outside-deps behavior, no render-time mutation. CodeRabbit independently flagged the same lines.MutableRefObjectforRefObjectin the impl and its test (CodeRabbit).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-nativeimports at all. Folder workspaces take the same route and snapshot path as git worktrees. An unreachable SSH host leavesconnState !== '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.yamlis 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:
The host conflates "unpublished" with "empty."
getMobileSessionTabsForWorktreeanswers "I hold no snapshot for this worktree" with{ tabs: [], publicationEpoch: 'none', snapshotVersion: 0 }— wire-identical to a genuinely empty workspace — andacceptSessionSnapshotaccepts a new epoch unconditionally, so mobile applies a pre-publication read as authoritative. The siblingfetchTerminalsalready defends against this class by requiring two consecutive empties before trusting zero;applySessionTabshas no such guard and setsterminalsLoaded = trueon any accepted snapshot. Fixing this properly needs a distinct sentinel and a protocol decision, not a mobile-only change.View-driven materialize can relaunch a dead agent tab in place.
shouldMaterializePendingTerminalspawns a fresh PTY for any mobile activation of a non-readytab, and mobile auto-activates any active pending terminal tab. A desktop tab whose agent process has exited is publishedpending-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, foruseRef(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.