Repository navigation
fix(agents): verify a sleeping session's tab is gone from every session partition before resuming into a fresh tab - #13037
Conversation
📝 WalkthroughWalkthroughThe change adds asynchronous rescue for stranded sleeping-agent sessions. The resume flow checks live and persisted worktree partitions, remote hydration, SSH snapshot application, ownership, and duplicate provider sessions before launching a rescue. Per-worktree rescue counts now coordinate background tab mounting, initial terminal creation, and deferred command delivery. Tests cover asynchronous replay, persisted-tab detection, rescue cleanup, background mounting, worktree reactivation, command delivery, and explicit startup payloads. Merge Risk: 🟡 Moderate · up to The change prevents duplicate session resumes, but configured default tabs may not be created when a worktree contains a persisted empty tab entry, and rescue gating depends on consistent state wiring and reconciled tab data. These bounded correctness issues should be addressed or explicitly accepted before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
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.
Actionable comments posted: 2
🧹 Nitpick comments (2)
src/renderer/src/lib/resume-sleeping-agent-session.test.ts (1)
945-993: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winWait on the rescue ref-count instead of draining microtasks manually.
Both tests assert a negative (the record is retained, no tab was created) after
await Promise.resolve()twice. The number of microtask ticks between theget()call and the end of the rescue is an implementation detail ofqueueStrandedSleepingAgentRescue. If a future change adds one moreawaitin that path, these assertions run before the rescue finishes and pass without testing anything.
strandedSleepingAgentRescuesByWorktreeIddrops to zero exactly when the rescue completes, so it is a stable completion signal. The sibling suite already uses it insrc/renderer/src/lib/worktree-reactivation-tab-forkbomb.test.tsLines 156-160.♻️ Proposed change for both tests
const launched = resumeSleepingAgentSessionsForWorktree('wt-1') - await vi.waitFor(() => expect(get).toHaveBeenCalled()) - await Promise.resolve() - await Promise.resolve() + await vi.waitFor(() => { + expect(useAppStore.getState().strandedSleepingAgentRescuesByWorktreeId['wt-1'] ?? 0).toBe(0) + }) expect(launched).toBe(0) const state = useAppStore.getState() expect(state.sleepingAgentSessionsByPaneKey[record.paneKey]).toBe(record) expect(state.tabsByWorktree['wt-1'].map((tab) => tab.id)).toEqual(['tab-1'])src/renderer/src/lib/worktree-activation.ts (1)
503-526: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueExtract the repeated first-tab command-queueing block.
The gate logic and the deferral condition are correct. The
queueHookCommandsForFirstWorktreeTabcall at Lines 509-523 is identical to the web-runtime block at Lines 478-492, including the argument order passed toqueueSetupAndIssueCommands. Two identical copies in one function will drift when thequeueSetupAndIssueCommandssignature changes.Extract a local closure and call it from both branches.
♻️ Proposed extraction
+ const holdCommandsForFirstTab = (): void => { + if (!setup && !issueCommand) { + return + } + queueHookCommandsForFirstWorktreeTab({ + worktreeId, + deliver: (state, firstTerminalTabId) => + queueSetupAndIssueCommands( + state, + worktreeId, + firstTerminalTabId, + setup, + issueCommand, + wrappedSetupCommandStr, + opts + ) + }) + }Then both branches become:
- if (setup || issueCommand) { - // Why: the pending rescue resolves to either the rescued tab or a post-rescue placeholder; hold commands for whichever tab lands first instead of dropping them. - queueHookCommandsForFirstWorktreeTab({ - worktreeId, - deliver: (state, firstTerminalTabId) => - queueSetupAndIssueCommands( - state, - worktreeId, - firstTerminalTabId, - setup, - issueCommand, - wrappedSetupCommandStr, - opts - ) - }) - } + // Why: the pending rescue resolves to either the rescued tab or a post-rescue placeholder; hold commands for whichever tab lands first instead of dropping them. + holdCommandsForFirstTab() return null
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 1339bb03-986e-4a83-abff-a86b006c8d24
📥 Commits
Reviewing files that changed from the base of the PR and between 02a1251 and 855808e00252a5e381480a6302ed0ea0c92f5851.
📒 Files selected for processing (9)
src/renderer/src/components/Terminal.tsxsrc/renderer/src/lib/resume-sleeping-agent-session-replay.test.tssrc/renderer/src/lib/resume-sleeping-agent-session.test.tssrc/renderer/src/lib/resume-sleeping-agent-session.tssrc/renderer/src/lib/wake-sleeping-agents-in-background-stranded-rescue.test.tssrc/renderer/src/lib/wake-sleeping-agents-in-background.tssrc/renderer/src/lib/worktree-activation.tssrc/renderer/src/lib/worktree-reactivation-tab-forkbomb.test.tssrc/renderer/src/store/slices/agent-status.ts
| if (isDirectSshRemoteWorkspaceApplyInProgress()) { | ||
| return | ||
| } | ||
| const state = useAppStore.getState() | ||
| const connectionId = getConnectionIdFromState(state, record.worktreeId) | ||
| if (connectionId && !state.remoteWorkspaceHydratedTargetIds.has(connectionId)) { | ||
| return | ||
| } | ||
| const partitions: WorkspaceSessionState[] = [] | ||
| try { | ||
| partitions.push(await window.api.session.get()) | ||
| if (connectionId) { | ||
| partitions.push(await window.api.session.get(toSshExecutionHostId(connectionId))) | ||
| } | ||
| } catch { | ||
| // Why: an unreadable partition cannot prove the tab is gone; resuming | ||
| // on failure is the duplicate-session direction. | ||
| return | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Add a timeout to the partition reads that gate tab creation.
beginStrandedSleepingAgentRescue runs before this block, and endStrandedSleepingAgentRescue runs only in the finally. While the count stays above zero, two consumers suppress tab creation for the worktree:
src/renderer/src/lib/worktree-activation.tsLine 503 returnsnullinstead of creating the initial terminal.src/renderer/src/components/Terminal.tsxLine 1501 returns beforecreateTab.
If window.api.session.get() never settles, the promise never rejects, the finally never runs, and the worktree stays without any tab for the rest of the session. The catch only covers rejection, not a hang.
Bound each read with a timeout. Treat a timeout as "cannot prove the tab is gone" and return, which releases the gate.
Read the two partitions concurrently as well. The reads are independent, and the gate blocks the user-visible initial terminal for their combined duration.
🛡️ Proposed fix: bound and parallelize the partition reads
const partitions: WorkspaceSessionState[] = []
try {
- partitions.push(await window.api.session.get())
- if (connectionId) {
- partitions.push(await window.api.session.get(toSshExecutionHostId(connectionId)))
- }
+ const reads = [
+ window.api.session.get(),
+ ...(connectionId ? [window.api.session.get(toSshExecutionHostId(connectionId))] : [])
+ ]
+ // Why: this read gates initial-terminal creation, so a hung main process must not
+ // leave the worktree permanently tabless — time out into the "cannot prove" branch.
+ partitions.push(
+ ...(await Promise.all(
+ reads.map((read) =>
+ Promise.race([
+ read,
+ new Promise<never>((_, reject) =>
+ setTimeout(() => reject(new Error('session partition read timed out')), 5_000)
+ )
+ ])
+ )
+ ))
+ )
} catch {
// Why: an unreadable partition cannot prove the tab is gone; resuming
// on failure is the duplicate-session direction.
return
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (isDirectSshRemoteWorkspaceApplyInProgress()) { | |
| return | |
| } | |
| const state = useAppStore.getState() | |
| const connectionId = getConnectionIdFromState(state, record.worktreeId) | |
| if (connectionId && !state.remoteWorkspaceHydratedTargetIds.has(connectionId)) { | |
| return | |
| } | |
| const partitions: WorkspaceSessionState[] = [] | |
| try { | |
| partitions.push(await window.api.session.get()) | |
| if (connectionId) { | |
| partitions.push(await window.api.session.get(toSshExecutionHostId(connectionId))) | |
| } | |
| } catch { | |
| // Why: an unreadable partition cannot prove the tab is gone; resuming | |
| // on failure is the duplicate-session direction. | |
| return | |
| } | |
| const partitions: WorkspaceSessionState[] = [] | |
| try { | |
| const reads = [ | |
| window.api.session.get(), | |
| ...(connectionId ? [window.api.session.get(toSshExecutionHostId(connectionId))] : []) | |
| ] | |
| // Why: this read gates initial-terminal creation, so a hung main process must not | |
| // leave the worktree permanently tabless — time out into the "cannot prove" branch. | |
| partitions.push( | |
| ...(await Promise.all( | |
| reads.map((read) => | |
| Promise.race([ | |
| read, | |
| new Promise<never>((_, reject) => | |
| setTimeout(() => reject(new Error('session partition read timed out')), 5_000) | |
| ) | |
| ]) | |
| ) | |
| )) | |
| ) | |
| } catch { | |
| // Why: an unreadable partition cannot prove the tab is gone; resuming | |
| // on failure is the duplicate-session direction. | |
| return | |
| } |
| const state = useAppStore.getState() | ||
| const connectionId = getConnectionIdFromState(state, record.worktreeId) | ||
| if (connectionId && !state.remoteWorkspaceHydratedTargetIds.has(connectionId)) { | ||
| return | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Inspect getConnectionIdFromState return semantics and how other callers treat undefined.
set -euo pipefail
fd -t f 'connection-owner-resolution.ts' -x sed -n '1,90p'
echo '--- callers ---'
rg -nP --type=ts -C4 '\bgetConnectionIdFromState\s*\('Repository: stablyai/orca
Length of output: 3579
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- locate resume-sleeping-agent-session.ts ---'
fd -t f 'resume-sleeping-agent-session\.ts' -x wc -l {} -x sed -n '150,220p' {}
echo '--- all getConnectionIdFromState usages ---'
rg -n -C3 '\bgetConnectionIdFromState\s*\('
echo '--- hydration/store selectors around hydratedTargetIds ---'
rg -n -C3 'remoteWorkspaceHydratedTargetIds|hydratedTargetIds'Repository: stablyai/orca
Length of output: 263
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- locate resume-sleeping-agent-session.ts ---'
file=$(fd -t f 'resume-sleeping-agent-session\.ts' | head -n1)
if [ -n "${file:-}" ]; then
wc -l "$file"
sed -n '150,220p' "$file"
fi
echo '--- all getConnectionIdFromState usages ---'
rg -n -C3 '\bgetConnectionIdFromState\s*\('
echo '--- hydration/store selectors around hydratedTargetIds ---'
rg -n -C3 'remoteWorkspaceHydratedTargetIds|hydratedTargetIds'Repository: stablyai/orca
Length of output: 2866
Defer rescue when connection state is unavailable.
getConnectionIdFromState can return undefined when the repo does not exist in state. Treat undefined the same as the skipped hydrate/resolved-no-target cases, because a missing repo in state can occur before repo hydration finishes and this path cannot prove the tab is gone.
…on partition before resuming into a fresh tab The wake sweep resumed a sleeping-agent record into a fresh tab whenever the record's tab was absent from tabsByWorktree. That map holds only materialized worktrees — a hydrated but never-activated remote worktree keeps its tabs in the persisted session partitions alone — so the sweep forked a second agent process onto a session whose terminal was still running on the host. The fresh-tab resume now runs behind an async verification: it skips, keeping the record, while a direct-SSH snapshot apply is in progress (the partitions can lag the store mid-apply), while the record's SSH target has not hydrated, when any persisted partition still lists the tab, and on a partition read failure — every uncertain outcome resolves to no launch. Only a tab absent from live state and every partition resumes, after re-validating record currency and provider-session ownership against fresh state. In-flight rescues are deduplicated per provider-session claim. A ref-counted strandedSleepingAgentRescuesByWorktreeId map gates both initial-terminal auto-create sites while a rescue is deciding, so an activation cannot race a placeholder tab into the worktree; the Terminal effect re-evaluates when a rescue concludes without launching so an empty worktree still receives its initial terminal. An explicit launch payload (startup, defaultTabs) always creates immediately — the gate only suppresses payloadless placeholder creation — and setup or issue commands arriving while a rescue is pending are queued for whichever tab lands first. Background wakes dispatch their mount per launched tab, so a rescue that resolves after the wake call returned still mounts its activate-false tab. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
855808e to
cd0e9e2
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
…stranded-rescue Resolves conflicts from upstream's worktree-activation module split: the stranded-rescue gate and its store-contract field move into worktree-initial-terminal-seeding.ts / worktree-activation-store-contract.ts, and Terminal.tsx keeps both dependency additions in the auto-create effect. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AqNqAZQTwmAkwGcHj5TYXk
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
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: e20e85ef-12ba-4a25-b6d4-380b3ff4a108
📒 Files selected for processing (10)
src/renderer/src/components/Terminal.tsxsrc/renderer/src/lib/resume-sleeping-agent-session-replay.test.tssrc/renderer/src/lib/resume-sleeping-agent-session.test.tssrc/renderer/src/lib/resume-sleeping-agent-session.tssrc/renderer/src/lib/wake-sleeping-agents-in-background-stranded-rescue.test.tssrc/renderer/src/lib/wake-sleeping-agents-in-background.tssrc/renderer/src/lib/worktree-activation-store-contract.tssrc/renderer/src/lib/worktree-initial-terminal-seeding.tssrc/renderer/src/lib/worktree-reactivation-tab-forkbomb.test.tssrc/renderer/src/store/slices/agent-status.ts
🚧 Files skipped from review as they are similar to previous changes (8)
- src/renderer/src/components/Terminal.tsx
- src/renderer/src/lib/resume-sleeping-agent-session-replay.test.ts
- src/renderer/src/store/slices/agent-status.ts
- src/renderer/src/lib/wake-sleeping-agents-in-background.ts
- src/renderer/src/lib/wake-sleeping-agents-in-background-stranded-rescue.test.ts
- src/renderer/src/lib/resume-sleeping-agent-session.test.ts
- src/renderer/src/lib/worktree-reactivation-tab-forkbomb.test.ts
- src/renderer/src/lib/resume-sleeping-agent-session.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
| if ( | ||
| hasPendingStrandedSleepingAgentRescue && | ||
| !startup && | ||
| !defaultTabs && | ||
| !store.tabsByWorktree[worktreeId]?.[0]?.id |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -eu
file='src/renderer/src/lib/worktree-initial-terminal-seeding.ts'
printf '%s\n' '--- outline ---'
ast-grep outline "$file" || true
printf '%s\n' '--- file size ---'
wc -l "$file"
printf '%s\n' '--- relevant implementation ---'
sed -n '1,230p' "$file"
printf '%s\n' '--- symbol references ---'
rg -n --glob '*.{ts,tsx}' 'hasExplicitLaunchWork|shouldAutoCreateInitialTerminal|applyDefaultTerminalTabs|worktree-initial-terminal-seeding|defaultTabs' .Repository: stablyai/orca
Length of output: 27133
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- seeding remainder ---'
sed -n '130,250p' src/renderer/src/lib/worktree-initial-terminal-seeding.ts
printf '%s\n' '--- default-tab helper ---'
cat -n src/renderer/src/lib/worktree-default-terminal-tabs.ts
printf '%s\n' '--- auto-create predicate ---'
cat -n src/renderer/src/components/terminal/initial-terminal.ts
printf '%s\n' '--- activation call path ---'
sed -n '110,220p' src/renderer/src/lib/worktree-activation.ts
printf '%s\n' '--- default-tab tests ---'
cat -n src/renderer/src/lib/worktree-activation-default-tabs.test.ts
printf '%s\n' '--- seeding test files ---'
for f in src/renderer/src/lib/worktree-activation-agent-startup.test.ts \
src/renderer/src/lib/worktree-activation-setup-script.test.ts \
src/renderer/src/lib/worktree-activation-issue-command.test.ts \
src/renderer/src/lib/worktree-activation-web-runtime.test.ts; do
printf '\n--- %s ---\n' "$f"
wc -l "$f"
rg -n -A12 -B8 'defaultTabs|tabsByWorktree|renderableTabCount|ensureWorktreeHasInitialTerminal' "$f" || true
doneRepository: stablyai/orca
Length of output: 45866
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- launch types ---'
rg -n -A35 -B10 'interface WorktreeDefaultTabsLaunch|type WorktreeDefaultTabsLaunch|WorktreeDefaultTabsLaunch' src/shared src/main src/renderer/src | head -260
printf '%s\n' '--- default-tab payload builders ---'
rg -n -A35 -B12 'function getDefaultTabsLaunch|getDefaultTabsLaunch|defaultTabs =|defaultTabs:' src/main/runtime/orca-runtime.ts src/main/ipc/worktree-remote.ts src/renderer/src/lib/new-workspace.ts src/shared
printf '%s\n' '--- activation test harness ---'
cat -n src/renderer/src/lib/worktree-activation-test-harness.ts | sed -n '1,260p'
printf '%s\n' '--- direct default-tab call sites ---'
rg -n -A12 -B12 'ensureWorktreeHasInitialTerminal\(' src/renderer/src --glob '*.{ts,tsx}'Repository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- hook normalization and fallback sources ---'
sed -n '205,265p' src/shared/orca-yaml.ts
sed -n '88,120p' src/main/effective-hook-config.ts
sed -n '1888,1902p' src/main/ipc/worktree-remote.ts
sed -n '2571,2583p' src/main/ipc/worktree-remote.ts
sed -n '24855,24870p' src/main/runtime/orca-runtime.ts
printf '%s\n' '--- activation test harness ---'
sed -n '1,240p' src/renderer/src/lib/worktree-activation-test-harness.ts
printf '%s\n' '--- creation-flow invocation ---'
sed -n '190,245p' src/renderer/src/lib/worktree-creation-flow.ts
printf '%s\n' '--- background terminal invocation ---'
sed -n '240,305p' src/renderer/src/lib/launch-worktree-background-terminals.ts
printf '%s\n' '--- focused behavioral model ---'
python3 - <<'PY'
from dataclasses import dataclass
def should_auto_create(renderable_count, has_persisted_state):
return renderable_count == 0 and not has_persisted_state
def apply_default_tabs(default_tabs):
if default_tabs is None:
return ("no-op", 0)
if len(default_tabs) == 0:
return ("marked-applied", 0)
return ("created-default-tabs", len(default_tabs))
def current_gate(renderable_count, has_persisted_state, startup=None, setup=None,
issue=None, default_tabs=None):
auto = should_auto_create(renderable_count, has_persisted_state)
explicit = bool(startup or setup or issue)
return auto or (renderable_count == 0 and explicit)
def proposed_gate(renderable_count, has_persisted_state, startup=None, setup=None,
issue=None, default_tabs=None):
auto = should_auto_create(renderable_count, has_persisted_state)
explicit = bool(startup or setup or issue or default_tabs)
return auto or (renderable_count == 0 and explicit)
def length_gate(renderable_count, has_persisted_state, startup=None, setup=None,
issue=None, default_tabs=None):
auto = should_auto_create(renderable_count, has_persisted_state)
explicit = bool(startup or setup or issue or (default_tabs and len(default_tabs) > 0))
return auto or (renderable_count == 0 and explicit)
cases = [
("new worktree, non-empty defaults", 0, False, None, ["Server"]),
("persisted empty row, non-empty defaults", 0, True, None, ["Server"]),
("persisted empty row, empty defaults", 0, True, None, []),
]
for name, count, persisted, startup, defaults in cases:
current = current_gate(count, persisted, startup=startup, default_tabs=defaults)
proposed = proposed_gate(count, persisted, startup=startup, default_tabs=defaults)
length = length_gate(count, persisted, startup=startup, default_tabs=defaults)
helper = apply_default_tabs(defaults)
print(f"{name}: current={current}, proposed={proposed}, length_guard={length}, helper={helper}")
PYRepository: stablyai/orca
Length of output: 14025
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- hook normalization and fallback sources ---'
sed -n '205,265p' src/shared/orca-yaml.ts
sed -n '88,120p' src/main/effective-hook-config.ts
sed -n '1888,1902p' src/main/ipc/worktree-remote.ts
sed -n '2571,2583p' src/main/ipc/worktree-remote.ts
sed -n '24855,24870p' src/main/runtime/orca-runtime.ts
printf '%s\n' '--- activation test harness ---'
sed -n '1,240p' src/renderer/src/lib/worktree-activation-test-harness.ts
printf '%s\n' '--- creation-flow invocation ---'
sed -n '190,245p' src/renderer/src/lib/worktree-creation-flow.ts
printf '%s\n' '--- background terminal invocation ---'
sed -n '240,305p' src/renderer/src/lib/launch-worktree-background-terminals.ts
printf '%s\n' '--- focused behavioral model ---'
python3 - <<'PY'
def should_auto_create(renderable_count, has_persisted_state):
return renderable_count == 0 and not has_persisted_state
def apply_default_tabs(default_tabs):
if default_tabs is None:
return ("no-op", 0)
if len(default_tabs) == 0:
return ("marked-applied", 0)
return ("created-default-tabs", len(default_tabs))
def current_gate(renderable_count, has_persisted_state, startup=None, setup=None,
issue=None, default_tabs=None):
auto = should_auto_create(renderable_count, has_persisted_state)
explicit = bool(startup or setup or issue)
return auto or (renderable_count == 0 and explicit)
def proposed_gate(renderable_count, has_persisted_state, startup=None, setup=None,
issue=None, default_tabs=None):
auto = should_auto_create(renderable_count, has_persisted_state)
explicit = bool(startup or setup or issue or default_tabs)
return auto or (renderable_count == 0 and explicit)
def length_gate(renderable_count, has_persisted_state, startup=None, setup=None,
issue=None, default_tabs=None):
auto = should_auto_create(renderable_count, has_persisted_state)
explicit = bool(startup or setup or issue or (default_tabs and len(default_tabs) > 0))
return auto or (renderable_count == 0 and explicit)
cases = [
("new worktree, non-empty defaults", 0, False, None, ["Server"]),
("persisted empty row, non-empty defaults", 0, True, None, ["Server"]),
("persisted empty row, empty defaults", 0, True, None, []),
]
for name, count, persisted, startup, defaults in cases:
current = current_gate(count, persisted, startup=startup, default_tabs=defaults)
proposed = proposed_gate(count, persisted, startup=startup, default_tabs=defaults)
length = length_gate(count, persisted, startup=startup, default_tabs=defaults)
helper = apply_default_tabs(defaults)
print(f"{name}: current={current}, proposed={proposed}, length_guard={length}, helper={helper}")
PYRepository: stablyai/orca
Length of output: 14025
Include non-empty defaultTabs in hasExplicitLaunchWork. If the worktree has a persisted empty tab entry, the current gate skips applyDefaultTerminalTabs, so configured default tabs are never created. Use defaultTabs?.tabs.length > 0 to preserve empty-payload behavior.
|
Thanks @robertnisipeanu for the session-partition resume race fix. Merged fix #16750 now covers the same host-unanswered and unverifiable gates for seeding and sleeping-agent resume. We will retain your contribution as historical credit and request no rebase, retest, or other follow-up. Closing this superseded branch. |
Problem
resumeSleepingAgentSessionsForWorktreeresumes a sleeping-agent record into a fresh tab whenever the record's wake tab is absent fromtabsByWorktreeand no preserved pane owns the session.tabsByWorktreeholds only materialized worktrees — a hydrated but never-activated remote worktree keeps its tabs in the persisted session partitions (workspaceSessionsByHostId) alone — so absence there proves nothing about the session. The sweep forked a second<agent> --resume <session>process onto a session whose terminal was still running on the remote host. Reproduced repeatedly against a direct-SSH workspace: every app restart duplicated a live Claude session because the worktree's tabs had not been materialized yet when the sweep ran.Change
The fresh-tab resume moves behind an async verification (
queueStrandedSleepingAgentRescue):session:getIPC) still lists the tab, and on a partition read failure. Every uncertain outcome resolves to no launch — a kept record is retried by a later sweep.A ref-counted
strandedSleepingAgentRescuesByWorktreeIdmap (in-memory only) gates both initial-terminal auto-create sites while a rescue is deciding, so activation cannot race a placeholder tab into the worktree; the Terminal effect re-evaluates when a rescue concludes without launching, so an empty worktree still receives its initial terminal. An explicit launch payload (startup,defaultTabs) always creates immediately — the gate suppresses only payloadless placeholder creation — andsetup/issueCommandarriving while a rescue is pending queue viaqueueHookCommandsForFirstWorktreeTabfor whichever tab lands first.wakeSleepingAgentsForWorktreeInBackgrounddispatches its background mount per launched tab, so a rescue resolving after the wake call returned still mounts itsactivate: falsetab.Testing
New coverage: partition-present → record kept; absent-everywhere → resume; partition IPC failure → record kept; apply-in-progress → record kept; the reactivation fork-bomb invariant with the async rescue; declined rescue still yields an initial terminal; queued
issueCommandreaches the first tab after a rescue resolves;startuppayload creates immediately despite a pending rescue; background mount fires for an async rescue launch (new integration test exercising the real sweep). Existing missing-tab resume tests migrated to the async shape with their original end-state assertions.typecheck:webclean; the resume/wake/activation suites pass (60 tests across the five directly affected files) and the full renderer lib+hooks sweep matches the origin/main baseline.Known limitations (deliberate): a rescue that can never settle (e.g. an unreachable partition IPC) keeps the record and suppresses that worktree's auto-created initial terminal until a later sweep; a rescue that declines on a non-focused worktree leaves it without an initial terminal until its next activation (queued commands are not lost).
🤖 Generated with Claude Code