Skip to content

fix(agents): verify a sleeping session's tab is gone from every session partition before resuming into a fresh tab - #13037

Closed
robertnisipeanu wants to merge 2 commits into
stablyai:mainfrom
robertnisipeanu:fix/sleeping-agent-stranded-rescue
Closed

robertnisipeanu wants to merge 2 commits into
stablyai:mainfrom
robertnisipeanu:fix/sleeping-agent-stranded-rescue

Conversation

@robertnisipeanu

Copy link
Copy Markdown
Contributor

Problem

resumeSleepingAgentSessionsForWorktree resumes a sleeping-agent record into a fresh tab whenever the record's wake tab is absent from tabsByWorktree and no preserved pane owns the session. tabsByWorktree holds 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):

  • Skips, keeping the record, while a direct-SSH snapshot apply is in progress (session writes are suppressed during an apply, so the partitions can lag the store), while the record's SSH target has not hydrated, when any persisted partition (local + the record's host, via the existing session:get IPC) 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.
  • Launches only when the tab is absent from live state and every partition, after re-validating record currency and provider-session ownership against fresh state. In-flight rescues deduplicate per provider-session claim key.

A ref-counted strandedSleepingAgentRescuesByWorktreeId map (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 — and setup/issueCommand arriving while a rescue is pending queue via queueHookCommandsForFirstWorktreeTab for whichever tab lands first. wakeSleepingAgentsForWorktreeInBackground dispatches its background mount per launched tab, so a rescue resolving after the wake call returned still mounts its activate: false tab.

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 issueCommand reaches the first tab after a rescue resolves; startup payload 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:web clean; 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

@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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 e9dc3

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the problem, implementation, testing, and limitations, but it omits several required template sections, including the linked issue and visual proof. Add the required template sections, including a valid Fixes # issue link, Visual Proof with N/A and a reason if applicable, checklist status, and review notes.
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the main change: checking all session partitions before resuming a sleeping agent into a new tab.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

🧹 Nitpick comments (2)
src/renderer/src/lib/resume-sleeping-agent-session.test.ts (1)

945-993: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Wait 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 the get() call and the end of the rescue is an implementation detail of queueStrandedSleepingAgentRescue. If a future change adds one more await in that path, these assertions run before the rescue finishes and pass without testing anything.

strandedSleepingAgentRescuesByWorktreeId drops to zero exactly when the rescue completes, so it is a stable completion signal. The sibling suite already uses it in src/renderer/src/lib/worktree-reactivation-tab-forkbomb.test.ts Lines 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 value

Extract the repeated first-tab command-queueing block.

The gate logic and the deferral condition are correct. The queueHookCommandsForFirstWorktreeTab call at Lines 509-523 is identical to the web-runtime block at Lines 478-492, including the argument order passed to queueSetupAndIssueCommands. Two identical copies in one function will drift when the queueSetupAndIssueCommands signature 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.tsx
  • src/renderer/src/lib/resume-sleeping-agent-session-replay.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/wake-sleeping-agents-in-background-stranded-rescue.test.ts
  • src/renderer/src/lib/wake-sleeping-agents-in-background.ts
  • src/renderer/src/lib/worktree-activation.ts
  • src/renderer/src/lib/worktree-reactivation-tab-forkbomb.test.ts
  • src/renderer/src/store/slices/agent-status.ts

Comment on lines +186 to +204
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
}

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.

🩺 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.ts Line 503 returns null instead of creating the initial terminal.
  • src/renderer/src/components/Terminal.tsx Line 1501 returns before createTab.

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.

Suggested change
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
}

Comment on lines +189 to +193
const state = useAppStore.getState()
const connectionId = getConnectionIdFromState(state, record.worktreeId)
if (connectionId && !state.remoteWorkspaceHydratedTargetIds.has(connectionId)) {
return
}

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.

🩺 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>
@robertnisipeanu
robertnisipeanu force-pushed the fix/sleeping-agent-stranded-rescue branch from 855808e to cd0e9e2 Compare August 14, 2026 23:16
@coderabbitai

coderabbitai Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

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
@coderabbitai

coderabbitai Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

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.

@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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e20e85ef-12ba-4a25-b6d4-380b3ff4a108

📥 Commits

Reviewing files that changed from the base of the PR and between 3ffab9a and e9dc3f9.

📒 Files selected for processing (10)
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/lib/resume-sleeping-agent-session-replay.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/wake-sleeping-agents-in-background-stranded-rescue.test.ts
  • src/renderer/src/lib/wake-sleeping-agents-in-background.ts
  • src/renderer/src/lib/worktree-activation-store-contract.ts
  • src/renderer/src/lib/worktree-initial-terminal-seeding.ts
  • src/renderer/src/lib/worktree-reactivation-tab-forkbomb.test.ts
  • src/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.

Comment on lines +120 to +124
if (
hasPendingStrandedSleepingAgentRescue &&
!startup &&
!defaultTabs &&
!store.tabsByWorktree[worktreeId]?.[0]?.id

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.

🎯 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
done

Repository: 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}")
PY

Repository: 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}")
PY

Repository: 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.

@nwparker nwparker removed the P1 label Aug 19, 2026
@Jinwoo-H

Copy link
Copy Markdown
Contributor

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.

@Jinwoo-H Jinwoo-H closed this Aug 31, 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.

5 participants