Skip to content

fix(mobile): stop a client terminal subscribe from reviving a slept workspace - #11389

Closed
mmarabel wants to merge 2 commits into
stablyai:mainfrom
mmarabel:fix/mobile-subscribe-wakes-slept-workspace
Closed

mmarabel wants to merge 2 commits into
stablyai:mainfrom
mmarabel:fix/mobile-subscribe-wakes-slept-workspace

Conversation

@mmarabel

Copy link
Copy Markdown
Contributor

Summary

Sleeping a workspace could be undone by a phone or web client, with no action on the desktop.

Sleep kills a workspace's PTYs but deliberately keeps tab.ptyId as a wake hint. planMobileTerminalTabMount only checked that the incoming handle resolved to a real tab, so when a client called terminal.subscribe on one of that workspace's terminals, the desktop background-mounted the pane and brought a PTY back up — reviving the workspace without any user activation and without navigating anywhere. The user sees a workspace they slept turn green again, and opening it shows a bare shell (a fresh spawn carries no agent resume).

This makes the planner fail closed when a mount could only create a PTY rather than attach one: the workspace holds no live PTY, no queued startup, and no pending activation spawn. terminal.subscribe already degrades to a scrollback-only stream when no PTY appears, so the client still gets the terminal's saved output — it just no longer resurrects the workspace.

Still allowed, and covered by tests:

  • a never-mounted tab in a workspace that has another live PTY (the case this path exists for)
  • a freshly created mobile tab whose PTY has not spawned yet (terminal.create → subscribe races the spawn)
  • a tab whose activation spawn is pending

Fixes #10205

Screenshots

No visual change.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • Added or updated high-quality tests that would catch regressions

Six new cases in mobile-terminal-tab-mount.test.ts (12/12 pass): three that a slept workspace is not revived via real-tab id, synthetic pty handle, or before consulting mount state; three that legitimate mounts still proceed.

Note on pnpm test: the full suite has 43 pre-existing failures in 9 files unrelated to this change (use-markup-draw-hint, pr-comment-presentation, pr-comments-list-selection, use-persisted-ai-vault-view-options, LinearAgentSkillSetupPrompt.reminder-toast, mobile-sidebar-onboarding-badge, SidebarToolbar, transcript-watch-liveness, agent-exec-handler). Verified identical failures on unmodified upstream/main at 4543bb6 — mostly window.localStorage being undefined in those environments.

Field verification

Reproduced and then verified fixed against a running dev build over CDP:

  • Before: a slept workspace (0 live PTYs) received a mobile-style tab mount and came back to life — live PTYs went 0 → 1 → 2 → 3 across three tabs while the desktop stayed on a different workspace the whole time. planMobileTerminalTabMount returned a mount plan for every slept workspace.
  • After: slept workspaces return null; a workspace with live PTYs still plans its mount.

AI Review Report

Reviewed with Claude Code across the risk areas below.

  • Cross-platform (macOS/Linux/Windows): pure state predicate over store records — no paths, shells, keyboard shortcuts, accelerators, or Electron platform APIs touched. No platform-conditional behavior added or changed.
  • SSH / remote: the guard reads ptyIdsByTabId, which is populated for local, SSH, and remote-runtime PTYs alike, so a live remote workspace still mounts. Remote-runtime and SSH pty ids are not special-cased, matching the surrounding code.
  • Agent/integration compatibility: the pending-startup and pending-activation-spawn escapes keep the terminal.create → subscribe path working, which is how mobile launches agents. Verified no other caller exists — planMobileTerminalTabMount is called only from useIpcEvents, which passes the full store state.
  • Performance: one Array.every over a single workspace's tabs on an event that already does more work; no new renders, subscriptions, or IPC.
  • UI quality: no visual change.
  • Security: see below.
  • Flagged and addressed: the first draft gated only on "no live PTY", which would have broken mobile terminal creation; the pending-startup and pending-activation-spawn conditions were added and given dedicated tests.
  • Considered and rejected: a durable sleptWorktreeIds marker. It is the more complete fix (it would also cover the non-mobile wake paths listed in [Bug]: Sleeping workspaces revive without user activation — hard to diagnose (open question on opt-in lifecycle logging) #10205), but the issue notes that approach was added and reverted historically, so it needs a maintainer decision rather than a drive-by change.

Security Audit

No new input handling, command execution, path handling, auth, secrets, or dependency surface. The change is a read-only predicate over existing renderer store state and strictly narrows what a remote client can cause the desktop to do — a client can no longer cause PTY spawns in a workspace the user has slept. IPC shape is unchanged; the message is already validated by the existing planner, and the new check runs before any mount is scheduled. No follow-up needed.

Notes

  • Behavior change for clients: subscribing to a terminal in a slept workspace now yields scrollback-only instead of silently starting the workspace. That is the intended product behavior per the issue's "Expected" section; waking should go through explicit activation (worktree.activate).
  • This closes the one path I could reproduce deterministically. [Bug]: Sleeping workspaces revive without user activation — hard to diagnose (open question on opt-in lifecycle logging) #10205 lists other candidate wake paths (activateAndRevealWorktree → resumeSleepingAgentSessionsForWorktree, cold-restore agent resume, startup hydration); I could not reproduce those on current main, including the issue's own Trigger A cascade, so they are deliberately out of scope here.
  • Two adjacent defects found while investigating, not fixed here to keep this single-topic — happy to file or fix separately:
    1. hasWorktreeSleepIntent is only set when sleeping the active workspace (sleep-worktree-flow.ts), so sleeping a background workspace lets its PTY exits reach bumpWorktreeActivity — a workspace registers activity at the moment it is slept.
    2. The startup reconnect fallback in store/slices/terminals.ts uses session.activeWorktreeIdsOnShutdown ?? …tabs.some(t => t.ptyId). The primary writer in lib/workspace-session.ts explicitly avoids tab.ptyId with the comment "which sleep preserves as a wake hint and would revive slept worktrees as active", but the fallback uses exactly that — so a session missing that field (older build, or a crash before the write) revives every slept workspace on next launch.

…orkspace

Sleeping a workspace kills its PTYs but deliberately keeps `tab.ptyId` as a
wake hint. `planMobileTerminalTabMount` only checked that the handle resolved
to a real tab, so a phone/web client calling `terminal.subscribe` made the
desktop background-mount that pane and bring a PTY back up — reviving the
workspace with no user activation and no navigation.

Fail closed when the workspace holds no live PTY and nothing is queued to
spawn, so a mount could only create a PTY rather than attach one.
`terminal.subscribe` already falls back to a scrollback-only stream when no
PTY appears, so the client still gets the saved output.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016Si2MAXbpmvDM3qBihjoTy
@greptile-apps

greptile-apps Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a bug where a mobile or web client calling terminal.subscribe on a sleeping workspace's terminal could revive the workspace on the desktop without any user action. Sleep deliberately retains tab.ptyId as a wake hint, and the planner previously checked only that the tab handle resolved — not whether any PTY was actually alive.

  • Adds worktreeHasNoResumableTerminal, a predicate that returns true only when every tab in the workspace lacks a live PTY (ptyIdsByTabId), a queued startup (pendingStartupByTabId), and a pending activation spawn — and gates planMobileTerminalTabMount on this check before any further planning occurs.
  • Adds six new test cases covering the blocked paths (slept workspace via real-tab id, synthetic pty handle, and pre-mount-state short-circuit) and the three allowed paths (another tab still live, fresh terminal.create startup pending, activation spawn pending).

Confidence Score: 5/5

Safe to merge — the change is a pure read-only predicate that strictly narrows what remote clients can trigger, and the three escape hatches preserve every legitimate mount path.

The guard correctly distinguishes a slept workspace (empty ptyIdsByTabId) from an awake one without touching tab.ptyId (the sleep-preserving hint that caused the original bug). All three escape hatches are logically sound and each has a dedicated test. No IPC shape, rendering, or store mutation is changed.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
src/renderer/src/lib/mobile-terminal-tab-mount.ts Adds worktreeHasNoResumableTerminal guard before any mount planning; correctly uses ptyIdsByTabId (live-PTY source of truth) rather than tab.ptyId (sleep-preserving hint). All three escape hatches (live PTY on any tab, pending startup, pending activation spawn) are sound and tested.
src/renderer/src/lib/mobile-terminal-tab-mount.test.ts Six new test cases added — three blocking paths and three allowed paths — using well-named state / sleptState helpers that accurately mirror the runtime distinction between live and slept workspaces.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[terminal.subscribe from mobile/web client] --> B{request.worktreeId?}
    B -- No --> Z1[return null]
    B -- Yes --> C{worktreeHasNoResumableTerminal?}
    C -- checks every tab --> D{"ptyIdsByTabId empty AND\npendingStartupByTabId empty AND\n!pendingActivationSpawn"}
    D -- all tabs satisfy --> E[return true — slept workspace]
    D -- any tab fails --> F[return false — awake workspace]
    E --> Z2[return null — no revival]
    F --> G{tabId provided?}
    G -- Yes --> H{tab exists in workspace?}
    H -- No --> Z3[return null]
    H -- Yes --> I[tabId = request.tabId]
    G -- No --> J{ptyId provided?}
    J -- Yes --> K[resolveTerminalTabIdForPtyId]
    K --> L{unique owner found?}
    L -- No --> Z4[return null]
    L -- Yes --> I
    J -- No --> Z5[return null]
    I --> M{isTabMounted?}
    M -- Yes --> Z6[return null]
    M -- No --> N[return BackgroundMountTerminalWorktreeDetail]
Loading

Reviews (2): Last reviewed commit: "refactor: condense mount guard rationale..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: bd412753-94ae-4769-991f-7ffdbfbfbb17

📥 Commits

Reviewing files that changed from the base of the PR and between c5d0e2e and 0f55816.

📒 Files selected for processing (1)
  • src/renderer/src/lib/mobile-terminal-tab-mount.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/lib/mobile-terminal-tab-mount.ts

📝 Walkthrough

Walkthrough

planMobileTerminalTabMount now checks for live PTYs or pending startup and activation state before planning a mobile terminal mount. Slept workspaces return null when no resumable terminal state exists, including requests using real-tab or synthetic PTY handles. Tests add fixtures and coverage for these cases, plus scenarios where another live tab or pending startup or activation state permits mounting.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main fix to stop slept workspaces from being revived by mobile terminal subscriptions.
Description check ✅ Passed The description includes all required sections and enough detail for summary, testing, review, security, and notes.
Linked Issues check ✅ Passed The PR fixes #10205's mobile terminal subscribe wake path and preserves legitimate mount cases; the broader logging question is intentionally out of scope.
Out of Scope Changes check ✅ Passed The changes stay focused on the mount planner and tests, with no unrelated code paths or extra features introduced.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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 (1)
src/renderer/src/lib/mobile-terminal-tab-mount.ts (1)

15-24: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Condense this rationale comment.

The full behavior explanation is useful but overly long for an inline source comment; retain the essential invariant and issue reference.

Suggested simplification
-/**
- * True when mounting this tab could only *create* a PTY rather than attach one:
- * the workspace holds no live PTY and nothing is queued to spawn.
- *
- * Why: sleeping a workspace kills its PTYs but keeps `tab.ptyId` as a wake hint,
- * so a mobile subscribe could mount the pane and bring the workspace back to life
- * on the desktop with no user activation (`#10205`). `terminal.subscribe` already
- * degrades to a scrollback-only stream when no PTY appears, so failing closed here
- * still serves the saved output — it just stops resurrecting a slept workspace.
- */
+/** Prevent mobile subscriptions from reviving slept workspaces (`#10205`). */

As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 97a044aa-9d1a-4e3a-b59d-516fcbb207d0

📥 Commits

Reviewing files that changed from the base of the PR and between 4543bb6 and c5d0e2e.

📒 Files selected for processing (2)
  • src/renderer/src/lib/mobile-terminal-tab-mount.test.ts
  • src/renderer/src/lib/mobile-terminal-tab-mount.ts

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016Si2MAXbpmvDM3qBihjoTy
@mmarabel

mmarabel commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

Closing this — it targets a path that is not the cause, and the path it does touch has since been fixed upstream.

Two things came out of a deeper investigation of #10205:

  1. The mobile-subscribe path was fixed properly in fix(runtime): refuse to silently wake a deliberately slept pane (STA-3465) #12672 (STA-3465). That change carries activation intent explicitly via TabActivationIntent and refuses the automatic reconnect probe from fix(remote-runtime): materialize the host surface when reconnecting a terminal pane #11542, which is the actual mechanism by which a client could respawn a slept pane. It is a better fix than the fail-closed planner guard here, and it is already in 1.4.177.

  2. The wake I was chasing is not a client path at all. The daemon log for both captures shows no client-hello before the respawn — the spawn comes from the already-connected desktop renderer in the same tick as the activation. The cause is the renderer pane-connect path: a slept workspace's pane stays mounted and its deferred connect falls through to a fresh spawn. Fixed in fix(terminal): keep a deliberately slept workspace from respawning its PTY #13343 with the captured caller.

Thanks for the patience on this one — the original premise was wrong and I would rather withdraw it than have it reviewed on that basis.

@mmarabel mmarabel closed this Aug 9, 2026
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.

[Bug]: Sleeping workspaces revive without user activation — hard to diagnose (open question on opt-in lifecycle logging)

3 participants