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..117329b1e191 --- /dev/null +++ b/src/renderer/src/lib/resume-sleeping-agent-session-live-ssh-dedupe.test.ts @@ -0,0 +1,301 @@ +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() +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 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 { + 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() + 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 } + }) + + const launched = resumeSleepingAgentSessionsForWorktree('wt-1') + + expect(launched).toBe(0) + 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' }) + 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 } + }) + + const launched = resumeSleepingAgentSessionsForWorktree('wt-1') + + expect(launched).toBe(1) + }) + + it("does not credit a split leaf with another leaf's ssh pty", () => { + const record = makeRecord() + setStoreState({ + 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 } + }) + + 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() + setStoreState({ + activeWorktreeId: 'wt-other', + tabsByWorktree: { 'wt-1': [makeTerminalTab('tab-1', 'wt-1')] }, + terminalLayoutsByTabId: { 'tab-1': makeLayout(LEAF_ID, null) }, + ptyIdsByTabId: {}, + sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } + }) + + const launched = resumeSleepingAgentSessionsForWorktree('wt-1') + + expect(launched).toBe(1) + }) + + it('finds the preserved tab when the record worktreeId is stale', () => { + const record = makeRecord() + 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 } + }) + + 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' } + }) + 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 } + }) + + 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) + }) + + // 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('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', () => { + const localPath = '/Users/neil/projects/wt-1' + const localWorktreeId = `repo-1::${localPath}` + const local = makeRecord({ + paneKey: makePaneKey('tab-1', LEAF_ID), + worktreeId: localWorktreeId, + 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: { [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(localWorktreeId)).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({ + paneKey: makePaneKey('tab-2', OTHER_LEAF_ID), + tabId: 'tab-2', + worktreeId: 'wt-2', + origin: 'live', + state: 'done', + 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, null) }, + ptyIdsByTabId: {}, + sleepingAgentSessionsByPaneKey: { [active.paneKey]: active, [finished.paneKey]: finished } + }) + + 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 bb9a84a912a4..e1c6d1b45344 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 { + sleepingRecordHostAllowsSessionClaim, + sleepingRecordNamesAnotherExecutionHost +} from './sleeping-record-execution-host-scope' import { resolveWorkspaceTerminalHostAuthority } from './workspace-terminal-host-authority' import { parkUntilHostSessionMirrorHydrates } from '@/runtime/host-session-mirror-hydration' @@ -175,6 +178,24 @@ function activeOrQueuedResumeClaimsProviderSession( return false } +function providerSessionOwnedElsewhere( + record: SleepingAgentSessionRecord, + state: ReturnType +): boolean { + // Same-worktree duplicates are handled by claim keys; finished notes never claim a session, and + // 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 && + other.agent === record.agent && + !isInvalidWorktreeActivationRecord(other) && + !activationTreatsNoteAsFinished(other) && + sleepingRecordHostAllowsSessionClaim(other, record, state) && + 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 +344,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..e2a4e19d3e15 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,27 @@ function paneWillConnectOnActivation( return !isWebTerminalSurfaceTabId(tabId) } +// Why: a record's worktreeId can be stale (e.g. agent-managed checkout); tab ids are global. +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 +164,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 +192,17 @@ export function recordPaneIsOwnedByPreservedPane( ) { return true } + // 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 = + 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 + } // 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 +212,7 @@ export function recordPaneIsOwnedByPreservedPane( stable.leafId, state.ptyIdsByTabId, state.terminalLayoutsByTabId - ) && paneWillConnectOnActivation(record.worktreeId, tabId, state) + ) && paneWillConnectOnActivation(owner.worktreeId, tabId, 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..891c88158b3d 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,17 @@ 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 { 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' @@ -74,3 +82,73 @@ export function sleepingRecordNamesAnotherExecutionHost( getKnownExecutionHostIdForWorktree(state, record.worktreeId) ) } + +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: 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) { + 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: SleepingRecordOwnerState +): ExecutionHostId | null { + const host = ownerExecutionHostIdForRecord(record, state) + 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 +} + +/** + * 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 sleepingRecordHostAllowsSessionClaim( + claimant: SleepingAgentSessionRecord, + record: SleepingAgentSessionRecord, + state: SleepingRecordOwnerState +): boolean { + 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 +}