From bcb381e6eca3b9acfdf7ba788f57a90b98b16d00 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 30 Jun 2026 15:30:29 -0700 Subject: [PATCH] Prevent repeated automatic agent resume tabs (#6945) --- ...sume-sleeping-agent-session-replay.test.ts | 196 ++++++++++++++++++ .../lib/resume-sleeping-agent-session.test.ts | 1 + .../src/lib/resume-sleeping-agent-session.ts | 77 ++++++- src/renderer/src/lib/worktree-activation.ts | 7 +- .../src/store/slices/store-cascades.test.ts | 9 + .../store/slices/terminal-orphan-helpers.ts | 8 + src/renderer/src/store/slices/terminals.ts | 32 ++- .../src/store/slices/worktrees.test.ts | 76 +++++++ src/renderer/src/store/slices/worktrees.ts | 6 + 9 files changed, 409 insertions(+), 3 deletions(-) create mode 100644 src/renderer/src/lib/resume-sleeping-agent-session-replay.test.ts diff --git a/src/renderer/src/lib/resume-sleeping-agent-session-replay.test.ts b/src/renderer/src/lib/resume-sleeping-agent-session-replay.test.ts new file mode 100644 index 000000000..195fa7218 --- /dev/null +++ b/src/renderer/src/lib/resume-sleeping-agent-session-replay.test.ts @@ -0,0 +1,196 @@ +import { afterEach, describe, expect, it } from 'vitest' +import type { SleepingAgentSessionRecord } from '../../../shared/agent-session-resume' +import { useAppStore } from '@/store' +import { resumeSleepingAgentSessionsForWorktree } from './resume-sleeping-agent-session' +import { launchAiVaultSessionInNewTab } from './launch-ai-vault-session' +import { buildWorkspaceSessionPayload } from './workspace-session' + +const initialAppStoreState = useAppStore.getState() + +afterEach(() => { + useAppStore.setState(initialAppStoreState, true) +}) + +function makeRecord( + overrides: Partial = {} +): SleepingAgentSessionRecord { + return { + paneKey: 'old-tab:leaf-1', + tabId: 'old-tab', + worktreeId: 'wt-1', + agent: 'codex', + providerSession: { key: 'session_id', id: 'sess-1' }, + prompt: 'continue', + state: 'working', + capturedAt: 1, + updatedAt: 1, + origin: 'live', + ...overrides + } +} + +function makeTerminalTab(id: string): Record { + return { id, ptyId: null, worktreeId: 'wt-1', title: 'shell', sortOrder: 0, createdAt: 1 } +} + +describe('resumeSleepingAgentSessionsForWorktree replay protection', () => { + it('stores provider-session metadata in the queued startup and runtime claim', () => { + const record = makeRecord() + useAppStore.setState({ + tabsByWorktree: { 'wt-1': [] }, + sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } + } as never) + + expect(resumeSleepingAgentSessionsForWorktree('wt-1')).toBe(1) + const resumedTab = useAppStore.getState().tabsByWorktree['wt-1']![0]! + const state = useAppStore.getState() + expect(state.pendingStartupByTabId[resumedTab.id]?.resumeProviderSession).toEqual( + record.providerSession + ) + expect(state.automaticAgentResumeClaimsByTabId[resumedTab.id]).toEqual({ + worktreeId: record.worktreeId, + launchAgent: record.agent, + providerSession: record.providerSession + }) + }) + + it('does not fork a provider session that is already queued', () => { + const record = makeRecord() + useAppStore.setState({ + tabsByWorktree: { 'wt-1': [] }, + sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } + } as never) + + expect(resumeSleepingAgentSessionsForWorktree('wt-1')).toBe(1) + useAppStore.setState((state) => ({ + sleepingAgentSessionsByPaneKey: { + ...state.sleepingAgentSessionsByPaneKey, + [record.paneKey]: record + } + })) + + expect(resumeSleepingAgentSessionsForWorktree('wt-1')).toBe(0) + expect(useAppStore.getState().tabsByWorktree['wt-1']).toHaveLength(1) + expect(useAppStore.getState().sleepingAgentSessionsByPaneKey[record.paneKey]).toBeUndefined() + }) + + it('does not fork after startup is consumed but before hooks report live status', () => { + const record = makeRecord() + useAppStore.setState({ + tabsByWorktree: { 'wt-1': [] }, + sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } + } as never) + + expect(resumeSleepingAgentSessionsForWorktree('wt-1')).toBe(1) + const resumedTab = useAppStore.getState().tabsByWorktree['wt-1']![0]! + expect(useAppStore.getState().consumeTabStartupCommand(resumedTab.id)).not.toBeNull() + expect(useAppStore.getState().pendingStartupByTabId[resumedTab.id]).toBeUndefined() + + useAppStore.setState({ + sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } + } as never) + expect(resumeSleepingAgentSessionsForWorktree('wt-1')).toBe(0) + expect(useAppStore.getState().tabsByWorktree['wt-1']).toHaveLength(1) + expect(useAppStore.getState().sleepingAgentSessionsByPaneKey[record.paneKey]).toBeUndefined() + }) + + it('does not fork when the same provider session is already live', () => { + const record = makeRecord() + useAppStore.setState({ + tabsByWorktree: { 'wt-1': [makeTerminalTab('old-tab'), makeTerminalTab('live-tab')] }, + agentStatusByPaneKey: { + 'live-tab:leaf-1': { + state: 'working', + prompt: record.prompt, + updatedAt: 10, + stateStartedAt: 10, + agentType: record.agent, + paneKey: 'live-tab:leaf-1', + worktreeId: 'wt-1', + tabId: 'live-tab', + providerSession: record.providerSession + } + }, + sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } + } as never) + expect(resumeSleepingAgentSessionsForWorktree('wt-1')).toBe(0) + expect(useAppStore.getState().tabsByWorktree['wt-1']).toHaveLength(2) + expect(useAppStore.getState().sleepingAgentSessionsByPaneKey[record.paneKey]).toBeUndefined() + }) + + it('does not let another worktree claim block the same provider session id', () => { + const record = makeRecord() + useAppStore.setState({ + tabsByWorktree: { + 'wt-1': [], + 'wt-2': [{ ...makeTerminalTab('claimed-tab'), worktreeId: 'wt-2' }] + }, + automaticAgentResumeClaimsByTabId: { + 'claimed-tab': { + worktreeId: 'wt-2', + launchAgent: record.agent, + providerSession: record.providerSession + } + }, + sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } + } as never) + + expect(resumeSleepingAgentSessionsForWorktree('wt-1')).toBe(1) + expect(useAppStore.getState().tabsByWorktree['wt-1']).toHaveLength(1) + expect(useAppStore.getState().tabsByWorktree['wt-2']).toHaveLength(1) + }) + + it('clears runtime automatic-resume claims when the tab closes', () => { + const record = makeRecord() + useAppStore.setState({ + tabsByWorktree: { 'wt-1': [] }, + sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } + } as never) + + expect(resumeSleepingAgentSessionsForWorktree('wt-1')).toBe(1) + const resumedTab = useAppStore.getState().tabsByWorktree['wt-1']![0]! + expect(useAppStore.getState().automaticAgentResumeClaimsByTabId[resumedTab.id]).toBeDefined() + + useAppStore.getState().closeTab(resumedTab.id) + + expect(useAppStore.getState().automaticAgentResumeClaimsByTabId[resumedTab.id]).toBeUndefined() + }) + + it('does not include runtime automatic-resume claims in workspace-session payloads', () => { + useAppStore.setState({ + tabsByWorktree: { 'wt-1': [makeTerminalTab('tab-1')] }, + automaticAgentResumeClaimsByTabId: { + 'tab-1': { + worktreeId: 'wt-1', + launchAgent: 'codex', + providerSession: { key: 'session_id', id: 'sess-1' } + } + } + } as never) + + const payload = buildWorkspaceSessionPayload(useAppStore.getState()) + + expect('automaticAgentResumeClaimsByTabId' in payload).toBe(false) + }) + + it('leaves explicit AI Vault resumes outside automatic-resume claims', () => { + useAppStore.setState({ tabsByWorktree: { 'wt-1': [] } } as never) + + const first = launchAiVaultSessionInNewTab({ + agent: 'codex', + worktreeId: 'wt-1', + command: "codex resume 'sess-1'", + launchConfig: { agentArgs: '', agentEnv: {} } + }) + const second = launchAiVaultSessionInNewTab({ + agent: 'codex', + worktreeId: 'wt-1', + command: "codex resume 'sess-1'", + launchConfig: { agentArgs: '', agentEnv: {} } + }) + + expect(first.tabId).not.toBe(second.tabId) + expect(useAppStore.getState().tabsByWorktree['wt-1']).toHaveLength(2) + expect(useAppStore.getState().automaticAgentResumeClaimsByTabId).toEqual({}) + }) +}) diff --git a/src/renderer/src/lib/resume-sleeping-agent-session.test.ts b/src/renderer/src/lib/resume-sleeping-agent-session.test.ts index 0486ac64b..1af352155 100644 --- a/src/renderer/src/lib/resume-sleeping-agent-session.test.ts +++ b/src/renderer/src/lib/resume-sleeping-agent-session.test.ts @@ -544,6 +544,7 @@ describe('resumeSleepingAgentSessionsForWorktree', () => { expect(startup?.env).toEqual({ CODEX_PROFILE: 'captured' }) expect(startup?.command).not.toContain('changed') expect(startup?.launchConfig).toEqual(record.launchConfig) + expect(startup?.resumeProviderSession).toEqual(record.providerSession) }) it('launches once and clears skipped duplicates for the same provider session', () => { diff --git a/src/renderer/src/lib/resume-sleeping-agent-session.ts b/src/renderer/src/lib/resume-sleeping-agent-session.ts index 98452556b..3579ca804 100644 --- a/src/renderer/src/lib/resume-sleeping-agent-session.ts +++ b/src/renderer/src/lib/resume-sleeping-agent-session.ts @@ -10,7 +10,10 @@ import { resolveTuiAgentLaunchArgs, resolveTuiAgentLaunchEnv } from '../../../shared/tui-agent-launch-defaults' -import type { SleepingAgentSessionRecord } from '../../../shared/agent-session-resume' +import type { + AgentProviderSessionMetadata, + SleepingAgentSessionRecord +} from '../../../shared/agent-session-resume' import { translate } from '@/i18n/i18n' import { AGENT_STATUS_STALE_AFTER_MS } from '../../../shared/agent-status-types' import { @@ -89,6 +92,7 @@ function launchSleepingAgentSession(record: SleepingAgentSessionRecord): boolean command: startupPlan.launchCommand, ...(startupPlan.env ? { env: startupPlan.env } : {}), launchConfig: startupPlan.launchConfig, + resumeProviderSession: record.providerSession, launchAgent: record.agent, ...(startupPlan.startupCommandDelivery ? { startupCommandDelivery: startupPlan.startupCommandDelivery } @@ -100,6 +104,11 @@ function launchSleepingAgentSession(record: SleepingAgentSessionRecord): boolean request_kind: 'resume' } }) + state.claimAutomaticAgentResume(tab.id, { + worktreeId: record.worktreeId, + launchAgent: record.agent, + providerSession: record.providerSession + }) state.clearSleepingAgentSession(record.paneKey) state.setActiveTabType('terminal') appendTabToWorktreeOrder(record.worktreeId, tab.id) @@ -158,6 +167,66 @@ function getNewestActiveRecordsByClaimKey( return newestRecords } +function providerSessionsMatch( + left: AgentProviderSessionMetadata | undefined, + right: AgentProviderSessionMetadata +): boolean { + return Boolean(left && left.key === right.key && left.id === right.id) +} + +function getAgentStatusTabId(entry: { + paneKey: string + tabId?: string | undefined +}): string | null { + if (entry.tabId) { + return entry.tabId + } + const separatorIndex = entry.paneKey.indexOf(':') + return separatorIndex === -1 ? null : entry.paneKey.slice(0, separatorIndex) +} + +function activeOrQueuedResumeClaimsProviderSession( + record: SleepingAgentSessionRecord, + state: ReturnType +): boolean { + const worktreeTabIds = new Set( + (state.tabsByWorktree[record.worktreeId] ?? []).map((tab) => tab.id) + ) + for (const entry of Object.values(state.agentStatusByPaneKey)) { + if ( + worktreeTabIds.has(getAgentStatusTabId(entry) ?? '') && + entry.worktreeId === record.worktreeId && + entry.agentType === record.agent && + entry.state !== 'done' && + providerSessionsMatch(entry.providerSession, record.providerSession) + ) { + return true + } + } + + for (const [tabId, startup] of Object.entries(state.pendingStartupByTabId)) { + if ( + worktreeTabIds.has(tabId) && + startup.launchAgent === record.agent && + providerSessionsMatch(startup.resumeProviderSession, record.providerSession) + ) { + return true + } + } + + for (const [tabId, claim] of Object.entries(state.automaticAgentResumeClaimsByTabId)) { + if ( + worktreeTabIds.has(tabId) && + claim.worktreeId === record.worktreeId && + claim.launchAgent === record.agent && + providerSessionsMatch(claim.providerSession, record.providerSession) + ) { + return true + } + } + return false +} + function isInvalidWorktreeActivationRecord(record: SleepingAgentSessionRecord): boolean { if (record.interrupted === true) { return true @@ -205,6 +274,12 @@ export function resumeSleepingAgentSessionsForWorktree(worktreeId: string): numb } continue } + if (activeOrQueuedResumeClaimsProviderSession(record, currentState)) { + // Why: main can replay the old wake record after the same provider + // session was already queued in a fresh tab; clear the stale replay. + state.clearSleepingAgentSession(record.paneKey) + continue + } const paneOwnedClaimKeys = getCurrentPaneOwnedClaimKeys(activeWorktreeRecords) if (paneOwnedClaimKeys.has(claimKey)) { if (!isPaneOwned) { diff --git a/src/renderer/src/lib/worktree-activation.ts b/src/renderer/src/lib/worktree-activation.ts index 08b1568c0..aaa84f3a2 100644 --- a/src/renderer/src/lib/worktree-activation.ts +++ b/src/renderer/src/lib/worktree-activation.ts @@ -11,7 +11,10 @@ import type { } from '../../../shared/types' import type { EventProps } from '../../../shared/telemetry-events' import type { StartupCommandDelivery } from '../../../shared/codex-startup-delivery' -import type { SleepingAgentLaunchConfig } from '../../../shared/agent-session-resume' +import type { + AgentProviderSessionMetadata, + SleepingAgentLaunchConfig +} from '../../../shared/agent-session-resume' import { shouldAutoCreateInitialTerminal } from '@/components/terminal/initial-terminal' import { buildSetupRunnerCommand } from './setup-runner' import { createSequencedSetupAgentCommands } from '../../../shared/setup-agent-sequencing' @@ -70,6 +73,7 @@ export type WorktreeStartupPayload = { command: string env?: Record launchConfig?: SleepingAgentLaunchConfig + resumeProviderSession?: AgentProviderSessionMetadata launchToken?: string launchAgent?: TuiAgent startupCommandDelivery?: StartupCommandDelivery @@ -116,6 +120,7 @@ type WorktreeActivationStore = Partial & { command: string env?: Record launchConfig?: SleepingAgentLaunchConfig + resumeProviderSession?: AgentProviderSessionMetadata launchToken?: string launchAgent?: TuiAgent initialAgentStatus?: { agent: TuiAgent; prompt: string } diff --git a/src/renderer/src/store/slices/store-cascades.test.ts b/src/renderer/src/store/slices/store-cascades.test.ts index c27533483..6412e2c19 100644 --- a/src/renderer/src/store/slices/store-cascades.test.ts +++ b/src/renderer/src/store/slices/store-cascades.test.ts @@ -1806,6 +1806,7 @@ describe('setActiveWorktree', () => { 'pendingInitialCwdByTabId', 'pendingSetupSplitByTabId', 'pendingIssueCommandSplitByTabId', + 'automaticAgentResumeClaimsByTabId', 'tabBarOrderByWorktree', 'cacheTimerByKey', 'activeTabIdByWorktree' @@ -1844,6 +1845,13 @@ describe('setActiveWorktree', () => { pendingStartupByTabId: { [orphanId]: { command: 'codex' } }, + automaticAgentResumeClaimsByTabId: { + [orphanId]: { + worktreeId: wt, + launchAgent: 'codex', + providerSession: { key: 'session_id', id: 'sess-1' } + } + }, pendingInitialCwdByTabId: { [orphanId]: '/repo/packages/web' }, @@ -1867,6 +1875,7 @@ describe('setActiveWorktree', () => { expect(s.runtimePaneTitlesByTabId[orphanId]).toBeUndefined() expect(s.terminalLayoutsByTabId[orphanId]).toBeUndefined() expect(s.pendingStartupByTabId[orphanId]).toBeUndefined() + expect(s.automaticAgentResumeClaimsByTabId[orphanId]).toBeUndefined() expect(s.pendingInitialCwdByTabId[orphanId]).toBeUndefined() expect(s.cacheTimerByKey[`${orphanId}:seed`]).toBeUndefined() expect(s.terminalLayoutsByTabId[replacement.id]).toEqual(makeLayout()) diff --git a/src/renderer/src/store/slices/terminal-orphan-helpers.ts b/src/renderer/src/store/slices/terminal-orphan-helpers.ts index bb388fad3..b6ffe73f9 100644 --- a/src/renderer/src/store/slices/terminal-orphan-helpers.ts +++ b/src/renderer/src/store/slices/terminal-orphan-helpers.ts @@ -17,6 +17,7 @@ type OrphanTerminalCleanupState = Pick< | 'pendingInitialCwdByTabId' | 'pendingSetupSplitByTabId' | 'pendingIssueCommandSplitByTabId' + | 'automaticAgentResumeClaimsByTabId' | 'tabBarOrderByWorktree' | 'cacheTimerByKey' | 'activeTabIdByWorktree' @@ -63,6 +64,7 @@ export function buildOrphanTerminalCleanupPatch( | 'pendingInitialCwdByTabId' | 'pendingSetupSplitByTabId' | 'pendingIssueCommandSplitByTabId' + | 'automaticAgentResumeClaimsByTabId' | 'tabBarOrderByWorktree' | 'cacheTimerByKey' | 'activeTabIdByWorktree' @@ -80,6 +82,7 @@ export function buildOrphanTerminalCleanupPatch( pendingInitialCwdByTabId: state.pendingInitialCwdByTabId, pendingSetupSplitByTabId: state.pendingSetupSplitByTabId, pendingIssueCommandSplitByTabId: state.pendingIssueCommandSplitByTabId, + automaticAgentResumeClaimsByTabId: state.automaticAgentResumeClaimsByTabId, tabBarOrderByWorktree: state.tabBarOrderByWorktree, cacheTimerByKey: state.cacheTimerByKey, activeTabIdByWorktree: state.activeTabIdByWorktree, @@ -99,6 +102,9 @@ export function buildOrphanTerminalCleanupPatch( const nextPendingInitialCwdByTabId = { ...state.pendingInitialCwdByTabId } const nextPendingSetupSplitByTabId = { ...state.pendingSetupSplitByTabId } const nextPendingIssueCommandSplitByTabId = { ...state.pendingIssueCommandSplitByTabId } + const nextAutomaticAgentResumeClaimsByTabId = { + ...state.automaticAgentResumeClaimsByTabId + } const nextTabBarOrderByWorktree = { ...state.tabBarOrderByWorktree, [worktreeId]: (state.tabBarOrderByWorktree[worktreeId] ?? []).filter( @@ -121,6 +127,7 @@ export function buildOrphanTerminalCleanupPatch( delete nextPendingInitialCwdByTabId[orphanTabId] delete nextPendingSetupSplitByTabId[orphanTabId] delete nextPendingIssueCommandSplitByTabId[orphanTabId] + delete nextAutomaticAgentResumeClaimsByTabId[orphanTabId] for (const key of Object.keys(nextCacheTimerByKey)) { if (key.startsWith(`${orphanTabId}:`)) { delete nextCacheTimerByKey[key] @@ -149,6 +156,7 @@ export function buildOrphanTerminalCleanupPatch( pendingInitialCwdByTabId: nextPendingInitialCwdByTabId, pendingSetupSplitByTabId: nextPendingSetupSplitByTabId, pendingIssueCommandSplitByTabId: nextPendingIssueCommandSplitByTabId, + automaticAgentResumeClaimsByTabId: nextAutomaticAgentResumeClaimsByTabId, tabBarOrderByWorktree: nextTabBarOrderByWorktree, cacheTimerByKey: nextCacheTimerByKey, activeTabIdByWorktree: nextActiveTabIdByWorktree, diff --git a/src/renderer/src/store/slices/terminals.ts b/src/renderer/src/store/slices/terminals.ts index 0271c8aee..295c63eab 100644 --- a/src/renderer/src/store/slices/terminals.ts +++ b/src/renderer/src/store/slices/terminals.ts @@ -11,7 +11,10 @@ import type { WorkspaceKey, WorkspaceSessionState } from '../../../../shared/types' -import type { SleepingAgentLaunchConfig } from '../../../../shared/agent-session-resume' +import type { + AgentProviderSessionMetadata, + SleepingAgentLaunchConfig +} from '../../../../shared/agent-session-resume' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' import { folderWorkspaceKey, @@ -290,6 +293,12 @@ function equalStringSets(a: readonly string[], b: readonly string[]): boolean { return a.every((value) => bSet.has(value)) } +export type AutomaticAgentResumeClaim = { + worktreeId: string + launchAgent: TuiAgent + providerSession: AgentProviderSessionMetadata +} + export type TerminalSlice = { tabsByWorktree: Record activeTabId: string | null @@ -327,6 +336,10 @@ export type TerminalSlice = { * split-button label across sessions. */ recentQuickCommandIdByGroup: Record setRecentQuickCommandForGroup: (groupId: string, quickCommandId: string) => void + /** Runtime-only claim for automatic sleeping-session recovery tabs. It + * bridges the gap after startup payload consumption and before hooks go live. */ + automaticAgentResumeClaimsByTabId: Record + claimAutomaticAgentResume: (tabId: string, claim: AutomaticAgentResumeClaim) => void pendingStartupByTabId: Record< string, { @@ -337,6 +350,7 @@ export type TerminalSlice = { startupCommandDelivery?: StartupCommandDelivery env?: Record launchConfig?: SleepingAgentLaunchConfig + resumeProviderSession?: AgentProviderSessionMetadata launchToken?: string launchAgent?: TuiAgent /** Initial prompt-start status for agents that lack native prompt hooks. */ @@ -498,6 +512,7 @@ export type TerminalSlice = { startupCommandDelivery?: StartupCommandDelivery env?: Record launchConfig?: SleepingAgentLaunchConfig + resumeProviderSession?: AgentProviderSessionMetadata launchToken?: string launchAgent?: TuiAgent initialAgentStatus?: { agent: TuiAgent; prompt: string } @@ -513,6 +528,7 @@ export type TerminalSlice = { startupCommandDelivery?: StartupCommandDelivery env?: Record launchConfig?: SleepingAgentLaunchConfig + resumeProviderSession?: AgentProviderSessionMetadata launchToken?: string launchAgent?: TuiAgent initialAgentStatus?: { agent: TuiAgent; prompt: string } @@ -579,6 +595,7 @@ export const createTerminalSlice: StateCreator pendingInitialCwdByTabId: {}, pendingSetupSplitByTabId: {}, pendingIssueCommandSplitByTabId: {}, + automaticAgentResumeClaimsByTabId: {}, tabBarOrderByWorktree: {}, workspaceSessionReady: false, defaultTerminalTabsAppliedByWorktreeId: {}, @@ -619,6 +636,15 @@ export const createTerminalSlice: StateCreator })) }, + claimAutomaticAgentResume: (tabId, claim) => { + set((s) => ({ + automaticAgentResumeClaimsByTabId: { + ...s.automaticAgentResumeClaimsByTabId, + [tabId]: claim + } + })) + }, + recordTerminalInput: (paneKey, timestamp = Date.now()) => { if (!paneKey || !Number.isFinite(timestamp)) { return @@ -1021,6 +1047,8 @@ export const createTerminalSlice: StateCreator } const nextPendingStartupByTabId = { ...s.pendingStartupByTabId } delete nextPendingStartupByTabId[tabId] + const nextAutomaticAgentResumeClaimsByTabId = { ...s.automaticAgentResumeClaimsByTabId } + delete nextAutomaticAgentResumeClaimsByTabId[tabId] const nextPendingInitialCwdByTabId = { ...s.pendingInitialCwdByTabId } delete nextPendingInitialCwdByTabId[tabId] const nextPendingSetupSplitByTabId = { ...s.pendingSetupSplitByTabId } @@ -1097,6 +1125,7 @@ export const createTerminalSlice: StateCreator canExpandPaneByTabId: nextCanExpand, terminalLayoutsByTabId: nextLayouts, pendingStartupByTabId: nextPendingStartupByTabId, + automaticAgentResumeClaimsByTabId: nextAutomaticAgentResumeClaimsByTabId, pendingInitialCwdByTabId: nextPendingInitialCwdByTabId, pendingSetupSplitByTabId: nextPendingSetupSplitByTabId, pendingIssueCommandSplitByTabId: nextPendingIssueCommandSplitByTabId, @@ -2833,6 +2862,7 @@ export const createTerminalSlice: StateCreator lastVisitedAtByWorktreeId: session.lastVisitedAtByWorktreeId ?? {}, defaultTerminalTabsAppliedByWorktreeId: session.defaultTerminalTabsAppliedByWorktreeId ?? {}, + automaticAgentResumeClaimsByTabId: {}, sleepingAgentSessionsByPaneKey, pendingReconnectWorktreeIds, pendingReconnectTabByWorktree, diff --git a/src/renderer/src/store/slices/worktrees.test.ts b/src/renderer/src/store/slices/worktrees.test.ts index b290b736b..ce3ba3176 100644 --- a/src/renderer/src/store/slices/worktrees.test.ts +++ b/src/renderer/src/store/slices/worktrees.test.ts @@ -9,6 +9,7 @@ import type { DetectedWorktreeListResult, FolderWorkspace, LocalBaseRefRefreshResult, + TerminalTab, Worktree, WorktreeLineage, WorkspaceLineage @@ -197,6 +198,18 @@ function makeWorktree(overrides: Partial & { id: string; repoId: strin } } +function makeTerminalTab(overrides: Partial & { id: string; worktreeId: string }) { + return { + ptyId: null, + title: 'Terminal', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1, + ...overrides + } +} + function createWebview(overrides: Partial = {}): Electron.WebviewTag { return { style: {}, @@ -3227,6 +3240,50 @@ describe('removeWorktree state cleanup', () => { expect(getHostedReviewLinkMutationGenerationForTests(surviving.id)).toBeGreaterThan(0) }) + it('cleans up automatic agent resume claims for removed worktree tabs', async () => { + const store = createTestStore() + const removed = makeWorktree({ + id: 'repo1::/path/wt1', + repoId: 'repo1', + path: '/path/wt1' + }) + const surviving = makeWorktree({ + id: 'repo1::/path/wt2', + repoId: 'repo1', + path: '/path/wt2' + }) + + store.setState({ + worktreesByRepo: { repo1: [removed, surviving] }, + tabsByWorktree: { + [removed.id]: [makeTerminalTab({ id: 'removed-tab', worktreeId: removed.id })], + [surviving.id]: [makeTerminalTab({ id: 'surviving-tab', worktreeId: surviving.id })] + }, + automaticAgentResumeClaimsByTabId: { + 'removed-tab': { + worktreeId: removed.id, + launchAgent: 'codex', + providerSession: { key: 'session_id', id: 'removed-session' } + }, + 'surviving-tab': { + worktreeId: surviving.id, + launchAgent: 'codex', + providerSession: { key: 'session_id', id: 'surviving-session' } + } + } + } as Partial) + + await store.getState().removeWorktree(removed.id) + + expect(store.getState().automaticAgentResumeClaimsByTabId).toEqual({ + 'surviving-tab': { + worktreeId: surviving.id, + launchAgent: 'codex', + providerSession: { key: 'session_id', id: 'surviving-session' } + } + }) + }) + it('purges the orphaned project that pointed at a destroyed runtime-owned SSH target', async () => { const store = createTestStore() const wt = makeWorktree({ id: 'repo1::/path/wt1', repoId: 'repo1', path: '/path/wt1' }) @@ -5792,6 +5849,18 @@ describe('purgeWorktreeTerminalState direct (design §4.4)', () => { }, ptyIdsByTabId: { 'tab-1': ['pty-1'], 'tab-2': ['pty-2'], 'tab-3': ['pty-3'] }, runtimePaneTitlesByTabId: { 'tab-1': 'claude', 'tab-3': 'bash' }, + automaticAgentResumeClaimsByTabId: { + 'tab-1': { + worktreeId: 'repoA::/a/wt1', + launchAgent: 'codex', + providerSession: { key: 'session_id', id: 'sess-1' } + }, + 'tab-3': { + worktreeId: 'repoA::/a/wt2', + launchAgent: 'codex', + providerSession: { key: 'session_id', id: 'sess-3' } + } + }, openFiles: [ { id: 'file-1', @@ -5845,6 +5914,13 @@ describe('purgeWorktreeTerminalState direct (design §4.4)', () => { expect(s.terminalLayoutsByTabId).toEqual({ 'tab-3': { panes: [] } }) expect(s.ptyIdsByTabId).toEqual({ 'tab-3': ['pty-3'] }) expect(s.runtimePaneTitlesByTabId).toEqual({ 'tab-3': 'bash' }) + expect(s.automaticAgentResumeClaimsByTabId).toEqual({ + 'tab-3': { + worktreeId: 'repoA::/a/wt2', + launchAgent: 'codex', + providerSession: { key: 'session_id', id: 'sess-3' } + } + }) expect(s.openFiles).toEqual([]) expect(s.editorDrafts).toEqual({ 'file-99': 'other' }) expect(s.markdownFrontmatterVisible).toEqual({ 'file-99': true }) diff --git a/src/renderer/src/store/slices/worktrees.ts b/src/renderer/src/store/slices/worktrees.ts index ee25d93c8..2ddc8100a 100644 --- a/src/renderer/src/store/slices/worktrees.ts +++ b/src/renderer/src/store/slices/worktrees.ts @@ -1968,6 +1968,7 @@ function buildWorktreePurgeState(s: AppState, worktreeIds: string[]): Partial const nextLayouts = { ...s.terminalLayoutsByTabId } const nextPtyIdsByTabId = { ...s.ptyIdsByTabId } const nextRuntimePaneTitlesByTabId = { ...s.runtimePaneTitlesByTabId } + const nextAutomaticAgentResumeClaimsByTabId = { + ...s.automaticAgentResumeClaimsByTabId + } for (const tabId of tabIds) { delete nextLayouts[tabId] delete nextPtyIdsByTabId[tabId] delete nextRuntimePaneTitlesByTabId[tabId] + delete nextAutomaticAgentResumeClaimsByTabId[tabId] } const nextDeleteState = { ...s.deleteStateByWorktreeId } delete nextDeleteState[worktreeId] @@ -3199,6 +3204,7 @@ export const createWorktreeSlice: StateCreator tabsByWorktree: nextTabs, ptyIdsByTabId: nextPtyIdsByTabId, runtimePaneTitlesByTabId: nextRuntimePaneTitlesByTabId, + automaticAgentResumeClaimsByTabId: nextAutomaticAgentResumeClaimsByTabId, terminalLayoutsByTabId: nextLayouts, deleteStateByWorktreeId: nextDeleteState, baseStatusByWorktreeId: (() => {