From f252bf2afdf009a257ee36570b7fa3a5b59dcfbf Mon Sep 17 00:00:00 2001 From: Robert Nisipeanu Date: Wed, 5 Aug 2026 13:10:23 +0300 Subject: [PATCH 1/9] fix(agents): stop the wake sweep from forking sessions that live SSH panes still own Co-Authored-By: Claude Fable 5 --- ...ping-agent-session-live-ssh-dedupe.test.ts | 128 ++++++++++++++++++ .../src/lib/resume-sleeping-agent-session.ts | 24 ++++ .../src/lib/sleeping-agent-pane-ownership.ts | 45 +++++- 3 files changed, 194 insertions(+), 3 deletions(-) create mode 100644 src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts diff --git a/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts b/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts new file mode 100644 index 000000000000..bd2c90c7a623 --- /dev/null +++ b/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts @@ -0,0 +1,128 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { SleepingAgentSessionRecord } from '../../../shared/agent-session-resume' +import { makePaneKey } from '../../../shared/stable-pane-id' +import { useAppStore } from '@/store' +import { resumeSleepingAgentSessionsForWorktree } from './resume-sleeping-agent-session' + +const initialAppStoreState = useAppStore.getState() +const LEAF_ID = '11111111-1111-4111-8111-111111111111' +const OTHER_LEAF_ID = '22222222-2222-4222-8222-222222222222' +const SSH_PTY_ID = 'ssh:ssh-target-1@@pty-3' + +afterEach(() => { + vi.unstubAllGlobals() + useAppStore.setState(initialAppStoreState, true) +}) + +function makeRecord( + overrides: Partial = {} +): SleepingAgentSessionRecord { + return { + paneKey: makePaneKey('tab-1', LEAF_ID), + tabId: 'tab-1', + worktreeId: 'wt-1', + agent: 'claude', + providerSession: { key: 'session_id', id: 'sess-1' }, + prompt: 'finish the task', + state: 'working', + origin: 'quit', + capturedAt: 1, + updatedAt: 1, + ...overrides + } +} + +function makeTerminalTab(id: string, worktreeId: string): Record { + return { + id, + ptyId: null, + worktreeId, + title: 'shell', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } +} + +function makeLayout(leafId: string, ptyId: string | null): Record { + return { + root: { type: 'leaf', leafId }, + activeLeafId: leafId, + expandedLeafId: null, + ptyIdsByLeafId: ptyId ? { [leafId]: ptyId } : {} + } +} + +describe('resumeSleepingAgentSessionsForWorktree — SSH panes and stale worktree ids', () => { + it('treats a leaf bound to an ssh pty as pane-owned while its target is disconnected', () => { + const record = makeRecord() + useAppStore.setState({ + activeWorktreeId: 'wt-other', + tabsByWorktree: { 'wt-1': [makeTerminalTab('tab-1', 'wt-1')] }, + terminalLayoutsByTabId: { 'tab-1': makeLayout(LEAF_ID, SSH_PTY_ID) }, + ptyIdsByTabId: {}, + sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } + } as never) + + const launched = resumeSleepingAgentSessionsForWorktree('wt-1') + + expect(launched).toBe(0) + expect(useAppStore.getState().sleepingAgentSessionsByPaneKey[record.paneKey]).toBe(record) + }) + + it('still resumes when the preserved pane has no pty binding and cannot own recovery', () => { + const record = makeRecord() + useAppStore.setState({ + activeWorktreeId: 'wt-other', + tabsByWorktree: { 'wt-1': [makeTerminalTab('tab-1', 'wt-1')] }, + terminalLayoutsByTabId: { 'tab-1': makeLayout(LEAF_ID, null) }, + ptyIdsByTabId: {}, + sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } + } as never) + + const launched = resumeSleepingAgentSessionsForWorktree('wt-1') + + expect(launched).toBe(1) + }) + + it('finds the preserved tab when the record worktreeId is stale', () => { + const record = makeRecord() + useAppStore.setState({ + activeWorktreeId: 'wt-other', + tabsByWorktree: { 'wt-1': [], 'wt-2': [makeTerminalTab('tab-1', 'wt-2')] }, + terminalLayoutsByTabId: { 'tab-1': makeLayout(LEAF_ID, SSH_PTY_ID) }, + ptyIdsByTabId: {}, + sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } + } as never) + + const launched = resumeSleepingAgentSessionsForWorktree('wt-1') + + expect(launched).toBe(0) + expect(useAppStore.getState().sleepingAgentSessionsByPaneKey[record.paneKey]).toBe(record) + }) + + it('clears a record whose provider session is owned by a record in another worktree', () => { + const stale = makeRecord({ providerSession: { key: 'session_id', id: 'sess-9' } }) + const owned = makeRecord({ + paneKey: makePaneKey('tab-2', OTHER_LEAF_ID), + tabId: 'tab-2', + worktreeId: 'wt-2', + providerSession: { key: 'session_id', id: 'sess-9' } + }) + useAppStore.setState({ + activeWorktreeId: 'wt-other', + tabsByWorktree: { 'wt-1': [], 'wt-2': [makeTerminalTab('tab-2', 'wt-2')] }, + terminalLayoutsByTabId: { 'tab-2': makeLayout(OTHER_LEAF_ID, SSH_PTY_ID) }, + ptyIdsByTabId: {}, + sleepingAgentSessionsByPaneKey: { [stale.paneKey]: stale, [owned.paneKey]: owned } + } as never) + + const launched = resumeSleepingAgentSessionsForWorktree('wt-1') + + expect(launched).toBe(0) + const records = useAppStore.getState().sleepingAgentSessionsByPaneKey + expect(records[stale.paneKey]).toBeUndefined() + expect(records[owned.paneKey]).toBe(owned) + }) +}) diff --git a/src/renderer/src/lib/resume-sleeping-agent-session.ts b/src/renderer/src/lib/resume-sleeping-agent-session.ts index bb9a84a912a4..ceaebd9ee6fd 100644 --- a/src/renderer/src/lib/resume-sleeping-agent-session.ts +++ b/src/renderer/src/lib/resume-sleeping-agent-session.ts @@ -175,6 +175,23 @@ function activeOrQueuedResumeClaimsProviderSession( return false } +function providerSessionOwnedElsewhere( + record: SleepingAgentSessionRecord, + state: ReturnType +): boolean { + const sessionId = record.providerSession?.id + if (!sessionId) { + return false + } + return Object.values(state.sleepingAgentSessionsByPaneKey).some( + (other) => + other !== record && + other.agent === record.agent && + agentProviderSessionsEqual(record.agent, other.providerSession, record.providerSession) && + recordPaneIsOwnedByPreservedPane(other, state) + ) +} + // Why: an interrupted turn is still resumable — `claude --resume` reopens the transcript at the // prompt — so discarding those records only stranded the session across wake and restart. function isInvalidWorktreeActivationRecord(record: SleepingAgentSessionRecord): boolean { @@ -323,6 +340,13 @@ export function resumeSleepingAgentSessionsForWorktree( if (isHostMirroredSleepingRecord(record)) { continue } + // Why: claim keys are worktree-scoped, but a provider session is global — + // a record whose stored worktreeId went stale must not relaunch a session + // that a pane tracked by another record still owns. + if (providerSessionOwnedElsewhere(record, currentState)) { + state.clearSleepingAgentSession(record.paneKey) + continue + } if (launchSleepingAgentSession(record, options)) { launched += 1 freshlyLaunchedClaimKeys.add(claimKey) diff --git a/src/renderer/src/lib/sleeping-agent-pane-ownership.ts b/src/renderer/src/lib/sleeping-agent-pane-ownership.ts index 0602f5bdce5a..ce741415049f 100644 --- a/src/renderer/src/lib/sleeping-agent-pane-ownership.ts +++ b/src/renderer/src/lib/sleeping-agent-pane-ownership.ts @@ -6,6 +6,7 @@ import type { TerminalPaneLayoutNode, TerminalTab } from '../../../shared/terminal-tab-types' +import { parseAppSshPtyId } from '../../../shared/ssh-pty-id' import { parseLegacyNumericPaneKey, parsePaneKey } from '../../../shared/stable-pane-id' import { isWebTerminalSurfaceTabId } from '../../../shared/terminal-surface-id' import { isPaneSpawnDeferred } from './pane-spawn-deferral-registry' @@ -131,6 +132,31 @@ function paneWillConnectOnActivation( return !isWebTerminalSurfaceTabId(tabId) } +// Why: sleeping records persist the worktreeId observed at capture time, which +// goes stale when the session's transcript project differs from the tab's +// worktree (e.g. an agent-managed checkout). Tab ids are globally unique, so a +// miss under the recorded worktree must fall back to the tab's real owner — +// otherwise a live pane is misread as gone and its session forked. +function findPreservedTabOwner( + state: AppStoreState, + worktreeIdHint: string, + tabId: string +): { tab: TerminalTab; worktreeId: string } | null { + const hinted = (state.tabsByWorktree[worktreeIdHint] ?? []).find( + (candidate) => candidate.id === tabId + ) + if (hinted) { + return { tab: hinted, worktreeId: worktreeIdHint } + } + for (const [worktreeId, tabs] of Object.entries(state.tabsByWorktree)) { + const tab = tabs.find((candidate) => candidate.id === tabId) + if (tab) { + return { tab, worktreeId } + } + } + return null +} + export function recordPaneIsOwnedByPreservedPane( record: SleepingAgentSessionRecord, state: AppStoreState @@ -142,10 +168,14 @@ export function recordPaneIsOwnedByPreservedPane( return false } const tabId = record.tabId ?? stable.tabId - const tab = worktreeTabs.find((candidate) => candidate.id === tabId) ?? null - if (!tab || !hasMatchingStablePaneLayout(tabId, stable.leafId, state.terminalLayoutsByTabId)) { + const owner = findPreservedTabOwner(state, record.worktreeId, tabId) + if ( + !owner || + !hasMatchingStablePaneLayout(tabId, stable.leafId, state.terminalLayoutsByTabId) + ) { return false } + const tab = owner.tab if (activationTreatsNoteAsFinished(record)) { return true } @@ -166,6 +196,15 @@ export function recordPaneIsOwnedByPreservedPane( ) { return true } + // Why: a remote SSH PTY survives transport loss — the disconnect handler + // clears ptyIdsByTabId for the whole target while the remote host keeps the + // process running. A leaf still bound to an SSH pty id owns its session + // with no live PTY mapped; treating it as dead forks a second `--resume`. + const leafPtyId = + state.terminalLayoutsByTabId[tabId]?.ptyIdsByLeafId?.[stable.leafId] ?? tab.ptyId + if (leafPtyId && parseAppSshPtyId(leafPtyId)) { + return true + } // Why: active sessions rely on pane-level cold restore. A preserved leaf // without a PTY/session id can repaint scrollback but cannot resume. return ( @@ -175,7 +214,7 @@ export function recordPaneIsOwnedByPreservedPane( stable.leafId, state.ptyIdsByTabId, state.terminalLayoutsByTabId - ) && paneWillConnectOnActivation(record.worktreeId, tabId, state) + ) && paneWillConnectOnActivation(owner.worktreeId, tabId, state) ) } From 0115613236ab356bee04cfd485d237484d7228b9 Mon Sep 17 00:00:00 2001 From: Robert Nisipeanu Date: Sun, 11 Oct 2026 11:59:15 +0300 Subject: [PATCH 2/9] fix(agents): only treat an ssh-bound leaf as owned while its target is unreachable A connected target's live-PTY map is authoritative: sleep kills the PTY but keeps its id. Cross-worktree session dedupe ignores finished and invalid records, the same records claim-key dedupe skips. Co-Authored-By: Claude Opus 5.5 (1M context) --- ...ping-agent-session-live-ssh-dedupe.test.ts | 40 +++++++++++++++++++ .../src/lib/resume-sleeping-agent-session.ts | 9 ++--- .../src/lib/sleeping-agent-pane-ownership.ts | 16 +++----- 3 files changed, 50 insertions(+), 15 deletions(-) diff --git a/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts b/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts index bd2c90c7a623..0aa2af28cb16 100644 --- a/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts +++ b/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts @@ -62,6 +62,7 @@ describe('resumeSleepingAgentSessionsForWorktree — SSH panes and stale worktre tabsByWorktree: { 'wt-1': [makeTerminalTab('tab-1', 'wt-1')] }, terminalLayoutsByTabId: { 'tab-1': makeLayout(LEAF_ID, SSH_PTY_ID) }, ptyIdsByTabId: {}, + sshConnectionStates: new Map([['ssh-target-1', { status: 'disconnected' }]]), sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } } as never) @@ -71,6 +72,22 @@ describe('resumeSleepingAgentSessionsForWorktree — SSH panes and stale worktre expect(useAppStore.getState().sleepingAgentSessionsByPaneKey[record.paneKey]).toBe(record) }) + it('resumes a leaf whose ssh pty is gone while its target is connected', () => { + const record = makeRecord({ origin: 'worktree-sleep' }) + useAppStore.setState({ + activeWorktreeId: 'wt-other', + tabsByWorktree: { 'wt-1': [makeTerminalTab('tab-1', 'wt-1')] }, + terminalLayoutsByTabId: { 'tab-1': makeLayout(LEAF_ID, SSH_PTY_ID) }, + ptyIdsByTabId: {}, + sshConnectionStates: new Map([['ssh-target-1', { status: 'connected' }]]), + sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } + } as never) + + const launched = resumeSleepingAgentSessionsForWorktree('wt-1') + + expect(launched).toBe(1) + }) + it('still resumes when the preserved pane has no pty binding and cannot own recovery', () => { const record = makeRecord() useAppStore.setState({ @@ -125,4 +142,27 @@ describe('resumeSleepingAgentSessionsForWorktree — SSH panes and stale worktre expect(records[stale.paneKey]).toBeUndefined() expect(records[owned.paneKey]).toBe(owned) }) + + it('does not let a finished note in another worktree clear an active record', () => { + const active = makeRecord({ providerSession: { key: 'session_id', id: 'sess-9' } }) + const finished = makeRecord({ + paneKey: makePaneKey('tab-2', OTHER_LEAF_ID), + tabId: 'tab-2', + worktreeId: 'wt-2', + origin: 'live', + state: 'done', + providerSession: { key: 'session_id', id: 'sess-9' } + }) + useAppStore.setState({ + activeWorktreeId: 'wt-other', + tabsByWorktree: { 'wt-1': [], 'wt-2': [makeTerminalTab('tab-2', 'wt-2')] }, + terminalLayoutsByTabId: { 'tab-2': makeLayout(OTHER_LEAF_ID, null) }, + ptyIdsByTabId: {}, + sleepingAgentSessionsByPaneKey: { [active.paneKey]: active, [finished.paneKey]: finished } + } as never) + + const launched = resumeSleepingAgentSessionsForWorktree('wt-1') + + expect(launched).toBe(1) + }) }) diff --git a/src/renderer/src/lib/resume-sleeping-agent-session.ts b/src/renderer/src/lib/resume-sleeping-agent-session.ts index ceaebd9ee6fd..b8b74ced8259 100644 --- a/src/renderer/src/lib/resume-sleeping-agent-session.ts +++ b/src/renderer/src/lib/resume-sleeping-agent-session.ts @@ -179,14 +179,13 @@ function providerSessionOwnedElsewhere( record: SleepingAgentSessionRecord, state: ReturnType ): boolean { - const sessionId = record.providerSession?.id - if (!sessionId) { - return false - } + // Same-worktree duplicates are handled by claim keys; finished notes never claim a session. return Object.values(state.sleepingAgentSessionsByPaneKey).some( (other) => - other !== record && + other.worktreeId !== record.worktreeId && other.agent === record.agent && + !isInvalidWorktreeActivationRecord(other) && + !activationTreatsNoteAsFinished(other) && agentProviderSessionsEqual(record.agent, other.providerSession, record.providerSession) && recordPaneIsOwnedByPreservedPane(other, state) ) diff --git a/src/renderer/src/lib/sleeping-agent-pane-ownership.ts b/src/renderer/src/lib/sleeping-agent-pane-ownership.ts index ce741415049f..f5487978389d 100644 --- a/src/renderer/src/lib/sleeping-agent-pane-ownership.ts +++ b/src/renderer/src/lib/sleeping-agent-pane-ownership.ts @@ -132,11 +132,7 @@ function paneWillConnectOnActivation( return !isWebTerminalSurfaceTabId(tabId) } -// Why: sleeping records persist the worktreeId observed at capture time, which -// goes stale when the session's transcript project differs from the tab's -// worktree (e.g. an agent-managed checkout). Tab ids are globally unique, so a -// miss under the recorded worktree must fall back to the tab's real owner — -// otherwise a live pane is misread as gone and its session forked. +// Why: a record's worktreeId can be stale (e.g. agent-managed checkout); tab ids are global. function findPreservedTabOwner( state: AppStoreState, worktreeIdHint: string, @@ -196,13 +192,13 @@ export function recordPaneIsOwnedByPreservedPane( ) { return true } - // Why: a remote SSH PTY survives transport loss — the disconnect handler - // clears ptyIdsByTabId for the whole target while the remote host keeps the - // process running. A leaf still bound to an SSH pty id owns its session - // with no live PTY mapped; treating it as dead forks a second `--resume`. + // Why: disconnect clears ptyIdsByTabId while the remote process keeps running, so a leaf + // bound to an unreachable SSH target is `unverifiable`, not dead. A connected target's + // live-PTY map is authoritative (sleep kills the PTY but keeps its id). const leafPtyId = state.terminalLayoutsByTabId[tabId]?.ptyIdsByLeafId?.[stable.leafId] ?? tab.ptyId - if (leafPtyId && parseAppSshPtyId(leafPtyId)) { + const sshPty = leafPtyId ? parseAppSshPtyId(leafPtyId) : null + if (sshPty && state.sshConnectionStates.get(sshPty.connectionId)?.status !== 'connected') { return true } // Why: active sessions rely on pane-level cold restore. A preserved leaf From ef2cb650238a68ebf7296a02b20360b911e6e5ef Mon Sep 17 00:00:00 2001 From: Robert Nisipeanu Date: Sun, 11 Oct 2026 12:22:07 +0300 Subject: [PATCH 3/9] fix(agents): use the tab pty only for a single-leaf layout when judging ssh ownership In a split tab the tab-level pty can belong to another leaf. Co-Authored-By: Claude Opus 5.5 (1M context) --- ...ping-agent-session-live-ssh-dedupe.test.ts | 28 +++++++++++++++++++ .../src/lib/sleeping-agent-pane-ownership.ts | 4 ++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts b/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts index 0aa2af28cb16..4c9ff915b259 100644 --- a/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts +++ b/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts @@ -88,6 +88,34 @@ describe('resumeSleepingAgentSessionsForWorktree — SSH panes and stale worktre expect(launched).toBe(1) }) + it("does not credit a split leaf with another leaf's ssh pty", () => { + const record = makeRecord() + useAppStore.setState({ + activeWorktreeId: 'wt-other', + tabsByWorktree: { 'wt-1': [{ ...makeTerminalTab('tab-1', 'wt-1'), ptyId: SSH_PTY_ID }] }, + terminalLayoutsByTabId: { + 'tab-1': { + root: { + type: 'split', + direction: 'vertical', + first: { type: 'leaf', leafId: OTHER_LEAF_ID }, + second: { type: 'leaf', leafId: LEAF_ID } + }, + activeLeafId: OTHER_LEAF_ID, + expandedLeafId: null, + ptyIdsByLeafId: {} + } + }, + ptyIdsByTabId: {}, + sshConnectionStates: new Map([['ssh-target-1', { status: 'disconnected' }]]), + sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } + } as never) + + const launched = resumeSleepingAgentSessionsForWorktree('wt-1') + + expect(launched).toBe(1) + }) + it('still resumes when the preserved pane has no pty binding and cannot own recovery', () => { const record = makeRecord() useAppStore.setState({ diff --git a/src/renderer/src/lib/sleeping-agent-pane-ownership.ts b/src/renderer/src/lib/sleeping-agent-pane-ownership.ts index f5487978389d..e2a4e19d3e15 100644 --- a/src/renderer/src/lib/sleeping-agent-pane-ownership.ts +++ b/src/renderer/src/lib/sleeping-agent-pane-ownership.ts @@ -195,8 +195,10 @@ export function recordPaneIsOwnedByPreservedPane( // Why: disconnect clears ptyIdsByTabId while the remote process keeps running, so a leaf // bound to an unreachable SSH target is `unverifiable`, not dead. A connected target's // live-PTY map is authoritative (sleep kills the PTY but keeps its id). + const layout = state.terminalLayoutsByTabId[tabId] + const isSingleLeafLayout = layout?.root?.type === 'leaf' && layout.root.leafId === stable.leafId const leafPtyId = - state.terminalLayoutsByTabId[tabId]?.ptyIdsByLeafId?.[stable.leafId] ?? tab.ptyId + layout?.ptyIdsByLeafId?.[stable.leafId] ?? (isSingleLeafLayout ? tab.ptyId : null) const sshPty = leafPtyId ? parseAppSshPtyId(leafPtyId) : null if (sshPty && state.sshConnectionStates.get(sshPty.connectionId)?.status !== 'connected') { return true From a1ff857e1c2b86946a042e2fd154ba3ad82b4aef Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 15 Oct 2026 21:59:42 -0700 Subject: [PATCH 4/9] test: route wake-sweep fixtures through one checked store setter --- ...ping-agent-session-live-ssh-dedupe.test.ts | 33 +++++++++++-------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts b/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts index 4c9ff915b259..aee9ba26c538 100644 --- a/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts +++ b/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts @@ -14,6 +14,11 @@ afterEach(() => { useAppStore.setState(initialAppStoreState, true) }) +function setStoreState(partial: Record): void { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: fixtures set only the slices the wake sweep reads; the rest stay at the real initial state. + useAppStore.setState(partial as Partial>) +} + function makeRecord( overrides: Partial = {} ): SleepingAgentSessionRecord { @@ -57,14 +62,14 @@ function makeLayout(leafId: string, ptyId: string | null): Record { it('treats a leaf bound to an ssh pty as pane-owned while its target is disconnected', () => { const record = makeRecord() - useAppStore.setState({ + setStoreState({ activeWorktreeId: 'wt-other', tabsByWorktree: { 'wt-1': [makeTerminalTab('tab-1', 'wt-1')] }, terminalLayoutsByTabId: { 'tab-1': makeLayout(LEAF_ID, SSH_PTY_ID) }, ptyIdsByTabId: {}, sshConnectionStates: new Map([['ssh-target-1', { status: 'disconnected' }]]), sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } - } as never) + }) const launched = resumeSleepingAgentSessionsForWorktree('wt-1') @@ -74,14 +79,14 @@ describe('resumeSleepingAgentSessionsForWorktree — SSH panes and stale worktre it('resumes a leaf whose ssh pty is gone while its target is connected', () => { const record = makeRecord({ origin: 'worktree-sleep' }) - useAppStore.setState({ + setStoreState({ activeWorktreeId: 'wt-other', tabsByWorktree: { 'wt-1': [makeTerminalTab('tab-1', 'wt-1')] }, terminalLayoutsByTabId: { 'tab-1': makeLayout(LEAF_ID, SSH_PTY_ID) }, ptyIdsByTabId: {}, sshConnectionStates: new Map([['ssh-target-1', { status: 'connected' }]]), sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } - } as never) + }) const launched = resumeSleepingAgentSessionsForWorktree('wt-1') @@ -90,7 +95,7 @@ describe('resumeSleepingAgentSessionsForWorktree — SSH panes and stale worktre it("does not credit a split leaf with another leaf's ssh pty", () => { const record = makeRecord() - useAppStore.setState({ + setStoreState({ activeWorktreeId: 'wt-other', tabsByWorktree: { 'wt-1': [{ ...makeTerminalTab('tab-1', 'wt-1'), ptyId: SSH_PTY_ID }] }, terminalLayoutsByTabId: { @@ -109,7 +114,7 @@ describe('resumeSleepingAgentSessionsForWorktree — SSH panes and stale worktre ptyIdsByTabId: {}, sshConnectionStates: new Map([['ssh-target-1', { status: 'disconnected' }]]), sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } - } as never) + }) const launched = resumeSleepingAgentSessionsForWorktree('wt-1') @@ -118,13 +123,13 @@ describe('resumeSleepingAgentSessionsForWorktree — SSH panes and stale worktre it('still resumes when the preserved pane has no pty binding and cannot own recovery', () => { const record = makeRecord() - useAppStore.setState({ + setStoreState({ activeWorktreeId: 'wt-other', tabsByWorktree: { 'wt-1': [makeTerminalTab('tab-1', 'wt-1')] }, terminalLayoutsByTabId: { 'tab-1': makeLayout(LEAF_ID, null) }, ptyIdsByTabId: {}, sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } - } as never) + }) const launched = resumeSleepingAgentSessionsForWorktree('wt-1') @@ -133,13 +138,13 @@ describe('resumeSleepingAgentSessionsForWorktree — SSH panes and stale worktre it('finds the preserved tab when the record worktreeId is stale', () => { const record = makeRecord() - useAppStore.setState({ + setStoreState({ activeWorktreeId: 'wt-other', tabsByWorktree: { 'wt-1': [], 'wt-2': [makeTerminalTab('tab-1', 'wt-2')] }, terminalLayoutsByTabId: { 'tab-1': makeLayout(LEAF_ID, SSH_PTY_ID) }, ptyIdsByTabId: {}, sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } - } as never) + }) const launched = resumeSleepingAgentSessionsForWorktree('wt-1') @@ -155,13 +160,13 @@ describe('resumeSleepingAgentSessionsForWorktree — SSH panes and stale worktre worktreeId: 'wt-2', providerSession: { key: 'session_id', id: 'sess-9' } }) - useAppStore.setState({ + setStoreState({ activeWorktreeId: 'wt-other', tabsByWorktree: { 'wt-1': [], 'wt-2': [makeTerminalTab('tab-2', 'wt-2')] }, terminalLayoutsByTabId: { 'tab-2': makeLayout(OTHER_LEAF_ID, SSH_PTY_ID) }, ptyIdsByTabId: {}, sleepingAgentSessionsByPaneKey: { [stale.paneKey]: stale, [owned.paneKey]: owned } - } as never) + }) const launched = resumeSleepingAgentSessionsForWorktree('wt-1') @@ -181,13 +186,13 @@ describe('resumeSleepingAgentSessionsForWorktree — SSH panes and stale worktre state: 'done', providerSession: { key: 'session_id', id: 'sess-9' } }) - useAppStore.setState({ + setStoreState({ activeWorktreeId: 'wt-other', tabsByWorktree: { 'wt-1': [], 'wt-2': [makeTerminalTab('tab-2', 'wt-2')] }, terminalLayoutsByTabId: { 'tab-2': makeLayout(OTHER_LEAF_ID, null) }, ptyIdsByTabId: {}, sleepingAgentSessionsByPaneKey: { [active.paneKey]: active, [finished.paneKey]: finished } - } as never) + }) const launched = resumeSleepingAgentSessionsForWorktree('wt-1') From 1157cd8a01252380ec4c9c0aa0dcc15aa5179420 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 15 Oct 2026 22:05:56 -0700 Subject: [PATCH 5/9] fix(agents): a record whose host moved can't claim a session in the wake sweep --- ...ping-agent-session-live-ssh-dedupe.test.ts | 41 +++++++++++++++++++ .../src/lib/resume-sleeping-agent-session.ts | 4 +- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts b/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts index aee9ba26c538..dcfbb9e367d2 100644 --- a/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts +++ b/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts @@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { SleepingAgentSessionRecord } from '../../../shared/agent-session-resume' import { makePaneKey } from '../../../shared/stable-pane-id' import { useAppStore } from '@/store' +import { makeWorktree, TEST_REPO } from '../store/slices/worktrees-slice-test-fixtures' import { resumeSleepingAgentSessionsForWorktree } from './resume-sleeping-agent-session' const initialAppStoreState = useAppStore.getState() @@ -176,6 +177,46 @@ describe('resumeSleepingAgentSessionsForWorktree — SSH panes and stale worktre expect(records[owned.paneKey]).toBe(owned) }) + // The other record's host moved, so it can't resume the session; letting it claim the session + // would delete the only record that can, and nothing would resume. + it('ignores a claim from a record whose worktree now routes to another host', () => { + const remotePath = '/home/neil/projects/wt-2' + const remoteWorktreeId = `repo-2::${remotePath}` + const local = makeRecord({ providerSession: { key: 'session_id', id: 'sess-9' } }) + const moved = makeRecord({ + paneKey: makePaneKey('tab-2', OTHER_LEAF_ID), + tabId: 'tab-2', + worktreeId: remoteWorktreeId, + connectionId: null, + providerSession: { key: 'session_id', id: 'sess-9' } + }) + setStoreState({ + activeWorktreeId: 'wt-other', + repos: [ + { ...TEST_REPO, id: 'repo-2', path: '/home/neil/projects', connectionId: 'ssh-target-1' } + ], + worktreesByRepo: { + 'repo-2': [ + makeWorktree({ + id: remoteWorktreeId, + repoId: 'repo-2', + path: remotePath, + hostId: 'ssh:ssh-target-1' + }) + ] + }, + tabsByWorktree: { + 'wt-1': [], + [remoteWorktreeId]: [makeTerminalTab('tab-2', remoteWorktreeId)] + }, + terminalLayoutsByTabId: { 'tab-2': makeLayout(OTHER_LEAF_ID, SSH_PTY_ID) }, + ptyIdsByTabId: {}, + sleepingAgentSessionsByPaneKey: { [local.paneKey]: local, [moved.paneKey]: moved } + }) + + expect(resumeSleepingAgentSessionsForWorktree('wt-1')).toBe(1) + }) + it('does not let a finished note in another worktree clear an active record', () => { const active = makeRecord({ providerSession: { key: 'session_id', id: 'sess-9' } }) const finished = makeRecord({ diff --git a/src/renderer/src/lib/resume-sleeping-agent-session.ts b/src/renderer/src/lib/resume-sleeping-agent-session.ts index b8b74ced8259..c91cd1e4c4e4 100644 --- a/src/renderer/src/lib/resume-sleeping-agent-session.ts +++ b/src/renderer/src/lib/resume-sleeping-agent-session.ts @@ -179,13 +179,15 @@ function providerSessionOwnedElsewhere( record: SleepingAgentSessionRecord, state: ReturnType ): boolean { - // Same-worktree duplicates are handled by claim keys; finished notes never claim a session. + // Same-worktree duplicates are handled by claim keys; finished notes never claim a session, and + // a record whose host moved can't resume it, so it can't claim it either. return Object.values(state.sleepingAgentSessionsByPaneKey).some( (other) => other.worktreeId !== record.worktreeId && other.agent === record.agent && !isInvalidWorktreeActivationRecord(other) && !activationTreatsNoteAsFinished(other) && + !sleepingRecordNamesAnotherExecutionHost(other, state) && agentProviderSessionsEqual(record.agent, other.providerSession, record.providerSession) && recordPaneIsOwnedByPreservedPane(other, state) ) From f48525147f222ff8fd18576ad5e9f030f53e1ce0 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 15 Oct 2026 22:10:49 -0700 Subject: [PATCH 6/9] fix(agents): a cross-workspace claim must name the same machine as the record --- ...ping-agent-session-live-ssh-dedupe.test.ts | 24 +++++++++++++++++++ .../src/lib/resume-sleeping-agent-session.ts | 8 +++++-- .../sleeping-record-execution-host-scope.ts | 23 ++++++++++++++++++ 3 files changed, 53 insertions(+), 2 deletions(-) diff --git a/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts b/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts index dcfbb9e367d2..0411d76b8ae5 100644 --- a/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts +++ b/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts @@ -217,6 +217,30 @@ describe('resumeSleepingAgentSessionsForWorktree — SSH panes and stale worktre expect(resumeSleepingAgentSessionsForWorktree('wt-1')).toBe(1) }) + // Matching ids on two machines (a copied state dir) are two sessions, not one. + it('ignores a claim from a pane on a different machine than this record', () => { + const local = makeRecord({ + connectionId: null, + providerSession: { key: 'session_id', id: 'sess-9' } + }) + const remote = makeRecord({ + paneKey: makePaneKey('tab-2', OTHER_LEAF_ID), + tabId: 'tab-2', + worktreeId: 'wt-2', + connectionId: 'ssh-target-1', + providerSession: { key: 'session_id', id: 'sess-9' } + }) + setStoreState({ + activeWorktreeId: 'wt-other', + tabsByWorktree: { 'wt-1': [], 'wt-2': [makeTerminalTab('tab-2', 'wt-2')] }, + terminalLayoutsByTabId: { 'tab-2': makeLayout(OTHER_LEAF_ID, SSH_PTY_ID) }, + ptyIdsByTabId: {}, + sleepingAgentSessionsByPaneKey: { [local.paneKey]: local, [remote.paneKey]: remote } + }) + + expect(resumeSleepingAgentSessionsForWorktree('wt-1')).toBe(1) + }) + it('does not let a finished note in another worktree clear an active record', () => { const active = makeRecord({ providerSession: { key: 'session_id', id: 'sess-9' } }) const finished = makeRecord({ diff --git a/src/renderer/src/lib/resume-sleeping-agent-session.ts b/src/renderer/src/lib/resume-sleeping-agent-session.ts index c91cd1e4c4e4..eea677084fa4 100644 --- a/src/renderer/src/lib/resume-sleeping-agent-session.ts +++ b/src/renderer/src/lib/resume-sleeping-agent-session.ts @@ -23,7 +23,10 @@ import { type UnhydratedHostMirror } from './host-mirrored-pane-liveness' import { parkUntilHostMirrorHandleLands } from './host-mirror-handle-gap-wait' -import { sleepingRecordNamesAnotherExecutionHost } from './sleeping-record-execution-host-scope' +import { + sleepingRecordNamesAnotherExecutionHost, + sleepingRecordsNameDifferentExecutionHosts +} from './sleeping-record-execution-host-scope' import { resolveWorkspaceTerminalHostAuthority } from './workspace-terminal-host-authority' import { parkUntilHostSessionMirrorHydrates } from '@/runtime/host-session-mirror-hydration' @@ -180,7 +183,7 @@ function providerSessionOwnedElsewhere( state: ReturnType ): boolean { // Same-worktree duplicates are handled by claim keys; finished notes never claim a session, and - // a record whose host moved can't resume it, so it can't claim it either. + // neither does a record whose host moved or that names a different machine than this record. return Object.values(state.sleepingAgentSessionsByPaneKey).some( (other) => other.worktreeId !== record.worktreeId && @@ -188,6 +191,7 @@ function providerSessionOwnedElsewhere( !isInvalidWorktreeActivationRecord(other) && !activationTreatsNoteAsFinished(other) && !sleepingRecordNamesAnotherExecutionHost(other, state) && + !sleepingRecordsNameDifferentExecutionHosts(record, other, state) && agentProviderSessionsEqual(record.agent, other.providerSession, record.providerSession) && recordPaneIsOwnedByPreservedPane(other, state) ) diff --git a/src/renderer/src/lib/sleeping-record-execution-host-scope.ts b/src/renderer/src/lib/sleeping-record-execution-host-scope.ts index 8c4a9f95f35b..1920fd50b033 100644 --- a/src/renderer/src/lib/sleeping-record-execution-host-scope.ts +++ b/src/renderer/src/lib/sleeping-record-execution-host-scope.ts @@ -74,3 +74,26 @@ export function sleepingRecordNamesAnotherExecutionHost( getKnownExecutionHostIdForWorktree(state, record.worktreeId) ) } + +/** + * Do two records positively name different machines? Locators are machine-scoped, so a pane on one + * machine never owns a session recorded on another, even when the ids match (a copied state dir). + * Fails open on the same unknowns as above: only a known disagreement counts. + */ +export function sleepingRecordsNameDifferentExecutionHosts( + a: SleepingAgentSessionRecord, + b: SleepingAgentSessionRecord, + state: WorktreeRuntimeOwnerState +): boolean { + if (a.connectionId !== undefined && b.connectionId !== undefined) { + if ((a.connectionId?.trim() || null) !== (b.connectionId?.trim() || null)) { + return true + } + } + const aHost = getKnownExecutionHostIdForWorktree(state, a.worktreeId) + const bHost = getKnownExecutionHostIdForWorktree(state, b.worktreeId) + if (!aHost || !bHost || parseExecutionHostId(aHost)?.kind === 'runtime') { + return false + } + return parseExecutionHostId(bHost)?.kind !== 'runtime' && aHost !== bHost +} From 8ce2a41e610a4c4528157619ed7dc4ac24f2fdbb Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 15 Oct 2026 22:15:32 -0700 Subject: [PATCH 7/9] fix(agents): resolve each record's machine from its own catalog or stamp evidence --- ...ping-agent-session-live-ssh-dedupe.test.ts | 18 +++++++++--- .../sleeping-record-execution-host-scope.ts | 28 +++++++++++-------- 2 files changed, 31 insertions(+), 15 deletions(-) diff --git a/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts b/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts index 0411d76b8ae5..b8d94bbdb308 100644 --- a/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts +++ b/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts @@ -217,10 +217,14 @@ describe('resumeSleepingAgentSessionsForWorktree — SSH panes and stale worktre expect(resumeSleepingAgentSessionsForWorktree('wt-1')).toBe(1) }) - // Matching ids on two machines (a copied state dir) are two sessions, not one. + // Matching ids on two machines (a copied state dir) are two sessions, not one. Here only the + // catalog names this record's machine and only the capture stamp names the other's. it('ignores a claim from a pane on a different machine than this record', () => { + const localPath = '/Users/neil/projects/wt-1' + const localWorktreeId = `repo-1::${localPath}` const local = makeRecord({ - connectionId: null, + paneKey: makePaneKey('tab-1', LEAF_ID), + worktreeId: localWorktreeId, providerSession: { key: 'session_id', id: 'sess-9' } }) const remote = makeRecord({ @@ -232,13 +236,19 @@ describe('resumeSleepingAgentSessionsForWorktree — SSH panes and stale worktre }) setStoreState({ activeWorktreeId: 'wt-other', - tabsByWorktree: { 'wt-1': [], 'wt-2': [makeTerminalTab('tab-2', 'wt-2')] }, + tabsByWorktree: { [localWorktreeId]: [], 'wt-2': [makeTerminalTab('tab-2', 'wt-2')] }, terminalLayoutsByTabId: { 'tab-2': makeLayout(OTHER_LEAF_ID, SSH_PTY_ID) }, ptyIdsByTabId: {}, + repos: [{ ...TEST_REPO, id: 'repo-1', path: '/Users/neil/projects' }], + worktreesByRepo: { + 'repo-1': [ + makeWorktree({ id: localWorktreeId, repoId: 'repo-1', path: localPath, hostId: 'local' }) + ] + }, sleepingAgentSessionsByPaneKey: { [local.paneKey]: local, [remote.paneKey]: remote } }) - expect(resumeSleepingAgentSessionsForWorktree('wt-1')).toBe(1) + expect(resumeSleepingAgentSessionsForWorktree(localWorktreeId)).toBe(1) }) it('does not let a finished note in another worktree clear an active record', () => { diff --git a/src/renderer/src/lib/sleeping-record-execution-host-scope.ts b/src/renderer/src/lib/sleeping-record-execution-host-scope.ts index 1920fd50b033..c01ab30a8740 100644 --- a/src/renderer/src/lib/sleeping-record-execution-host-scope.ts +++ b/src/renderer/src/lib/sleeping-record-execution-host-scope.ts @@ -75,6 +75,20 @@ export function sleepingRecordNamesAnotherExecutionHost( ) } +// Why each side alone: either the catalog or the capture stamp can be the only evidence for a record. +function resolveSleepingRecordMachine( + record: SleepingAgentSessionRecord, + state: WorktreeRuntimeOwnerState +): ExecutionHostId | null { + const host = getKnownExecutionHostIdForWorktree(state, record.worktreeId) + if (host && parseExecutionHostId(host)?.kind !== 'runtime') { + return host + } + // A null stamp is "local or paired runtime", so only an SSH stamp names a machine. + const stamp = record.connectionId?.trim() + return stamp ? toSshExecutionHostId(stamp) : null +} + /** * Do two records positively name different machines? Locators are machine-scoped, so a pane on one * machine never owns a session recorded on another, even when the ids match (a copied state dir). @@ -85,15 +99,7 @@ export function sleepingRecordsNameDifferentExecutionHosts( b: SleepingAgentSessionRecord, state: WorktreeRuntimeOwnerState ): boolean { - if (a.connectionId !== undefined && b.connectionId !== undefined) { - if ((a.connectionId?.trim() || null) !== (b.connectionId?.trim() || null)) { - return true - } - } - const aHost = getKnownExecutionHostIdForWorktree(state, a.worktreeId) - const bHost = getKnownExecutionHostIdForWorktree(state, b.worktreeId) - if (!aHost || !bHost || parseExecutionHostId(aHost)?.kind === 'runtime') { - return false - } - return parseExecutionHostId(bHost)?.kind !== 'runtime' && aHost !== bHost + const aMachine = resolveSleepingRecordMachine(a, state) + const bMachine = resolveSleepingRecordMachine(b, state) + return aMachine !== null && bMachine !== null && aMachine !== bMachine } From 326877772658c2f3e649b175adc89e083d76dac0 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 15 Oct 2026 22:23:37 -0700 Subject: [PATCH 8/9] fix(agents): judge a cross-workspace claim's host from owner rows, not the focused server The focus-read ratchet rejects new reads of the routing default; comparing two records' machines needs only each record's own workspace owner row. --- .../src/lib/resume-sleeping-agent-session.ts | 7 ++- .../sleeping-record-execution-host-scope.ts | 54 +++++++++++++++---- 2 files changed, 46 insertions(+), 15 deletions(-) diff --git a/src/renderer/src/lib/resume-sleeping-agent-session.ts b/src/renderer/src/lib/resume-sleeping-agent-session.ts index eea677084fa4..e1c6d1b45344 100644 --- a/src/renderer/src/lib/resume-sleeping-agent-session.ts +++ b/src/renderer/src/lib/resume-sleeping-agent-session.ts @@ -24,8 +24,8 @@ import { } from './host-mirrored-pane-liveness' import { parkUntilHostMirrorHandleLands } from './host-mirror-handle-gap-wait' import { - sleepingRecordNamesAnotherExecutionHost, - sleepingRecordsNameDifferentExecutionHosts + sleepingRecordHostAllowsSessionClaim, + sleepingRecordNamesAnotherExecutionHost } from './sleeping-record-execution-host-scope' import { resolveWorkspaceTerminalHostAuthority } from './workspace-terminal-host-authority' import { parkUntilHostSessionMirrorHydrates } from '@/runtime/host-session-mirror-hydration' @@ -190,8 +190,7 @@ function providerSessionOwnedElsewhere( other.agent === record.agent && !isInvalidWorktreeActivationRecord(other) && !activationTreatsNoteAsFinished(other) && - !sleepingRecordNamesAnotherExecutionHost(other, state) && - !sleepingRecordsNameDifferentExecutionHosts(record, other, state) && + sleepingRecordHostAllowsSessionClaim(other, record, state) && agentProviderSessionsEqual(record.agent, other.providerSession, record.providerSession) && recordPaneIsOwnedByPreservedPane(other, state) ) diff --git a/src/renderer/src/lib/sleeping-record-execution-host-scope.ts b/src/renderer/src/lib/sleeping-record-execution-host-scope.ts index c01ab30a8740..80a9d63bc777 100644 --- a/src/renderer/src/lib/sleeping-record-execution-host-scope.ts +++ b/src/renderer/src/lib/sleeping-record-execution-host-scope.ts @@ -1,9 +1,12 @@ import type { SleepingAgentSessionRecord } from '../../../shared/agent-session-resume' import { + getRepoExecutionHostId, parseExecutionHostId, toSshExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' +import { getRepoIdFromWorktreeId } from '@/store/slices/worktree-helpers' +import { findIndexedRepoOwner, findIndexedWorktreeOwner } from './worktree-runtime-owner-index' import { getKnownExecutionHostIdForWorktree } from './worktree-runtime-owner' import type { WorktreeRuntimeOwnerState } from './worktree-runtime-owner-state' @@ -75,12 +78,32 @@ export function sleepingRecordNamesAnotherExecutionHost( ) } -// Why each side alone: either the catalog or the capture stamp can be the only evidence for a record. +// Why owner rows only: two records' machines are a property of their own workspaces, never of the +// focused server, so this reads no routing default and an unknown owner stays unknown. +function ownerExecutionHostIdForRecord( + record: SleepingAgentSessionRecord, + state: WorktreeRuntimeOwnerState +): ExecutionHostId | null { + const worktree = findIndexedWorktreeOwner(state.worktreesByRepo, record.worktreeId) + const worktreeHost = parseExecutionHostId(worktree?.hostId)?.id + if (worktreeHost) { + return worktreeHost + } + const repo = findIndexedRepoOwner( + state.repos, + worktree?.repoId ?? getRepoIdFromWorktreeId(record.worktreeId) + ) + return repo && (repo.executionHostId?.trim() || repo.connectionId?.trim()) + ? getRepoExecutionHostId(repo) + : null +} + +// Why each side alone: either the owner row or the capture stamp can be the only evidence for a record. function resolveSleepingRecordMachine( record: SleepingAgentSessionRecord, state: WorktreeRuntimeOwnerState ): ExecutionHostId | null { - const host = getKnownExecutionHostIdForWorktree(state, record.worktreeId) + const host = ownerExecutionHostIdForRecord(record, state) if (host && parseExecutionHostId(host)?.kind !== 'runtime') { return host } @@ -90,16 +113,25 @@ function resolveSleepingRecordMachine( } /** - * Do two records positively name different machines? Locators are machine-scoped, so a pane on one - * machine never owns a session recorded on another, even when the ids match (a copied state dir). - * Fails open on the same unknowns as above: only a known disagreement counts. + * May `claimant`'s pane stand in for `record`'s session? Locators are machine-scoped, so not when the + * claimant's host moved since capture (it could not resume the session either), nor when the two + * records positively name different machines, even with matching ids (a copied state dir). Fails + * open on the same unknowns as above: only known disagreement blocks the claim. */ -export function sleepingRecordsNameDifferentExecutionHosts( - a: SleepingAgentSessionRecord, - b: SleepingAgentSessionRecord, +export function sleepingRecordHostAllowsSessionClaim( + claimant: SleepingAgentSessionRecord, + record: SleepingAgentSessionRecord, state: WorktreeRuntimeOwnerState ): boolean { - const aMachine = resolveSleepingRecordMachine(a, state) - const bMachine = resolveSleepingRecordMachine(b, state) - return aMachine !== null && bMachine !== null && aMachine !== bMachine + if ( + agentResumeOriginNamesAnotherExecutionHost( + claimant.connectionId, + ownerExecutionHostIdForRecord(claimant, state) + ) + ) { + return false + } + const claimantMachine = resolveSleepingRecordMachine(claimant, state) + const recordMachine = resolveSleepingRecordMachine(record, state) + return claimantMachine === null || recordMachine === null || claimantMachine === recordMachine } From d01252ee0be64f4811b1be45a3dc2a35786c4814 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 15 Oct 2026 22:28:28 -0700 Subject: [PATCH 9/9] fix(agents): resolve a folder workspace's host before it can claim a session --- ...ping-agent-session-live-ssh-dedupe.test.ts | 25 +++++++++++++++++++ .../sleeping-record-execution-host-scope.ts | 23 ++++++++++++++--- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts b/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts index b8d94bbdb308..117329b1e191 100644 --- a/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts +++ b/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts @@ -217,6 +217,31 @@ describe('resumeSleepingAgentSessionsForWorktree — SSH panes and stale worktre expect(resumeSleepingAgentSessionsForWorktree('wt-1')).toBe(1) }) + it('ignores a claim from a folder workspace whose host moved since capture', () => { + const folderWorkspaceId = 'folder:fw-1' + const local = makeRecord({ providerSession: { key: 'session_id', id: 'sess-9' } }) + const moved = makeRecord({ + paneKey: makePaneKey('tab-2', OTHER_LEAF_ID), + tabId: 'tab-2', + worktreeId: folderWorkspaceId, + connectionId: null, + providerSession: { key: 'session_id', id: 'sess-9' } + }) + setStoreState({ + activeWorktreeId: 'wt-other', + folderWorkspaces: [{ id: 'fw-1', connectionId: 'ssh-target-1', diffComments: [] }], + tabsByWorktree: { + 'wt-1': [], + [folderWorkspaceId]: [makeTerminalTab('tab-2', folderWorkspaceId)] + }, + terminalLayoutsByTabId: { 'tab-2': makeLayout(OTHER_LEAF_ID, SSH_PTY_ID) }, + ptyIdsByTabId: {}, + sleepingAgentSessionsByPaneKey: { [local.paneKey]: local, [moved.paneKey]: moved } + }) + + expect(resumeSleepingAgentSessionsForWorktree('wt-1')).toBe(1) + }) + // Matching ids on two machines (a copied state dir) are two sessions, not one. Here only the // catalog names this record's machine and only the capture stamp names the other's. it('ignores a claim from a pane on a different machine than this record', () => { diff --git a/src/renderer/src/lib/sleeping-record-execution-host-scope.ts b/src/renderer/src/lib/sleeping-record-execution-host-scope.ts index 80a9d63bc777..891c88158b3d 100644 --- a/src/renderer/src/lib/sleeping-record-execution-host-scope.ts +++ b/src/renderer/src/lib/sleeping-record-execution-host-scope.ts @@ -6,6 +6,11 @@ import { type ExecutionHostId } from '../../../shared/execution-host' import { getRepoIdFromWorktreeId } from '@/store/slices/worktree-helpers' +import { parseWorkspaceKey } from '../../../shared/workspace-scope' +import { + findFolderWorkspaceOwner, + type FolderWorkspaceRuntimeOwnerState +} from './folder-workspace-runtime-owner' import { findIndexedRepoOwner, findIndexedWorktreeOwner } from './worktree-runtime-owner-index' import { getKnownExecutionHostIdForWorktree } from './worktree-runtime-owner' import type { WorktreeRuntimeOwnerState } from './worktree-runtime-owner-state' @@ -78,12 +83,24 @@ export function sleepingRecordNamesAnotherExecutionHost( ) } +type SleepingRecordOwnerState = WorktreeRuntimeOwnerState & FolderWorkspaceRuntimeOwnerState + // Why owner rows only: two records' machines are a property of their own workspaces, never of the // focused server, so this reads no routing default and an unknown owner stays unknown. function ownerExecutionHostIdForRecord( record: SleepingAgentSessionRecord, - state: WorktreeRuntimeOwnerState + state: SleepingRecordOwnerState ): ExecutionHostId | null { + const workspaceScope = parseWorkspaceKey(record.worktreeId) + if (workspaceScope?.type === 'folder') { + const folder = findFolderWorkspaceOwner(state, workspaceScope.folderWorkspaceId) + const group = folder?.projectGroupId + ? state.projectGroups?.find((candidate) => candidate.id === folder.projectGroupId) + : undefined + const explicit = parseExecutionHostId(folder?.executionHostId ?? group?.executionHostId)?.id + const connectionId = folder?.connectionId?.trim() || group?.connectionId?.trim() + return explicit ?? (connectionId ? toSshExecutionHostId(connectionId) : null) + } const worktree = findIndexedWorktreeOwner(state.worktreesByRepo, record.worktreeId) const worktreeHost = parseExecutionHostId(worktree?.hostId)?.id if (worktreeHost) { @@ -101,7 +118,7 @@ function ownerExecutionHostIdForRecord( // Why each side alone: either the owner row or the capture stamp can be the only evidence for a record. function resolveSleepingRecordMachine( record: SleepingAgentSessionRecord, - state: WorktreeRuntimeOwnerState + state: SleepingRecordOwnerState ): ExecutionHostId | null { const host = ownerExecutionHostIdForRecord(record, state) if (host && parseExecutionHostId(host)?.kind !== 'runtime') { @@ -121,7 +138,7 @@ function resolveSleepingRecordMachine( export function sleepingRecordHostAllowsSessionClaim( claimant: SleepingAgentSessionRecord, record: SleepingAgentSessionRecord, - state: WorktreeRuntimeOwnerState + state: SleepingRecordOwnerState ): boolean { if ( agentResumeOriginNamesAnotherExecutionHost(