Skip to content

fix(sleep): reopen a slept agent whose tab is gone in a fresh tab instead of stranding it - #33598

Merged
nwparker merged 1 commit into
mainfrom
nwparker/agint-sleep-wake-record-lifecycle
Oct 25, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/agint-sleep-wake-record-lifecycle

Conversation

@nwparker

@nwparker nwparker commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​117 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​114
Prod 11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​105 $\color{#cf222e}{\Huge{\mathbf{−}}}$​15 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​90

Summary (ELI5)

When you put a workspace to sleep, Orca saves a note for each agent ("resume Claude session X in tab T"). On wake, Orca resumes the agent when tab T opens. If tab T has disappeared by then, nothing ever opens it. The note just sits there, the workspace opens a plain new tab, and your conversation is never resumed. With this change Orca reopens that agent in a fresh tab with --resume, then throws the note away.

Root cause

Since #31564, main captures workspace-sleep records (origin: 'worktree-sleep', state: 'done', restoreOnTabOpenOnly: true). Main resumes them only when their own pane opens (main-resumed-sleep-pane.ts → worktrees:resumeSleptPane). The window's activation sweep skips every such record (!isWorkspaceSleepRecord(record) in resumeSleepingAgentSessionsForWorktree). window-save-sleep-records.ts keeps main's copy through every window save. So a record whose tab is gone is never resumed by anyone, and it is never cleared. Before #31564 the window sweep deleted it instead (the original report). On current main it is stranded rather than deleted, and the user-visible result is the same: a new tab with no resume.

What changed

  • isStrandedWorkspaceSleepRecord (in sleeping-agent-pane-ownership.ts) matches a workspace-sleep record when no tab in any workspace still lists its tab id.
  • The activation sweep and the phone background wake now include stranded records. The sweep treats them as active, not as passive history, and passes them through all the existing guards (host authority, host mirrors, claim dedupe, provider session owned elsewhere). It then launches them with the existing launchSleepingAgentSession, which opens a fresh tab, uses the captured launch config, and shows the "session restored" banner.
  • When the sweep settles a stranded record (resumed or deduped), it calls a new IPC, worktrees:retireStrandedSleepRecord. Main removes its copy only if the record is still a workspace-sleep record and its partition still lists no tab for the pane (dropStrandedSleepRecord). This stops a duplicate --resume on the next restart. A placed record can never be dropped this way.
  • Placed records are unchanged: main still resumes them in their own pane.

Upstream reference: Claude Code resumes from the transcript by id (claude --resume <session_id>). The fake model server below received the earlier turns in the resumed request.

How verified

Isolated dev Electron (ORCA_DEV_USER_DATA_PATH=/tmp/...), real Claude Code 2.1.310 with an isolated CLAUDE_CONFIG_DIR, and a local fake Anthropic server.

Repro on main (a944e37):

  1. Started claude in a tab, sent "remember the word PINEAPPLE", and waited for it to finish (done).
  2. Slept the workspace from the sidebar menu. Main's record was origin: worktree-sleep, state: done, restoreOnTabOpenOnly: true, matching the report.
  3. Quit Orca, removed the tab, its unified tab and its layout from workspaceSession (the report's step 3), and restarted.
  4. Clicked the workspace. Result: a plain shell tab, no claude, and no request to the model server. Main's record was still in the session, stranded, with nothing able to resume it.

With this branch, same state:

  • Clicking the workspace opened a Claude Code tab with the "session restored" banner and the PINEAPPLE turn in it. Main's stranded record was gone, replaced by the new pane's live record.
  • Then I sent "what word?". The fake server got msgs=5, so the resumed conversation carried its history.
  • After a full restart, the workspace still had one tab and no duplicate resume.
  • Regression check: a normal Sleep → wake with the tab present still resumed in the original pane (same tab id, one tab).
  • Closing a slept tab removed its record from both the window and main. Nothing came back after that.

Tests: pnpm tc, the sleep/resume/wake suites (52 files, 502 tests), and check:code-quality:changed. The new regression test fails on main.

Risk

  • The behavior change is limited to workspace-sleep records whose tab no longer exists anywhere. Before this PR they did nothing. Now they reopen as a fresh resume tab when the workspace is activated, just as quit and live records already do.
  • Main refuses to drop a record whose tab is still listed. A stale window cannot discard an in-pane resume.
  • Layout-owner (dark) builds: main's carried unplaced records go through the same sweep and IPC. Not separately exercised.
  • Remote: paired-runtime records are still parked or skipped by the existing host-authority and mirror guards. SSH records live in the repo host partition, which the IPC resolves via getWorkspaceSessionHostIdForWorktree. Web client: no-op stub.

Fixes #22657

…tead of stranding it

Main resumes a workspace sleep's agents only when their own pane opens, so a
record whose tab had disappeared was never resumed: activation opened a plain
default tab and the record sat in main's session forever. The window's
activation sweep now resumes such a stranded record in a fresh tab with
--resume and asks main to drop its copy; main drops it only while no tab
lists the pane, so placed records keep their in-pane resume.

Fixes #22657
@coderabbitai

coderabbitai Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Walkthrough

The change detects workspace-sleep records whose tabs no longer have preserved owners. The resume sweep can resume these records and retire them through a new worktree IPC and runtime operation. The background wake flow also includes stranded records. Tests cover record removal conditions, resumption, and retention when a tab remains.

Priority: Normal

Severity of issue fixed: Medium

Merge Risk: Moderate · up to 8be37

The change recovers sessions whose tab is gone, but a session whose status was stale at sleep time can lose its resume handle instead of being resumed. A failed retirement request can also let the same session resume twice on a later wake. Resolve the stale-status handling before merging.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 14 functions across 16 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly describes the main change: reopening a slept agent in a fresh tab when its original tab is missing.
Description check Passed The description is mostly complete. It explains the user impact, root cause, implementation, linked issue, testing, regression coverage, and risks. It does not include the template's Visual Proof, Rev…
Linked Issues check Passed Linked issue #22657 is the only direct target. Its requested outcome is that a finished Claude session's workspace-sleep record, whose tab is gone on wake, is not silently deleted and is resumed in a …
Out of Scope Changes check Passed All changed files support the stranded-record recovery for #22657. isStrandedWorkspaceSleepRecord and the sweep filter in resume-sleeping-agent-session.ts define the recovered set. `settleSweptRec…
Full details: Description check

Explanation

The description is mostly complete. It explains the user impact, root cause, implementation, linked issue, testing, regression coverage, and risks. It does not include the template's Visual Proof, Review, Notes, or Checklist sections, but the core required context is present.

Full details: Linked Issues check

Explanation

Linked issue #22657 is the only direct target. Its requested outcome is that a finished Claude session's workspace-sleep record, whose tab is gone on wake, is not silently deleted and is resumed in a fresh tab. The head source confirms the implementation. In sleeping-agent-pane-ownership.ts, isStrandedWorkspaceSleepRecord returns true for a isWorkspaceSleepRecord record whose tab id is absent from every tabsByWorktree list. In resume-sleeping-agent-session.ts, resumeSleepingAgentSessionsForWorktree now admits a workspace-sleep record only when it is stranded. Placed records are still excluded, so main keeps resuming them in their own pane. A stranded record has no preserved owner, so it reaches launchSleepingAgentSession after the existing host-authority, mirror, claim-dedupe, and provider-ownership guards. On success it is settled. This matches the issue's first suggested fix, resuming into a fresh tab instead of deleting. The issue's 'at minimum' notice is not needed because the restore path is implemented. The issue's separate item, investigating why the slept workspace's tab list became empty, is excluded by the PR objectives as separate work and is not a coding requirement of this PR. Limitation: the diff tool returned no text, so swept-sleep-record-settlement.ts and the main-side dropStrandedSleepRecord path were assessed from the supplied summary, not from source. The author's reported reproduction and tests are not independently verified here.

Full details: Out of Scope Changes check

Explanation

All changed files support the stranded-record recovery for #22657. isStrandedWorkspaceSleepRecord and the sweep filter in resume-sleeping-agent-session.ts define the recovered set. settleSweptRecord and sweepTreatsAsFinished in swept-sleep-record-settlement.ts settle the record after launch or dedupe. The new worktrees:retireStrandedSleepRecord channel is wired through worktrees.ts, register-worktree-sleep-handlers.ts, managed-workspace-operations.ts, preload worktree-api.ts and worktrees-bridge.ts, and the web no-op stub. It prevents a duplicate resume on restart. dropStrandedSleepRecord in worktree-sleep-resume-records.ts removes a record only when its tab is absent from every workspace, so it cannot remove a placed record. wake-sleeping-agents-in-background.ts uses the same stranded predicate for phone wake. The test changes cover the stranded path, the retained placed-tab path, and the main-side drop rules. No change addresses unrelated behavior. The head source read for the sweep and predicate matches the summary.

Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

🔇 Additional comments: 1
src/main/runtime/workspaces/managed-workspace-operations.ts-273-273: 1

273-273: Major · Data Integrity & Integration · Quick win

⚠️ Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.

Verify the record belongs to worktreeId before deleting it.

If two worktrees share a session host, an IPC request can select one worktree and supply a stranded pane key belonging to the other. dropStrandedSleepRecord checks the pane key and tab list, but not record.worktreeId. Main can therefore delete the other worktree’s resume handle. Pass worktreeId into the helper and require record.worktreeId === worktreeId before removal. Based on learnings, renderer arguments that affect privileged main-process behavior require validation at the IPC boundary.

Source: Learnings


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 53284d47-76e8-4b70-a4b6-cab10ae871a0
Commits

Reviewing files that changed from the base of the PR and between 038805f and 8be37f2.

Files selected for processing: 16
  • src/main/ipc/worktrees-create-metadata-persistence.test.ts
  • src/main/ipc/worktrees.ts
  • src/main/ipc/worktrees/sleep/register-worktree-sleep-handlers.ts
  • src/main/runtime/terminal/stop/worktree-sleep-resume-records.test.ts
  • src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts
  • src/main/runtime/workspaces/managed-workspace-operations.ts
  • src/preload/api/worktree-api.ts
  • src/preload/api/worktrees-bridge.ts
  • src/renderer/src/lib/resume-sleeping-agent-session-stranded-sleep.test.ts
  • src/renderer/src/lib/resume-sleeping-agent-session.test.ts
  • src/renderer/src/lib/resume-sleeping-agent-session.ts
  • src/renderer/src/lib/sleeping-agent-pane-ownership.ts
  • src/renderer/src/lib/swept-sleep-record-settlement.ts
  • src/renderer/src/lib/wake-sleeping-agents-in-background.test.ts
  • src/renderer/src/lib/wake-sleeping-agents-in-background.ts
  • src/renderer/src/web/preload-api/web-worktrees-api.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

}
if (isInvalidWorktreeActivationRecord(record)) {
state.clearSleepingAgentSession(record.paneKey)
settleSweptRecord(record)

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.

Major · Data Integrity & Integration · Quick win

Preserve a stranded sleep record when its status is stale.

If an unfinished agent last updated more than 30 minutes before sleep capture, isInvalidWorktreeActivationRecord returns true. The new selection includes its stranded workspace-sleep record, and this branch now clears the renderer record and requests deletion from main without attempting recovery. A stale status does not establish that the provider session cannot resume. Keep the resume handle or report a recovery failure instead of retiring it on this age check.

Comment on lines +18 to +21
void Promise.resolve()
.then(() => window.api.worktrees.retireStrandedSleepRecord({ worktreeId, paneKey }))
.catch((error: unknown) =>
console.warn('[sleep-resume] could not retire a stranded sleep record', error)

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.

Major · Data Integrity & Integration · Heavy lift

🔎 Supported by static analysis

Script executed:

#!/bin/bash
# Inspect the session write and restore paths for both processes.
rg -n -C 4 'commitWorkspaceSessionEdit|clearSleepingAgentSession\s*\(|sleepingAgentSessionsByPaneKey|retireStrandedSleepRecord' src/main/runtime src/renderer/src/store src/renderer/src/lib

Repository: stablyai/orca

Length of output: 45667


Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- changed helper ---'
nl -ba src/renderer/src/lib/swept-sleep-record-settlement.ts | sed -n '1,120p'
printf '%s\n' '--- IPC symbol references ---'
rg -n -F --glob '*.{ts,tsx}' 'retireStrandedSleepRecord' src | head -80
printf '%s\n' '--- main session persistence symbols ---'
rg -n -F --glob '*.ts' -e 'clearSleepingAgentSession' -e 'sleepingAgentSessionsByPaneKey' -e 'commitWorkspaceSessionEdit' src/main src/renderer/src/store src/renderer/src/lib | head -180

Repository: stablyai/orca

Length of output: 26928


Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- main retirement method ---'
nl -ba src/main/runtime/workspaces/managed-workspace-operations.ts | sed -n '225,290p'
printf '%s\n' '--- commitWorkspaceSessionEdit declarations and callers ---'
rg -n -F --glob '*.ts' 'commitWorkspaceSessionEdit' src/main | head -80
printf '%s\n' '--- session save handling for sleep records ---'
nl -ba src/main/persistence/window-save-sleep-records.ts 2>/dev/null | sed -n '1,180p' || true
nl -ba src/main/persistence/window-save-divergence.ts 2>/dev/null | sed -n '1,180p' || true
printf '%s\n' '--- handler binding ---'
nl -ba src/main/ipc/worktrees/sleep/register-worktree-sleep-handlers.ts | sed -n '25,55p'

Repository: stablyai/orca

Length of output: 15188


Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- commit implementation ---'
nl -ba src/main/runtime/terminal/stop/worktree-terminal-stop.ts | sed -n '95,155p'
printf '%s\n' '--- drop helper definition and uses ---'
rg -n -F --glob '*.ts' 'dropStrandedSleepRecord'
printf '%s\n' '--- drop helper source context ---'
file=$(rg -l -F --glob '*.ts' 'function dropStrandedSleepRecord' src | head -1)
test -n "$file"
rg -n -C 12 -F -- 'function dropStrandedSleepRecord' "$file"

Repository: stablyai/orca

Length of output: 5315


Script executed:

#!/bin/bash
set -eu
nl -ba src/main/runtime/terminal/stop/worktree-terminal-stop.ts | sed -n '110,145p'
rg -n -C 10 -F --glob '*.ts' 'function dropStrandedSleepRecord' src

Repository: stablyai/orca

Length of output: 4065


Keep retirement recoverable when the IPC request fails.

If retireStrandedSleepRecord rejects before dropStrandedSleepRecord durably removes the main record, settleSweptRecord has already cleared the renderer record. The catch only logs the error. The main-owned record can remain available to a later wake sweep, which may resume the same provider session again. Preserve a retryable retirement intent or reconcile the main record before settlement completes.

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]: Waking a slept workspace silently deletes a finished Claude session's resume record when its tab is missing

1 participant