Skip to content

fix(terminal): launch prior/default agent when a woken terminal can't resume - #6277

Merged
Jinwoo-H merged 3 commits into
stablyai:mainfrom
mmarabel:fix/wake-sleeping-default-agent
Jul 5, 2026
Merged

Jinwoo-H merged 3 commits into
stablyai:mainfrom
mmarabel:fix/wake-sleeping-default-agent

Conversation

@mmarabel

@mmarabel mmarabel commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Waking a sleeping worktree — or restoring terminals after an app restart — left a terminal that previously ran an agent as a blank shell while the tab still showed the agent's icon/title. You had to manually re-run claude/codex to get going.

Root cause: in pty-connection.ts, buildColdRestoreAgentResumeStartup() returns null whenever the agent's provider session can't be resumed (no provider session, or the resume plan can't be built). The caller then spawns a bare shell, and nothing clears the tab's launchAgent, so the stale agent icon remains.

This change adds a fresh-launch fallback at exactly those null points. When resume isn't possible, an agent terminal now comes back as a fresh session (no --resume) of the agent it previously ran, resolved in priority order:

  1. live agent status (agentType), else
  2. the sleeping record's agent, else
  3. the terminal's persisted tab.launchAgent (the durable signal across restarts), else
  4. the pane's startup launchAgent.

If the prior agent is unknown but there's evidence the terminal was an agent terminal (a live status entry or sleeping record exists), the configured default agent is used — exactly like opening a new terminal. A genuine plain shell (no agent ever ran there, no default trigger) stays blank. No context is carried over (a clean session), and the correct agent icon is restored because the fresh startup flows through the existing cold-restore path that sets launchAgent.

Fixes #4557

Screenshots

Waking a slept agent terminal — before vs after (PII redacted):

wake-terminal-before-after.mp4
  • Before: the woken terminal comes up as a blank shell (with a stale agent icon).
  • After: it relaunches the agent it previously ran; a plain shell still wakes blank.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test — pty-connection.test.ts passes (193 incl. 4 new cases). The only full-suite failures are pre-existing, environment-only flakes unrelated to this change (src/relay/git-handler.test.ts, src/relay/subprocess.test.ts — they pass in isolation and flake under parallel load; they also fail on a clean upstream/main).
  • pnpm build
  • Added regression tests: unresumable sleeping record → fresh agent; persisted tab.launchAgent → fresh prior agent after restart; agent terminal with unrecoverable agent → default agent; plain shell stays blank.

AI Review Report

Ran an adversarial review of the diff. Risks checked and outcomes:

  • Forcing an agent into a plain shell / new terminal — verified safe: the pendingStartupCommand guard returns null for any launch that already carries a startup command; the default-agent fallback only fires when a live entry or sleeping record exists; a brand-new blank terminal has none of those (even with a default agent configured), so it stays blank. New-terminal creation does not route through this builder.
  • Resume behavior unchanged — the fallback is only reached at the three sites that previously returned null; the successful-resume branch is untouched (existing resume tests pass).
  • Cross-platform (macOS/Linux/Windows + WSL) — the fresh launch uses the same getColdRestoreAgentResumePlatform() and buildAgentStartupPlan (same shell resolution/quoting) as the resume path; empty prompt avoids quoting risk; WSL→linux mapping is identical. No shortcuts/labels/paths touched.
  • SSH/remote — parity confirmed: the fresh startup object has the same shape as the resume object and is delivered through the existing SSH cold-restore mechanism; no SSH-specific code change.
  • Type widening — ColdRestoreAgentResumeStartup.agent widened from ResumableTuiAgent to TuiAgent (a fresh launch can target a non-resumable agent). All consumers accept TuiAgent (registerAgentLaunchConfig metadata is AgentType; launchAgent fields are TuiAgent).
  • Hardened clearSleepingRecordProviderDuplicates to tolerate a record without a providerSession (now reachable via the fresh-launch path).

Security Audit

  • Command execution — the fresh launch command is built by the same buildAgentStartupPlan used for new terminals; no user-derived strings are interpolated unquoted (empty prompt), and args/env come from the existing settings-resolution helpers.
  • No new IPC surface, secrets, auth, path handling, or dependency changes.

Notes

  • Behavior is gated so plain shells and blank new terminals are never converted into agents.
  • The fresh launch starts a clean session (no transcript continuation), matching the agreed behavior.

… resume

Waking a sleeping worktree (or restoring terminals after an app restart)
left an agent terminal as a BLANK shell while still showing the agent's
icon: `buildColdRestoreAgentResumeStartup` returned null whenever the
provider session couldn't be resumed, and the caller then spawned a bare
shell.

Now, when resume isn't possible, an agent terminal comes back as a FRESH
session of the agent it previously ran (live status -> sleeping record ->
persisted tab `launchAgent`); if that agent is unknown but the terminal was
an agent terminal, the configured default agent is used. A genuine plain
shell stays blank, and the existing resume path, SSH/remote, and WSL
behavior are unchanged.

Fixes stablyai#4557

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 24, 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

Run ID: 5cd65984-1a5f-49e0-b010-106c07e745e7

📥 Commits

Reviewing files that changed from the base of the PR and between 0907fd3 and d2d1a43.

📒 Files selected for processing (2)
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/components/terminal-pane/pty-connection.ts

📝 Walkthrough

Walkthrough

The pull request updates cold-restore handling in pty-connection.ts so unresumable or otherwise unstartable TUI agent sessions can fall back to a fresh startup plan. It widens the cold-restore agent type, normalizes provider-session handling for sleeping records, adds SSH remote-platform resolution, and introduces buildFreshFallback() to choose a replacement agent from live, sleeping, tab, or default sources. The test file adds mock typing support and new cold-restore cases covering fallback, restore, and blank-shell outcomes.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main fix: waking a terminal now launches the prior or default agent when resume fails.
Description check ✅ Passed The description includes all required sections with concrete testing, screenshots, review, security, and notes, and is mostly complete.
Linked Issues check ✅ Passed The PR matches #4557 by relaunching an agent on wake, using the default agent when needed, and leaving plain shells blank.
Out of Scope Changes check ✅ Passed The code and tests stay focused on cold-restore agent fallback and regression coverage, with no obvious unrelated changes.

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: 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/components/terminal-pane/pty-connection.ts (1)

870-879: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Guard every providerSession dereference, not just duplicate clearing.

Lines 903-915 handle records without providerSession, but Line 875 and Line 2287 still dereference it directly. A no-provider sleeping record can still crash terminal restore before the fresh fallback runs.

Potential fix
-    const providerSessionKeys = new Set(
-      legacyMatches.map(([, record]) =>
-        [
-          record.worktreeId,
-          record.agent,
-          record.providerSession.key,
-          record.providerSession.id
-        ].join('\0')
-      )
-    )
+    const providerSessionKeys = new Set(
+      legacyMatches
+        .map(([, record]) => {
+          const session = record.providerSession
+          return session
+            ? [record.worktreeId, record.agent, session.key, session.id].join('\0')
+            : null
+        })
+        .filter((key): key is string => key !== null)
+    )
+    const allLegacyMatchesHaveProviderSession = legacyMatches.every(
+      ([, record]) => Boolean(record.providerSession)
+    )
@@
-      (providerSessionKeys.size === 1
+      (allLegacyMatchesHaveProviderSession && providerSessionKeys.size === 1
         ? legacyMatches.length === 1
           ? legacyMatches[0]
           : oldestLegacyMatch
         : null)
@@
       const matchingSleepingLaunchConfig =
         sleepingRecord?.launchConfig &&
         (!useLiveEntry ||
           (sleepingRecord.agent === agent &&
-            sleepingRecord.providerSession.key === providerSession.key &&
-            sleepingRecord.providerSession.id === providerSession.id))
+            sleepingRecord.providerSession?.key === providerSession.key &&
+            sleepingRecord.providerSession?.id === providerSession.id))
           ? sleepingRecord.launchConfig
           : undefined

Also applies to: 903-915, 2283-2289


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 7ade0368-bdd4-4b35-a3ca-623ef7a06e89

📥 Commits

Reviewing files that changed from the base of the PR and between 7369c4c and 231db84.

📒 Files selected for processing (2)
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts

@mmarabel

Copy link
Copy Markdown
Contributor Author

walkthrough

wake-terminal-before-after.mp4

mmarabel and others added 2 commits June 24, 2026 21:43
…ume) launch

Addresses CodeRabbit review on stablyai#6277.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

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

Thanks for the fix. I added a small maintainer follow-up to cover the cold-restore edge cases:

  • Fresh fallback ignores stale completed live rows.
  • Stored launch config/env is preserved when relaunching the agent.
  • SSH fallback uses the known remote platform.
  • Malformed sleeping records are handled defensively.

Validated with focused terminal-pane tests, typecheck, lint, and Electron smoke coverage.

@Jinwoo-H
Jinwoo-H merged commit 85d555f into stablyai:main Jul 5, 2026
1 of 2 checks passed
Jinwoo-H added a commit that referenced this pull request Jul 5, 2026
Re-based onto the current shared remote tip (4110c29, which already
carried an older main sync + windows-update-daemon-adoption); this brings
in the 18 newer main commits through v1.4.124-rc.1. MERGE, not rebase.

Conflict resolutions (our structure wins; main's semantics graft in):

- update-check feature (update-check-click-options.ts + test,
  GeneralUpdateSettingsSection.tsx, SidebarSettingsHelpMenu.tsx + test,
  updater.ts + test): took main's shape — getUpdateCheckHint() centralizes
  the RC/perf hint, pointerdown modifier-capture handler, and the refined
  `checkVariant === 'prerelease'` guard so a perf check never permanently
  opts background retries into the RC channel. getUpdateCheckClickOptions
  (the actual behavior) was byte-identical on both sides.

- Ctrl+K clear vs producer flow control (pty-subprocess.ts, session.ts,
  session.test.ts): kept BOTH — our pause()/resume() flow-control methods
  AND main's clear() ConPTY screen-state resync (#7413). Orthogonal.

- orca-runtime.ts: took main's public visibility on
  clearHeadlessTerminalBuffer (ipc/pty.ts Ctrl+K path calls it); dropped
  main's createHeadlessEmulator factory — our Phase-5 query-authority
  emulator construction is restructured and has no caller for it.

Incoming (auto-merged, off the byte-delivery path): #6277 agent cold-
restore fallback (pty-connection.ts), node-pty ConPTY relocation (#7421),
MiniMax rate limits, translations.

Gates: typecheck 0 errors; ipc+daemon+terminal-pane+pane-manager 4204
passed; both fuzz suites pass; hand-resolved renderer files pass. No
delivery/restore/flow-control/ACK/batching/scheduler bytes changed, so no
10MB bench required.

Co-authored-by: Orca <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… resume (stablyai#6277)

* fix(terminal): launch prior/default agent when a woken terminal can't resume

Waking a sleeping worktree (or restoring terminals after an app restart)
left an agent terminal as a BLANK shell while still showing the agent's
icon: `buildColdRestoreAgentResumeStartup` returned null whenever the
provider session couldn't be resumed, and the caller then spawned a bare
shell.

Now, when resume isn't possible, an agent terminal comes back as a FRESH
session of the agent it previously ran (live status -> sleeping record ->
persisted tab `launchAgent`); if that agent is unknown but the terminal was
an agent terminal, the configured default agent is used. A genuine plain
shell stays blank, and the existing resume path, SSH/remote, and WSL
behavior are unchanged.

Fixes stablyai#4557

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* test(terminal): assert default-agent cold restore is a fresh (non-resume) launch

Addresses CodeRabbit review on stablyai#6277.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* Fix cold restore agent fallback

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: Jinwoo-H <[email protected]>
Co-authored-by: Orca <[email protected]>
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]: Awaking sleeping session does not start agent automatically

2 participants