diff --git a/src/main/ai-vault/cached-session-list.ts b/src/main/ai-vault/cached-session-list.ts index 673de66e666e..8a02ee2f6bf4 100644 --- a/src/main/ai-vault/cached-session-list.ts +++ b/src/main/ai-vault/cached-session-list.ts @@ -109,7 +109,7 @@ export async function listAiVaultSessions( force: args?.force, signal: options.signal, start: async (scanSignal) => { - const result = await scanAiVaultSessionsInBackground( + const scanned = await scanAiVaultSessionsInBackground( { limit: args?.limit, unlimited: args?.unlimited, @@ -118,6 +118,9 @@ export async function listAiVaultSessions( }, scanSignal ) + // The bound this scan ran under, echoed so a reader can tell a whole answer from a slice + // instead of guessing from the row count. + const result: AiVaultListResult = { ...scanned, appliedSessionDepth: depth } // A delete (or other invalidation) landed while this scan was running: // its result predates the delete, so caching it would resurrect the // deleted session for the TTL. Return it to this caller but don't cache. diff --git a/src/main/ai-vault/remote-session-scanner.test.ts b/src/main/ai-vault/remote-session-scanner.test.ts index c1c99bcbf129..f38338b7dcf8 100644 --- a/src/main/ai-vault/remote-session-scanner.test.ts +++ b/src/main/ai-vault/remote-session-scanner.test.ts @@ -3,6 +3,7 @@ import { getRemoteHostPlatform } from '../ssh/ssh-remote-platform' import { scanRemoteAiVaultSessions } from './remote-session-scanner' import { MemoryRemoteProvider, jsonLines } from './remote-session-scanner-test-fixtures' import { primeAgentFixture } from './session-scanner-prime-agent-fixtures' +import { DEFAULT_AI_VAULT_SCAN_LIMIT } from '../../shared/ai-vault-session-depth' describe('scanRemoteAiVaultSessions', () => { it('indexes Cline manifests on the SSH-owned disk without messages-file phantoms', async () => { @@ -45,6 +46,9 @@ describe('scanRemoteAiVaultSessions', () => { }) expect(result.issues).toEqual([]) + // Silence here is read downstream as a possible slice, which refuses recovery on every + // SSH host; the scan must say the bound it actually ran under. + expect(result.appliedSessionDepth).toBe(DEFAULT_AI_VAULT_SCAN_LIMIT) expect(result.sessions).toHaveLength(1) expect(result.sessions[0]).toMatchObject({ agent: 'cline', diff --git a/src/main/ai-vault/remote-session-scanner.ts b/src/main/ai-vault/remote-session-scanner.ts index 2ebaba9103ac..9caae0f5708c 100644 --- a/src/main/ai-vault/remote-session-scanner.ts +++ b/src/main/ai-vault/remote-session-scanner.ts @@ -35,7 +35,7 @@ import { recordSessionScanIssue } from './session-scan-issues' import { canStopParsingSessions } from './session-scan-cutoff' import { refreshCodexTitleFromIndex } from './session-scanner-codex-cached-title' import { limitRemoteScanFilesystemConcurrency } from './remote-session-scan-concurrency' -import { aiVaultScanLimit } from '../../shared/ai-vault-session-depth' +import { aiVaultScanLimit, requestedAiVaultSessionDepth } from '../../shared/ai-vault-session-depth' const REMOTE_SCAN_CONCURRENCY = 8 const REMOTE_PARSE_CANDIDATE_MULTIPLIER = 2 @@ -129,7 +129,10 @@ export async function scanRemoteAiVaultSessions(args: { return { sessions: mergeRemoteSessions(cappedSessions, scopeSessions), issues, - scannedAt: new Date().toISOString() + scannedAt: new Date().toISOString(), + // Echo the bound this scan ran under. Silence here is read downstream as a possible slice, + // which refuses recovery on every SSH host. + appliedSessionDepth: requestedAiVaultSessionDepth(args) } } diff --git a/src/main/ai-vault/runtime-session-scanner.test.ts b/src/main/ai-vault/runtime-session-scanner.test.ts index 922a6af96d7c..4d2348d2baee 100644 --- a/src/main/ai-vault/runtime-session-scanner.test.ts +++ b/src/main/ai-vault/runtime-session-scanner.test.ts @@ -116,6 +116,19 @@ describe('runtime AI Vault session scanner', () => { ]) }) + it('keeps the scan depth the host applied, so coverage is not read as truncated', async () => { + mocks.callRuntimeEnvironment.mockResolvedValueOnce({ + ok: true, + result: { ...result([session('local', 'session-1')]), appliedSessionDepth: 'unlimited' } + }) + + const scanResult = await scanRuntimeAiVaultSessions('/user-data', 'env-1', {}) + + // Retagging owns host identity only. Dropping this field reads downstream as a truncated + // scan, which refuses recovery on every runtime host. + expect(scanResult.appliedSessionDepth).toBe('unlimited') + }) + it('stamps accepted sessions with the requested runtime host', async () => { const scanResult = await scanRuntimeAiVaultSessions('/user-data', 'env-1', {}) diff --git a/src/main/ai-vault/runtime-session-scanner.ts b/src/main/ai-vault/runtime-session-scanner.ts index b876c029b451..6d5d0dab6124 100644 --- a/src/main/ai-vault/runtime-session-scanner.ts +++ b/src/main/ai-vault/runtime-session-scanner.ts @@ -155,10 +155,13 @@ function withRuntimeExecutionHost( result: AiVaultListResult, executionHostId: `runtime:${string}` ): AiVaultListResult { + // Spread, not a field list: retagging owns host identity only. Rebuilding the result by hand + // silently drops whatever else the host answered — `appliedSessionDepth` went that way, and its + // absence reads as a truncated scan, which disables recovery for every runtime host. return { + ...result, sessions: result.sessions.map((session) => retagRuntimeSession(session, executionHostId)), - issues: result.issues.map((issue) => ({ ...issue, executionHostId })), - scannedAt: result.scannedAt + issues: result.issues.map((issue) => ({ ...issue, executionHostId })) } } diff --git a/src/main/ai-vault/session-list-result-validation.test.ts b/src/main/ai-vault/session-list-result-validation.test.ts index 484b8c4eb6de..a314d742c7e6 100644 --- a/src/main/ai-vault/session-list-result-validation.test.ts +++ b/src/main/ai-vault/session-list-result-validation.test.ts @@ -19,6 +19,43 @@ describe('parseAiVaultListResult', () => { ) }) + // EP-COMPAT: hosts and clients update independently, so both wire shapes have to survive this + // parser — it rebuilds the result field by field and would otherwise drop what it does not name. + it('carries the depth a newer host says it applied', () => { + const parsed = parseAiVaultListResult({ + sessions: [validSession()], + issues: [], + scannedAt: '2026-07-27T00:00:00.000Z', + appliedSessionDepth: 'unlimited' + }) + + expect(parsed.appliedSessionDepth).toBe('unlimited') + }) + + it('leaves the applied depth absent for a host that predates the field', () => { + const parsed = parseAiVaultListResult({ + sessions: [validSession()], + issues: [], + scannedAt: '2026-07-27T00:00:00.000Z' + }) + + expect(parsed.appliedSessionDepth).toBeUndefined() + }) + + // A value this build cannot read is no more provable than silence, so it degrades to absent + // rather than to a number a reader would trust. + it('drops a malformed applied depth instead of failing the whole result', () => { + const parsed = parseAiVaultListResult({ + sessions: [validSession()], + issues: [], + scannedAt: '2026-07-27T00:00:00.000Z', + appliedSessionDepth: 'most-of-them' + }) + + expect(parsed.sessions).toHaveLength(1) + expect(parsed.appliedSessionDepth).toBeUndefined() + }) + it('keeps known-agent sessions while silently dropping unknown-agent rows', () => { const parsed = parseAiVaultListResult({ sessions: [validSession(), { ...validSession('session-new'), agent: 'future-agent' }], diff --git a/src/main/ai-vault/session-list-result-validation.ts b/src/main/ai-vault/session-list-result-validation.ts index 4ba72fdd43be..c9cb0b0e0788 100644 --- a/src/main/ai-vault/session-list-result-validation.ts +++ b/src/main/ai-vault/session-list-result-validation.ts @@ -100,7 +100,13 @@ const aiVaultScanIssueSchema = z.object({ const aiVaultListResultEnvelopeSchema = z.object({ sessions: z.array(z.unknown()), issues: z.array(z.unknown()), - scannedAt: z.string() + scannedAt: z.string(), + // Absent from a host older than the field, and that absence is the answer: the caller reads it + // as "coverage unprovable". A malformed value is the same thing, so it is dropped, not coerced. + appliedSessionDepth: z + .union([z.literal('unlimited'), z.number().int().positive()]) + .optional() + .catch(undefined) }) export function parseAiVaultListResult(value: unknown): AiVaultListResult { @@ -151,5 +157,12 @@ export function parseAiVaultListResult(value: unknown): AiVaultListResult { message: `Skipped ${invalidCount} invalid Agent Session History result ${invalidCount === 1 ? 'entry' : 'entries'}.` }) } - return { sessions, issues, scannedAt: envelope.data.scannedAt } + return { + sessions, + issues, + scannedAt: envelope.data.scannedAt, + ...(envelope.data.appliedSessionDepth === undefined + ? {} + : { appliedSessionDepth: envelope.data.appliedSessionDepth }) + } } diff --git a/src/main/ai-vault/session-list-results.test.ts b/src/main/ai-vault/session-list-results.test.ts index 781ee65d1240..f391fb839af2 100644 --- a/src/main/ai-vault/session-list-results.test.ts +++ b/src/main/ai-vault/session-list-results.test.ts @@ -10,6 +10,15 @@ function listResult(issues: AiVaultScanIssue[]): AiVaultListResult { return { sessions: [], issues, scannedAt: '2026-08-02T00:00:00.000Z' } } +function legWithDepth(depth: AiVaultListResult['appliedSessionDepth']): AiVaultListResult { + return { + sessions: [], + issues: [], + scannedAt: '2026-08-02T00:00:00.000Z', + appliedSessionDepth: depth + } +} + function session(index: number): AiVaultSession { const id = `session-${index}` const timestamp = new Date(Date.UTC(2026, 7, 2, 0, 0, index)).toISOString() @@ -223,3 +232,43 @@ describe('mergeAiVaultListResults', () => { expect(merged.issues.filter((issue) => !issue.kind)).toEqual([]) }) }) + +describe('merged scan coverage', () => { + it('reports unlimited only when the merge and every leg were uncapped', () => { + const merged = mergeAiVaultListResults( + [legWithDepth('unlimited'), legWithDepth('unlimited')], + undefined, + true + ) + + expect(merged.appliedSessionDepth).toBe('unlimited') + }) + + it('takes the tightest bound any leg applied', () => { + const merged = mergeAiVaultListResults( + [legWithDepth('unlimited'), legWithDepth(25)], + undefined, + true + ) + + expect(merged.appliedSessionDepth).toBe(25) + }) + + // One leg that cannot prove its coverage makes the merge unprovable: the rows it withheld are + // exactly the ones missing here, and no other leg can vouch for them. + it('reports nothing when a leg predates the signal', () => { + const merged = mergeAiVaultListResults( + [legWithDepth('unlimited'), listResult([])], + undefined, + true + ) + + expect(merged.appliedSessionDepth).toBeUndefined() + }) + + it('reports its own limit when the merge itself is the tighter bound', () => { + const merged = mergeAiVaultListResults([legWithDepth('unlimited')], 10) + + expect(merged.appliedSessionDepth).toBe(10) + }) +}) diff --git a/src/main/ai-vault/session-list-results.ts b/src/main/ai-vault/session-list-results.ts index e0fb7e8a0cdd..ada5cf60b2d1 100644 --- a/src/main/ai-vault/session-list-results.ts +++ b/src/main/ai-vault/session-list-results.ts @@ -5,7 +5,7 @@ import type { } from '../../shared/ai-vault-types' import type { ExecutionHostId } from '../../shared/execution-host' import { sessionSortTime } from './session-scanner-accumulator' -import { aiVaultScanLimit } from '../../shared/ai-vault-session-depth' +import { aiVaultScanLimit, type AiVaultSessionDepth } from '../../shared/ai-vault-session-depth' export function aiVaultScanIssueResult(args: { executionHostId?: ExecutionHostId @@ -52,10 +52,33 @@ export function restampAiVaultListResult( } ), issues: result.issues.map((issue) => ({ ...issue, executionHostId })), - scannedAt: result.scannedAt + scannedAt: result.scannedAt, + ...(result.appliedSessionDepth === undefined + ? {} + : { appliedSessionDepth: result.appliedSessionDepth }) } } +/** The tightest bound any leg applied, or undefined when a leg did not say — one unprovable leg + * makes the merged answer unprovable, because the rows it withheld are the ones this merge is + * missing. */ +function mergedAppliedSessionDepth( + results: readonly AiVaultListResult[], + ownDepth: AiVaultSessionDepth +): AiVaultSessionDepth | undefined { + let tightest = ownDepth + for (const result of results) { + const depth = result.appliedSessionDepth + if (depth === undefined) { + return undefined + } + if (depth !== 'unlimited' && (tightest === 'unlimited' || depth < tightest)) { + tightest = depth + } + } + return tightest +} + export function mergeAiVaultListResults( results: readonly AiVaultListResult[], rawLimit: number | undefined, @@ -74,6 +97,7 @@ export function mergeAiVaultListResults( sessions: [...byId.values()] .sort((left, right) => sessionSortTime(right) - sessionSortTime(left)) .slice(0, limit), + appliedSessionDepth: mergedAppliedSessionDepth(results, unlimited ? 'unlimited' : limit), issues, // Why: a merge is not a new scan. Reminting here made every all-host cache // hit look fresh to the renderer, which only skipped apply when scannedAt diff --git a/src/main/ai-vault/session-scan-issues.ts b/src/main/ai-vault/session-scan-issues.ts index b3e21f9c5a80..0b3779313605 100644 --- a/src/main/ai-vault/session-scan-issues.ts +++ b/src/main/ai-vault/session-scan-issues.ts @@ -1,10 +1,11 @@ -import type { AiVaultScanIssue } from '../../shared/ai-vault-types' +import { AI_VAULT_SCAN_ISSUE_LIMIT, type AiVaultScanIssue } from '../../shared/ai-vault-types' // Why: a stalled WSL distro or an unreachable remote host fails one probe per // discovered path, so an uncapped list ships one row per transcript file in the // tree over IPC. Local and remote scans share the bound — the failure shape is -// the same and both feed the same panel. -const SCAN_ISSUE_LIMIT = 500 +// the same and both feed the same panel. Shared, because a list AT the bound is +// how a reader tells that issues were dropped. +const SCAN_ISSUE_LIMIT = AI_VAULT_SCAN_ISSUE_LIMIT /** Append a scan issue, collapsing everything past the cap into one notice. */ export function recordSessionScanIssue(issues: AiVaultScanIssue[], issue: AiVaultScanIssue): void { diff --git a/src/main/ipc/ai-vault-scan-coalescing.test.ts b/src/main/ipc/ai-vault-scan-coalescing.test.ts index 8a8ad0a3665a..d1318fa38dcf 100644 --- a/src/main/ipc/ai-vault-scan-coalescing.test.ts +++ b/src/main/ipc/ai-vault-scan-coalescing.test.ts @@ -43,6 +43,7 @@ vi.mock('./ssh', () => ({ requestActiveSshAiVaultSessionTitles: mocks.requestActiveSshAiVaultSessionTitles })) +const { DEFAULT_AI_VAULT_SCAN_LIMIT } = await import('../../shared/ai-vault-session-depth') const { _internals, registerAiVaultHandlers } = await import('./ai-vault') const EMPTY_RESULT: AiVaultListResult = { sessions: [], @@ -90,7 +91,13 @@ describe('Agent Session History scan coalescing', () => { await expect(first).rejects.toMatchObject({ name: 'AbortError' }) expect(scan).toHaveBeenCalledTimes(1) resolveScan?.(EMPTY_RESULT) - await expect(second).resolves.toEqual(EMPTY_RESULT) + // The local leg echoes the depth it scanned under, so a reader can tell a whole answer from a + // slice; a mocked remote leg comes back exactly as the mock produced it. + await expect(second).resolves.toEqual( + scope === 'local' + ? { ...EMPTY_RESULT, appliedSessionDepth: DEFAULT_AI_VAULT_SCAN_LIMIT } + : EMPTY_RESULT + ) }) it('coalesces every all-host leg while isolating caller cancellation', async () => { diff --git a/src/renderer/src/components/terminal-pane/AgentResumeChooser.test.tsx b/src/renderer/src/components/terminal-pane/AgentResumeChooser.test.tsx new file mode 100644 index 000000000000..2ce5117c3f4d --- /dev/null +++ b/src/renderer/src/components/terminal-pane/AgentResumeChooser.test.tsx @@ -0,0 +1,130 @@ +// @vitest-environment happy-dom + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { AgentResumeCandidate } from '../../../../shared/agent-resume-candidate' +import { AgentResumeChooser } from './AgentResumeChooser' + +vi.mock('@/i18n/i18n', () => ({ + translate: vi.fn((_key: string, fallback: string) => fallback) +})) + +const mountedRoots: Root[] = [] + +function makeCandidate(id: string, updatedAt: number): AgentResumeCandidate { + return { + agent: 'claude', + providerSession: { key: 'session_id', id }, + cwd: '/w', + title: `Session ${id}`, + updatedAt, + messageCount: 758, + branch: null, + executionHostId: null, + executionHostPlatform: null + } +} + +const CANDIDATES = [ + makeCandidate('a521d69e-9181-481c-ab8e-998a1881b731', 1_789_000_000_000), + makeCandidate('b171319f-6711-4537-89be-00f26ccc7e32', 1_788_000_000_000) +] + +async function renderChooser(onResume = vi.fn()): Promise<{ onResume: typeof onResume }> { + const container = document.createElement('div') + document.body.appendChild(container) + const root = createRoot(container) + mountedRoots.push(root) + await act(async () => { + root.render( + + ) + }) + return { onResume } +} + +function rows(): HTMLElement[] { + return [...document.body.querySelectorAll('[role="option"]')] +} + +function listbox(): HTMLElement { + const element = document.body.querySelector('[role="listbox"]') + if (!element) { + throw new Error('listbox not rendered') + } + return element +} + +async function pressKey(key: string): Promise { + await act(async () => { + listbox().dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true })) + }) +} + +afterEach(() => { + for (const root of mountedRoots.splice(0)) { + act(() => root.unmount()) + } + document.body.innerHTML = '' +}) + +describe('AgentResumeChooser', () => { + // A blocking decision surface has to trap focus, or Tab reaches the xterm underneath and the + // user can type into the very shell a row is about to replace. + it('renders through the Dialog primitive with a modal surface', async () => { + await renderChooser() + const content = document.body.querySelector('[data-slot="dialog-content"]') + expect(content).not.toBeNull() + expect(content?.getAttribute('data-testid')).toBe('agent-resume-chooser') + expect(document.body.querySelector('[data-slot="dialog-overlay"]')).not.toBeNull() + }) + + it('focuses the listbox rather than the dialog close button', async () => { + await renderChooser() + expect(document.activeElement).toBe(listbox()) + }) + + // CORRECTNESS: native buttons let Tab move real focus without moving `selected`, and Enter then + // resumed a different session than the focused one — a silent fork of the wrong transcript. + it('gives rows no focus of their own, so focus and selection cannot diverge', async () => { + await renderChooser() + for (const row of rows()) { + expect(row.tagName).not.toBe('BUTTON') + expect(row.hasAttribute('tabindex')).toBe(false) + } + expect(listbox().getAttribute('aria-activedescendant')).toBe(rows()[0].id) + }) + + it('resumes the row aria-selected names after the cursor moves', async () => { + const { onResume } = await renderChooser() + await pressKey('ArrowDown') + + const selectedRows = rows().filter((row) => row.getAttribute('aria-selected') === 'true') + expect(selectedRows).toHaveLength(1) + expect(listbox().getAttribute('aria-activedescendant')).toBe(selectedRows[0].id) + + await pressKey('Enter') + expect(onResume).toHaveBeenCalledWith(CANDIDATES[1]) + }) + + // docs/STYLEGUIDE.md: flat bg-accent is near-invisible on a light dialog surface, and a lost + // cursor here means resuming the wrong transcript. + it('marks the selected row with the documented jump-palette selection surface', async () => { + await renderChooser() + const [first, second] = rows() + expect(first.className).toContain('jump-palette-item') + expect(first.getAttribute('data-selected')).toBe('true') + expect(second.hasAttribute('data-selected')).toBe(false) + + await pressKey('ArrowDown') + expect(rows()[0].hasAttribute('data-selected')).toBe(false) + expect(rows()[1].getAttribute('data-selected')).toBe('true') + }) + + it('resumes by number key', async () => { + const { onResume } = await renderChooser() + await pressKey('2') + expect(onResume).toHaveBeenCalledWith(CANDIDATES[1]) + }) +}) diff --git a/src/renderer/src/components/terminal-pane/AgentResumeChooser.tsx b/src/renderer/src/components/terminal-pane/AgentResumeChooser.tsx new file mode 100644 index 000000000000..eba1c85c1e14 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/AgentResumeChooser.tsx @@ -0,0 +1,183 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { translate } from '@/i18n/i18n' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle +} from '@/components/ui/dialog' +import type { AgentResumeCandidate } from '../../../../shared/agent-resume-candidate' +import { buildAgentResumeChooserRows } from './agent-resume-chooser-rows' + +type AgentResumeChooserProps = { + candidates: readonly AgentResumeCandidate[] + onResume: (candidate: AgentResumeCandidate) => void + onDismiss: () => void +} + +/** + * The one visible surface of agent auto-resume. It appears only when the resolver + * refused to decide, because resuming the wrong transcript forks it unrecoverably. + * + * It renders INSTEAD of the pane's spawn, never over a running shell: selecting a row + * hands the resume to the spawn that has been held back, so no resume command is ever + * typed into a live shell (docs/reference/omp-resume-transcript-locator.md). Dismissing + * spawns the plain shell, which is exactly the behaviour without this feature. + * + * Why the `Dialog` primitive and not an inline overlay: this is a blocking decision, and an + * overlay traps nothing — Tab reached the xterm underneath, so the user could type into the very + * shell a row was about to replace, and focus never returned where it started. + * + * Why the rows are not buttons: focus and selection have to be ONE value. Native buttons let Tab + * move real focus without moving `selected`, and Enter then resumed `rows[selected]` — a different + * session than the focused one, silently forking the wrong transcript. The listbox alone takes + * focus and names the active row through `aria-activedescendant`, so there is nothing to diverge. + */ +export function AgentResumeChooser({ + candidates, + onResume, + onDismiss +}: AgentResumeChooserProps): React.JSX.Element | null { + const rows = buildAgentResumeChooserRows(candidates) + const [selected, setSelected] = useState(0) + const listboxRef = useRef(null) + + // Why: a shrinking list (a sibling pane claimed one) must not strand the cursor past the end. + useEffect(() => { + setSelected((current) => (current < rows.length ? current : Math.max(0, rows.length - 1))) + }, [rows.length]) + + const handleKeyDown = useCallback( + (event: React.KeyboardEvent): void => { + if (rows.length === 0) { + return + } + // Number/arrow/Enter only: no platform-specific modifier, so this reads the same on + // macOS, Linux and Windows. Escape is the Dialog's, which also restores focus. + if (event.key === 'ArrowDown') { + event.preventDefault() + setSelected((current) => (current + 1) % rows.length) + return + } + if (event.key === 'ArrowUp') { + event.preventDefault() + setSelected((current) => (current - 1 + rows.length) % rows.length) + return + } + // The Radix focus trap also holds the close and dismiss buttons, so one Tab moves focus off + // this listbox and every key below stops firing while the selected row still looks active — + // a dialog whose help text promises "press a number or Enter" with a dead keyboard. Rows are + // deliberately not tabbable, so holding focus here costs no reachable stop. + if (event.key === 'Tab' && !event.altKey && !event.ctrlKey && !event.metaKey) { + event.preventDefault() + return + } + if (event.key === 'Enter') { + event.preventDefault() + const row = rows[selected] + if (row) { + onResume(row.candidate) + } + return + } + const digit = Number.parseInt(event.key, 10) + if (Number.isInteger(digit) && digit >= 1 && digit <= rows.length) { + event.preventDefault() + onResume(rows[digit - 1].candidate) + } + }, + [onResume, rows, selected] + ) + + if (rows.length === 0) { + return null + } + + const activeRowId = `agent-resume-choice-${rows[selected]?.candidate.providerSession.id ?? ''}` + + return ( + { + if (!open) { + onDismiss() + } + }} + > + { + event.preventDefault() + listboxRef.current?.focus() + }} + > + + + {translate( + 'components.terminalPane.AgentResumeChooser.title', + 'Which session should this terminal resume?' + )} + + + {translate( + 'components.terminalPane.AgentResumeChooser.help', + 'Press a number or Enter to resume, Esc for a plain shell.' + )} + + +
+ {rows.map((row, index) => ( +
setSelected(index)} + onClick={() => onResume(row.candidate)} + // `jump-palette-item` is the documented selection surface: flat bg-accent is + // near-invisible on a light dialog, and the cursor decides which transcript Enter + // resumes (docs/STYLEGUIDE.md, "List rows"). + className="jump-palette-item flex cursor-pointer items-baseline gap-3 rounded-md border border-transparent px-3 py-2 text-left text-sm text-foreground" + > + + {index + 1} + + {row.title} + + {row.agentLabel} · {row.messageCount} · {row.age} + +
+ ))} +
+ + + +
+
+ ) +} diff --git a/src/renderer/src/components/terminal-pane/AgentResumeChooserPortals.tsx b/src/renderer/src/components/terminal-pane/AgentResumeChooserPortals.tsx new file mode 100644 index 000000000000..2dbe73455c64 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/AgentResumeChooserPortals.tsx @@ -0,0 +1,55 @@ +import type { AgentResumeCandidate } from '../../../../shared/agent-resume-candidate' +import { makePaneKey } from '../../../../shared/stable-pane-id' +import { getAgentResumePaneHandler } from '@/lib/agent-resume-pane-handlers' +import { clearPendingAgentResumeChoices } from '@/lib/pending-agent-resume-choices' +import { usePendingAgentResumeChoices } from '@/lib/use-pending-agent-resume-choices' +import { AgentResumeChooser } from './AgentResumeChooser' + +export type AgentResumeChooserPane = { + id: number + leafId: string +} + +type AgentResumeChooserPortalsProps = { + tabId: string + panes: readonly AgentResumeChooserPane[] +} + +/** One pane's chooser. A child component because the pending-choice subscription is a hook + * and the parent renders a list. The chooser portals itself through `Dialog`, so nothing is + * mounted into the pane's own container — a modal decision surface belongs above the app. */ +function AgentResumeChooserPortal({ paneKey }: { paneKey: string }): React.JSX.Element | null { + const choice = usePendingAgentResumeChoices(paneKey) + if (!choice || choice.candidates.length === 0) { + return null + } + const resume = (candidate: AgentResumeCandidate): void => { + // Why the owner: the pane key is the same across a reconnect, so a choice scanned for a + // retired binding would otherwise invoke the SUCCESSOR's handler and replace its shell. + // Kept open when the handler refuses: another pane reserved that session between the offer + // and the click, and the remaining rows are still the user's to choose from. + if (getAgentResumePaneHandler(paneKey, choice.owner)?.(candidate) === true) { + clearPendingAgentResumeChoices(paneKey) + } + } + return ( + clearPendingAgentResumeChoices(paneKey)} + /> + ) +} + +export function AgentResumeChooserPortals({ + tabId, + panes +}: AgentResumeChooserPortalsProps): React.JSX.Element { + return ( + <> + {panes.map((pane) => ( + + ))} + + ) +} diff --git a/src/renderer/src/components/terminal-pane/TerminalPaneSurface.tsx b/src/renderer/src/components/terminal-pane/TerminalPaneSurface.tsx index 8165537e39cd..d1292b1db204 100644 --- a/src/renderer/src/components/terminal-pane/TerminalPaneSurface.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalPaneSurface.tsx @@ -12,6 +12,7 @@ import { TerminalSessionStateSaveFailureDialog } from './TerminalSessionStateSav import { LinkActionPopover } from '@/components/link-actions/LinkActionPopover' import { TerminalAgentSessionForkDialog } from './TerminalAgentSessionForkDialog' import { SessionRestoredBannerPortals } from './SessionRestoredBannerPortals' +import { AgentResumeChooserPortals } from './AgentResumeChooserPortals' import { handleInternalTerminalFileDrop } from './terminal-drop-handler' import { TerminalQuickCommandEditorDialog } from './TerminalQuickCommandEditorDialog' import { TerminalPaneNativeChatPortal } from './TerminalPaneNativeChatPortal' @@ -220,6 +221,11 @@ export function TerminalPaneSurface({ panes={managerRef.current?.getPanes() ?? []} paneIds={sessionRestoredBannerPaneIds} /> + {/* Only the active tab: the chooser is an app-modal Dialog now, and an inactive tab's + pending choice would otherwise follow the user onto whatever tab they switched to. */} + {isActive && ( + + )} = {}): AgentResumeCandidate { + return { + agent: 'claude', + providerSession: { key: 'session_id', id: 'a521d69e-9181-481c-ab8e-998a1881b731' }, + cwd: '/w', + title: 'Round 6', + updatedAt: HOST_NOW, + messageCount: 758, + branch: null, + executionHostId: null, + executionHostPlatform: null, + ...overrides + } +} + +describe('buildAgentResumeChooserRows', () => { + // `updatedAt` is the host's clock. Ages measured against the renderer's would be fiction + // under skew, on the one surface where the user decides from exactly this evidence. + it('ages every row against the newest candidate, not the renderer clock', () => { + const rows = buildAgentResumeChooserRows([ + makeCandidate(), + makeCandidate({ + providerSession: { key: 'session_id', id: 'b171319f-6711-4537-89be-00f26ccc7e32' }, + updatedAt: HOST_NOW - 3 * 60 * 60 * 1000 + }) + ]) + expect(rows.map((row) => row.age)).toEqual(['newest', '3h older']) + }) + + it('reads the same however far the host clock is from this one', () => { + const skewed = buildAgentResumeChooserRows([ + makeCandidate({ updatedAt: Date.now() + 86_400_000 }) + ]) + expect(skewed[0].age).toBe('newest') + }) +}) diff --git a/src/renderer/src/components/terminal-pane/agent-resume-chooser-rows.ts b/src/renderer/src/components/terminal-pane/agent-resume-chooser-rows.ts new file mode 100644 index 000000000000..2d1343f0ada2 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/agent-resume-chooser-rows.ts @@ -0,0 +1,65 @@ +import type { AgentResumeCandidate } from '../../../../shared/agent-resume-candidate' +import { AI_VAULT_AGENT_LABELS } from '../../../../shared/ai-vault-types' +import { translate } from '@/i18n/i18n' + +/** How many candidates the chooser offers. Past this the list stops being a glance + * and the AI Vault sidebar is the better surface. */ +export const AGENT_RESUME_CHOOSER_MAX_ROWS = 5 + +/** Reuses the vault's label map so one agent reads the same everywhere; an agent the + * vault does not label (it indexes a different set) falls back to its own id. */ +export function agentResumeChooserAgentLabel(agent: string): string { + const labels: Record = AI_VAULT_AGENT_LABELS + return labels[agent] ?? agent +} + +/** Ages are relative to the newest candidate, never to the renderer clock: `updatedAt` is the + * HOST's clock, and under skew a "2h ago" computed here would be fiction on the surface where + * the user is choosing on exactly that evidence. Candidate-to-candidate distance is skew-free + * because both sides come from the same host clock. */ +export function agentResumeChooserRelativeAge(updatedAt: number, newestUpdatedAt: number): string { + const K = 'components.terminalPane.AgentResumeChooser.age' + if (!Number.isFinite(updatedAt) || !Number.isFinite(newestUpdatedAt)) { + return translate(`${K}.unknown`, 'unknown') + } + const minutes = Math.floor(Math.max(0, newestUpdatedAt - updatedAt) / 60_000) + if (minutes < 1) { + return translate(`${K}.newest`, 'newest') + } + if (minutes < 60) { + return translate(`${K}.minutes`, '{{count}}m older', { count: minutes }) + } + const hours = Math.floor(minutes / 60) + if (hours < 24) { + return translate(`${K}.hours`, '{{count}}h older', { count: hours }) + } + return translate(`${K}.days`, '{{count}}d older', { count: Math.floor(hours / 24) }) +} + +export type AgentResumeChooserRow = { + candidate: AgentResumeCandidate + agentLabel: string + title: string + age: string + messageCount: number + branch: string | null +} + +/** Ranking is display order only — the resolver already refused to decide, so nothing + * here may be read as a recommendation. */ +export function buildAgentResumeChooserRows( + candidates: readonly AgentResumeCandidate[] +): AgentResumeChooserRow[] { + const newestUpdatedAt = candidates.reduce( + (newest, candidate) => (candidate.updatedAt > newest ? candidate.updatedAt : newest), + Number.NEGATIVE_INFINITY + ) + return candidates.slice(0, AGENT_RESUME_CHOOSER_MAX_ROWS).map((candidate) => ({ + candidate, + agentLabel: agentResumeChooserAgentLabel(candidate.agent), + title: candidate.title.trim() || candidate.providerSession.id, + age: agentResumeChooserRelativeAge(candidate.updatedAt, newestUpdatedAt), + messageCount: Math.max(0, Math.trunc(candidate.messageCount)), + branch: candidate.branch + })) +} diff --git a/src/renderer/src/components/terminal-pane/agent-resume-reservation-dispose-identity.test.ts b/src/renderer/src/components/terminal-pane/agent-resume-reservation-dispose-identity.test.ts new file mode 100644 index 000000000000..b1eb538d4cba --- /dev/null +++ b/src/renderer/src/components/terminal-pane/agent-resume-reservation-dispose-identity.test.ts @@ -0,0 +1,136 @@ +import type * as React from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { makePaneKey } from '../../../../shared/stable-pane-id' +import { flushAsyncTicks } from './pty-connection-test-async' +import { + createMockTransport, + createPane, + createManager, + leafIdForPane, + type MockTransport +} from './pty-connection-test-pane-fixtures' +import { buildPaneConnectionDeps } from './pty-connection-test-deps' +import type * as AgentResumeSessionReservations from '@/lib/agent-resume-session-reservations' +import { createInitialStoreState } from './pty-connection-test-store-fixtures' +import type { StoreState } from './pty-connection-test-store-state' +import { + installTerminalTestGlobals, + restoreTerminalTestGlobals +} from './pty-connection-test-environment' + +const { scheduleRuntimeGraphSync, notifyCodexPaneBoundForStaleSweep } = vi.hoisted(() => ({ + scheduleRuntimeGraphSync: vi.fn(), + notifyCodexPaneBoundForStaleSweep: vi.fn() +})) + +let mockStoreState: StoreState +let transportFactoryQueue: MockTransport[] = [] +let storeSubscribers: ((state: StoreState) => void)[] = [] + +vi.mock('@/runtime/sync-runtime-graph', () => ({ scheduleRuntimeGraphSync })) +vi.mock('@/lib/codex-stale-pane-sweep', () => ({ notifyCodexPaneBoundForStaleSweep })) + +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => mockStoreState, + subscribe: (listener: (state: StoreState) => void) => { + storeSubscribers.push(listener) + return () => { + storeSubscribers = storeSubscribers.filter((candidate) => candidate !== listener) + } + } + } +})) + +vi.mock('@/lib/agent-status', async (importOriginal) => { + const { buildAgentStatusModuleMock } = await import('./pty-connection-test-environment') + return buildAgentStatusModuleMock(await importOriginal>()) +}) + +// Why: connectPanePty calls hooks outside React; only useCallback needs to pass through. +vi.mock('react', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + useCallback: unknown>(fn: T): T => fn + } +}) + +vi.mock('./pty-transport', () => ({ + createIpcPtyTransport: vi.fn(() => { + const nextTransport = transportFactoryQueue.shift() + if (!nextTransport) { + throw new Error('No mock transport queued') + } + return nextTransport + }) +})) + +const SESSION_ID = 'a521d69e-9181-481c-ab8e-998a1881b731' +const PANE_KEY = makePaneKey('tab-1', leafIdForPane(1)) + +/** + * A retired binding's dispose must not release a resume reservation, because the reservation + * lives under the STABLE pane key its successor also uses. Releasing a successor's reservation + * reopens the window where two panes resume one transcript and fork it. + */ +describe('agent resume reservations across a pane binding replacement', () => { + beforeEach(() => { + vi.resetModules() + vi.clearAllMocks() + transportFactoryQueue = [] + storeSubscribers = [] + mockStoreState = createInitialStoreState(() => mockStoreState) + installTerminalTestGlobals() + }) + + afterEach(async () => { + await restoreTerminalTestGlobals() + }) + + /** Why imported here: `vi.resetModules()` gives each test a fresh module registry, so the + * reservation store the pane writes to is only the same one the assertions read when both + * come from this import. */ + async function connectPane(): Promise<{ + deps: ReturnType + dispose: () => void + reservations: typeof AgentResumeSessionReservations + }> { + const { connectPanePty } = await import('./pty-connection') + const transport = createMockTransport('pty-id') + transportFactoryQueue.push(transport) + const deps = buildPaneConnectionDeps(() => mockStoreState, { + isVisibleRef: { current: true } + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the shared pane/manager/deps fixtures model exactly the surface connectPanePty reads; every connect test in this directory passes them through the same casts. + const binding = connectPanePty(createPane(1) as never, createManager(1) as never, deps as never) + await flushAsyncTicks(6) + return { + deps, + dispose: () => binding.dispose(), + reservations: await import('@/lib/agent-resume-session-reservations') + } + } + + it('keeps a reservation a successor binding holds', async () => { + const { deps, dispose, reservations } = await connectPane() + reservations.reserveAgentResumeSession(SESSION_ID, PANE_KEY) + // A successor connection claimed this pane slot before the retired binding tore down. + deps.paneTransportsRef.current.set(1, { successor: true }) + + dispose() + + expect(reservations.agentResumeSessionsReservedElsewhere('other-pane')).toContain(SESSION_ID) + }) + + it('releases its own reservation when it still owns the pane', async () => { + const { dispose, reservations } = await connectPane() + reservations.reserveAgentResumeSession(SESSION_ID, PANE_KEY) + + dispose() + + expect(reservations.agentResumeSessionsReservedElsewhere('other-pane')).not.toContain( + SESSION_ID + ) + }) +}) diff --git a/src/renderer/src/components/terminal-pane/pty-connection-agent-resume-handler-ownership.test.ts b/src/renderer/src/components/terminal-pane/pty-connection-agent-resume-handler-ownership.test.ts new file mode 100644 index 000000000000..4f4b3bc4f0f2 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/pty-connection-agent-resume-handler-ownership.test.ts @@ -0,0 +1,138 @@ +/** + * The chooser reaches a pane through `registerAgentResumePaneHandler`, and the owner it names is + * the pty binding's transport. Every other test in this area hands the installer a session bag that + * already has a `transport`, so none of them can see the install ORDER that `connectPanePty` + * actually uses — and while the registration ran before the transport existed, the handler sat + * under owner `undefined` and every Enter, number key and click silently did nothing. + * + * So this binds through the real sequence and asserts the two owners agree. + */ +import type * as React from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { makePaneKey } from '../../../../shared/stable-pane-id' +import { flushAsyncTicks } from './pty-connection-test-async' +import { + createMockTransport, + createPane, + createManager, + leafIdForPane, + type MockTransport +} from './pty-connection-test-pane-fixtures' +import { buildPaneConnectionDeps } from './pty-connection-test-deps' +import type { connectPanePty } from './pty-connection' +import { createInitialStoreState } from './pty-connection-test-store-fixtures' +import type { StoreState } from './pty-connection-test-store-state' +import { + installTerminalTestGlobals, + restoreTerminalTestGlobals +} from './pty-connection-test-environment' + +const { scheduleRuntimeGraphSync, notifyCodexPaneBoundForStaleSweep, toastInfo } = vi.hoisted( + () => ({ + scheduleRuntimeGraphSync: vi.fn(), + notifyCodexPaneBoundForStaleSweep: vi.fn(), + toastInfo: vi.fn() + }) +) + +let mockStoreState: StoreState +let transportFactoryQueue: MockTransport[] = [] + +vi.mock('@/runtime/sync-runtime-graph', () => ({ scheduleRuntimeGraphSync })) +vi.mock('@/lib/codex-stale-pane-sweep', () => ({ notifyCodexPaneBoundForStaleSweep })) +vi.mock('sonner', () => ({ toast: { info: toastInfo } })) + +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => mockStoreState, + subscribe: () => () => {} + } +})) + +vi.mock('@/lib/agent-status', async (importOriginal) => { + const { buildAgentStatusModuleMock } = await import('./pty-connection-test-environment') + return buildAgentStatusModuleMock(await importOriginal>()) +}) + +// Why: connectPanePty calls hooks outside React here; no test in this file renders. +vi.mock('react', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + useCallback: unknown>(fn: T): T => fn + } +}) + +vi.mock('./pty-transport', () => ({ + createIpcPtyTransport: vi.fn(() => { + const next = transportFactoryQueue.shift() + if (!next) { + throw new Error('No mock transport queued') + } + return next + }) +})) + +vi.mock('./remote-runtime-pty-transport', () => ({ + createRemoteRuntimePtyTransport: vi.fn(() => { + const next = transportFactoryQueue.shift() + if (!next) { + throw new Error('No mock transport queued') + } + return next + }) +})) + +/** Drives the real connect path with this directory's shared pty fixtures. One place carries the + * fixture-to-signature cast so the assertions below stay about ownership. */ +function connectWithFixtures( + connect: typeof connectPanePty +): ReturnType { + const deps = buildPaneConnectionDeps(() => mockStoreState) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: createPane, createManager and buildPaneConnectionDeps are this directory's shared connectPanePty fixtures; every other test here drives the same function with them, and they supply every field it reads. + connect(createPane(1) as never, createManager(1) as never, deps as never) + return deps +} + +describe('agent resume pane handler ownership, through the real connect sequence', () => { + beforeEach(() => { + vi.resetModules() + vi.clearAllMocks() + transportFactoryQueue = [] + mockStoreState = createInitialStoreState(() => mockStoreState) + installTerminalTestGlobals() + }) + + afterEach(async () => { + await restoreTerminalTestGlobals() + }) + + it('registers the resume handler under the transport the chooser publishes choices with', async () => { + // Why the dynamic import: `vi.resetModules()` gives each test a fresh registry instance, and a + // file-level import would read the previous one — the handler under test would never appear. + const { connectPanePty } = await import('./pty-connection') + const { getAgentResumePaneHandler } = await import('@/lib/agent-resume-pane-handlers') + const transport = createMockTransport() + transportFactoryQueue.push(transport) + const deps = connectWithFixtures(connectPanePty) + await flushAsyncTicks() + + const paneKey = makePaneKey(deps.tabId, leafIdForPane(1)) + // `setPendingAgentResumeChoices` stamps a choice with this same transport, so a handler the + // lookup cannot find under it is a chooser no keystroke can reach. + expect(getAgentResumePaneHandler(paneKey, transport)).toBeTypeOf('function') + expect(getAgentResumePaneHandler(paneKey, {})).toBeUndefined() + }) + + it('leaves no handler registered under an absent owner', async () => { + const { connectPanePty } = await import('./pty-connection') + const { getAgentResumePaneHandler } = await import('@/lib/agent-resume-pane-handlers') + transportFactoryQueue.push(createMockTransport()) + const deps = connectWithFixtures(connectPanePty) + await flushAsyncTicks() + + const paneKey = makePaneKey(deps.tabId, leafIdForPane(1)) + // The install-order defect: `session.transport` was still undefined at registration time. + expect(getAgentResumePaneHandler(paneKey, undefined)).toBeUndefined() + }) +}) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-resume-recovery-install.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-resume-recovery-install.test.ts new file mode 100644 index 000000000000..43b589d4b2cf --- /dev/null +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-resume-recovery-install.test.ts @@ -0,0 +1,448 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { AgentResumeCandidate } from '../../../../../shared/agent-resume-candidate' +import { getAgentResumePaneHandler } from '@/lib/agent-resume-pane-handlers' +import { getPendingAgentResumeChoices } from '@/lib/pending-agent-resume-choices' +import { resetAgentResumeSessionReservations } from '@/lib/agent-resume-session-reservations' +import type { AgentResumeCandidateScan } from '@/lib/agent-resume-candidate-source' +import { installAgentResumeRecovery } from './agent-resume-recovery-install' +import { installPanePtyVisibilityBind } from './pane-pty-visibility-bind' +import type { ConnectPanePtySession } from './connect-pane-pty-session' + +const storeState: { + agentStatusByPaneKey: Record + terminalLayoutsByTabId: Record + settings: Record +} = { agentStatusByPaneKey: {}, terminalLayoutsByTabId: {}, settings: {} } + +// Real leaf UUIDs: the claim rule resolves a row's pane from its key, and `parsePaneKey` rejects +// anything else. Only the liveness-sensitive cases below need them. +const OWN_LEAF = 'c6d5f4aa-2f0e-4a31-9c1e-1d6f1a0b2c30' +const SIBLING_LEAF = 'd7e6a5bb-3f1f-4b42-8d2f-2e7f2b1c3d41' +const OWN_PANE_KEY = `tab-1:${OWN_LEAF}` +const SIBLING_PANE_KEY = `tab-9:${SIBLING_LEAF}` + +function bindLayout(tabId: string, leafId: string, ptyId: string | undefined): void { + storeState.terminalLayoutsByTabId[tabId] = { ptyIdsByLeafId: { [leafId]: ptyId } } +} + +const storeSubscribers: (() => void)[] = [] +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => storeState, + subscribe: (listener: () => void) => { + storeSubscribers.push(listener) + return () => { + const at = storeSubscribers.indexOf(listener) + if (at !== -1) { + storeSubscribers.splice(at, 1) + } + } + } + } +})) +vi.mock('@/runtime/sync-runtime-graph', () => ({ scheduleRuntimeGraphSync: vi.fn() })) +vi.mock('@/lib/codex-stale-pane-sweep', () => ({ notifyCodexPaneBoundForStaleSweep: vi.fn() })) +vi.mock('@/lib/agent-resume-launch-target', () => ({ + resolveAgentResumeLaunchTarget: () => ({ platform: 'linux' }) +})) +vi.mock('./candidate-resume-startup', () => ({ + buildCandidateResumeStartup: () => ({ agent: 'claude' }) +})) + +const fetchCandidates = vi.fn<() => Promise>() +vi.mock('@/lib/agent-resume-candidate-source', () => ({ + fetchAgentResumeCandidates: () => fetchCandidates() +})) + +function makeCandidate(overrides: Partial = {}): AgentResumeCandidate { + return { + agent: 'claude', + providerSession: { key: 'session_id', id: 'a521d69e-9181-481c-ab8e-998a1881b731' }, + cwd: '/w', + title: 'Round 6', + updatedAt: 1_789_000_000_000, + messageCount: 758, + branch: null, + executionHostId: null, + executionHostPlatform: null, + ...overrides + } +} + +/** Two survivors nothing separates, so the resolver asks rather than resuming. */ +function twoCandidates(): AgentResumeCandidate[] { + return [ + makeCandidate(), + makeCandidate({ + providerSession: { key: 'session_id', id: 'b171319f-6711-4537-89be-00f26ccc7e32' }, + updatedAt: 1_788_000_000_000 + }) + ] +} + +/** The installers read a session bag, so the fixture supplies exactly the fields they touch. */ +function buildSession( + paneKey: string, + overrides: Record = {}, + sharedPaneTransports?: Map +): ConnectPanePtySession { + const transport = { getPtyId: () => null, getConnectionId: () => null, disconnect: vi.fn() } + const paneTransports = sharedPaneTransports ?? new Map() + // The successor of a replaced binding: registering it retires whichever binding held the slot. + paneTransports.set(1, transport) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: ConnectPanePtySession is an index-signature bag whose pane/manager fields the installers under test never dereference; this fixture supplies every field they do read. + const session = { + pane: { id: 1, leafId: paneKey }, + manager: {}, + deps: { + tabId: 'tab-1', + worktreeId: 'wt-1', + isVisibleRef: { current: true }, + paneTransportsRef: { current: paneTransports }, + clearTabPtyId: vi.fn() + }, + transport, + cacheKey: paneKey, + disposed: false, + worktree: { path: '/w' }, + executionHostId: null, + executionHostPlatform: null, + spawnedFreshPtyId: 'pty-1', + lastTerminalInputAt: Number.NaN, + // The tab-wide value the guard must NOT read; the pane-scoped one is what authorizes a resume. + resolveExpectedLaunchTuiAgent: () => 'claude', + resolvePaneScopedTuiAgent: () => 'claude', + getSleepingRecordForPane: () => null, + startFreshColdRestoreAgentResume: vi.fn(), + clearExitedPanePtyLayoutBinding: vi.fn(), + syncPanePtyLayoutBinding: vi.fn(), + ...overrides + } as unknown as ConnectPanePtySession + installAgentResumeRecovery(session) + return session +} + +beforeEach(() => { + vi.clearAllMocks() + resetAgentResumeSessionReservations() + storeState.agentStatusByPaneKey = {} + storeState.terminalLayoutsByTabId = {} + fetchCandidates.mockResolvedValue({ kind: 'complete', candidates: [makeCandidate()] }) +}) + +describe('recovery triggers', () => { + // The primary scenario: Orca opens with the tab already active, so the pane is visible on + // mount and never transitions hidden -> visible. + it('runs for a pane that is already visible when its shell spawns', async () => { + const session = buildSession('tab-1:leaf-visible', { spawnedFreshPtyId: null }) + installPanePtyVisibilityBind(session) + session.claimCapturedDirectSshRetryPty = () => true + session.bindActivePanePty = (ptyId: string) => { + session.spawnedFreshPtyId = ptyId + return true + } + + await session.onPtySpawn('pty-1') + await vi.waitFor(() => expect(session.startFreshColdRestoreAgentResume).toHaveBeenCalledOnce()) + }) + + // The second half of the same question: a pane whose pty is replaced while its tab stays + // active gets a new binding, and that binding — not the retired one — runs recovery. + it('runs for a replacement binding and never for the binding it retired', async () => { + const paneTransports = new Map() + const retired = buildSession('tab-1:leaf-replaced', {}, paneTransports) + const successor = buildSession('tab-1:leaf-replaced', {}, paneTransports) + + await retired.attemptAgentResumeRecovery() + expect(fetchCandidates).not.toHaveBeenCalled() + + await successor.attemptAgentResumeRecovery() + expect(successor.startFreshColdRestoreAgentResume).toHaveBeenCalledOnce() + expect(retired.startFreshColdRestoreAgentResume).not.toHaveBeenCalled() + }) + + // C: `resolveExpectedLaunchTuiAgent` reads the tab-wide launchAgent, which describes the tab's + // ORIGINAL pty. A plain-shell split beside an agent pane must not inherit that evidence and + // have its shell replaced by a historical conversation. + it('never runs on tab-wide launch evidence alone', async () => { + const session = buildSession('tab-1:leaf-split', { resolvePaneScopedTuiAgent: () => null }) + await session.attemptAgentResumeRecovery() + expect(fetchCandidates).not.toHaveBeenCalled() + expect(session.startFreshColdRestoreAgentResume).not.toHaveBeenCalled() + }) + + // D: a cancelled or partial scan answered about nothing, so it must not burn the one attempt + // this connection gets. + it('does not spend the attempt on an unverifiable scan', async () => { + const session = buildSession('tab-1:leaf-partial') + fetchCandidates.mockResolvedValueOnce({ kind: 'unverifiable', reason: 'scan-issues' }) + + await session.attemptAgentResumeRecovery() + expect(session.agentResumeRecoveryAttempted).toBe(false) + expect(session.startFreshColdRestoreAgentResume).not.toHaveBeenCalled() + + await session.attemptAgentResumeRecovery() + expect(session.startFreshColdRestoreAgentResume).toHaveBeenCalledOnce() + }) + + it('does not run twice when the pane is later revealed', async () => { + const session = buildSession('tab-1:leaf-latch') + await session.attemptAgentResumeRecovery() + await session.attemptAgentResumeRecovery() + expect(fetchCandidates).toHaveBeenCalledOnce() + }) + + // Without positive evidence, a plain shell revealed once would be destructively replaced by + // an unrelated conversation that merely shares the workspace. + it('never runs for a pane with no evidence it hosted an agent', async () => { + const session = buildSession('tab-1:leaf-plain', { + resolveExpectedLaunchTuiAgent: () => null, + resolvePaneScopedTuiAgent: () => null + }) + await session.attemptAgentResumeRecovery() + expect(fetchCandidates).not.toHaveBeenCalled() + expect(session.startFreshColdRestoreAgentResume).not.toHaveBeenCalled() + }) + + it('retries once pane-scoped agent status hydrates, with no visibility flip', async () => { + // The hook server's persisted snapshot can land after onPtySpawn already ran the gate. An + // already-visible pane gets no later reveal, so without this the pane stays a plain shell. + let paneAgent: string | null = null + const session = buildSession('tab-1:leaf-late-status', { + resolveExpectedLaunchTuiAgent: () => null, + resolvePaneScopedTuiAgent: () => paneAgent + }) + const before = storeSubscribers.length + await session.attemptAgentResumeRecovery() + expect(fetchCandidates).not.toHaveBeenCalled() + expect(storeSubscribers.length).toBe(before + 1) + + paneAgent = 'claude' + for (const listener of storeSubscribers.slice()) { + listener() + } + await Promise.resolve() + await Promise.resolve() + + expect(fetchCandidates).toHaveBeenCalled() + }) + + it('never recovers into a pane opened to run a specific command', async () => { + // launchAgent here names what the user just asked to start, not a conversation that went + // missing. Recovery begins before the startup is delivered, so a scan finishing later would + // replace the requested agent with an older transcript. + const session = buildSession('tab-1:leaf-deliberate', { + paneStartup: { command: 'claude', launchAgent: 'claude' } + }) + await session.attemptAgentResumeRecovery() + expect(fetchCandidates).not.toHaveBeenCalled() + expect(session.startFreshColdRestoreAgentResume).not.toHaveBeenCalled() + // Latched: the request still stands once the command has been delivered and cleared. + session.paneStartup = undefined + await session.attemptAgentResumeRecovery() + expect(fetchCandidates).not.toHaveBeenCalled() + }) + + it('retires the bound plain shell before spawning the resume', async () => { + // The fresh shell still owns the pane's stable key, so a bare connect would reattach it and + // the resume command would never run — success reported over an untouched shell. + const session = buildSession('tab-1:leaf-retire') + fetchCandidates.mockResolvedValueOnce({ kind: 'complete', candidates: [makeCandidate()] }) + await session.attemptAgentResumeRecovery() + expect(session.transport.disconnect).toHaveBeenCalled() + expect(session.clearExitedPanePtyLayoutBinding).toHaveBeenCalledWith('pty-1') + expect(session.startFreshColdRestoreAgentResume).toHaveBeenCalled() + const disconnectOrder = session.transport.disconnect.mock.invocationCallOrder[0] + const spawnOrder = session.startFreshColdRestoreAgentResume.mock.invocationCallOrder[0] + expect(disconnectOrder).toBeLessThan(spawnOrder) + }) + + it('leaves a reattached PTY alone', async () => { + const session = buildSession('tab-1:leaf-reattached', { spawnedFreshPtyId: null }) + await session.attemptAgentResumeRecovery() + expect(fetchCandidates).not.toHaveBeenCalled() + }) + + // EP-ERRORS: a relay that never answered is not evidence about this pane. + it('retries after a failed attempt instead of disabling recovery', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const session = buildSession('tab-1:leaf-retry') + fetchCandidates.mockRejectedValueOnce(new Error('relay down')) + + await session.attemptAgentResumeRecovery() + expect(session.agentResumeRecoveryAttempted).toBe(false) + expect(warn).toHaveBeenCalled() + + await session.attemptAgentResumeRecovery() + expect(session.startFreshColdRestoreAgentResume).toHaveBeenCalledOnce() + warn.mockRestore() + }) +}) + +describe('concurrent panes on one transcript', () => { + // Both scans resolve the same sole candidate before either spawn reports a status, so only + // the synchronous reservation can keep them apart. + it('lets exactly one of two panes revealed together resume the session', async () => { + const first = buildSession('tab-1:leaf-a') + const second = buildSession('tab-1:leaf-b') + + await Promise.all([first.attemptAgentResumeRecovery(), second.attemptAgentResumeRecovery()]) + + const resumed = [first, second].filter( + (session) => session.startFreshColdRestoreAgentResume.mock.calls.length > 0 + ) + expect(resumed).toHaveLength(1) + }) +}) + +describe('a choice that settles after the pane is gone', () => { + it('is never offered once the pane was disposed', async () => { + const session = buildSession('tab-1:leaf-disposed') + fetchCandidates.mockImplementation(async () => { + session.disposed = true + return { kind: 'complete', candidates: twoCandidates() } + }) + + await session.attemptAgentResumeRecovery() + expect(getPendingAgentResumeChoices('tab-1:leaf-disposed')).toBeUndefined() + }) + + it('is never offered once a successor owns the pane', async () => { + const session = buildSession('tab-1:leaf-successor') + fetchCandidates.mockImplementation(async () => { + // A successor connection claimed this pane's slot while the scan was in flight. + session.deps.paneTransportsRef.current.delete(1) + return { kind: 'complete', candidates: twoCandidates() } + }) + + await session.attemptAgentResumeRecovery() + expect(getPendingAgentResumeChoices('tab-1:leaf-successor')).toBeUndefined() + expect(getAgentResumePaneHandler('tab-1:leaf-successor', session.transport)).toBeDefined() + }) +}) + +describe('revalidating a claim at chooser selection', () => { + // The chooser's rows were scanned seconds ago, and the renderer-local reservation map is not the + // only way a candidate goes live: another pane's cold restore and an Agent Session History + // launch both reserve nothing here, so the host-owned status store is the evidence. + it('refuses a candidate that went live after the chooser was populated', async () => { + const session = buildSession(OWN_PANE_KEY) + const candidate = makeCandidate() + storeState.agentStatusByPaneKey = { + [SIBLING_PANE_KEY]: { providerSession: candidate.providerSession, state: 'working' } + } + bindLayout('tab-9', SIBLING_LEAF, 'pty-9') + + const handler = getAgentResumePaneHandler(OWN_PANE_KEY, session.transport) + expect(handler?.(candidate)).toBe(false) + expect(session.startFreshColdRestoreAgentResume).not.toHaveBeenCalled() + }) + + // TOO NARROW, fixed: `done` is "task complete but pane LIVE" (agent-status.ts), so a finished + // sibling still owns its transcript and resuming it here would run two agents on one. + it('refuses a candidate whose only row is a done-but-live sibling pane', async () => { + const session = buildSession(OWN_PANE_KEY) + const candidate = makeCandidate() + storeState.agentStatusByPaneKey = { + [SIBLING_PANE_KEY]: { providerSession: candidate.providerSession, state: 'done' } + } + bindLayout('tab-9', SIBLING_LEAF, 'pty-9') + + const handler = getAgentResumePaneHandler(OWN_PANE_KEY, session.transport) + expect(handler?.(candidate)).toBe(false) + expect(session.startFreshColdRestoreAgentResume).not.toHaveBeenCalled() + }) + + it('resumes once the pane that held the row is gone from this renderer', async () => { + const session = buildSession(OWN_PANE_KEY) + const candidate = makeCandidate() + storeState.agentStatusByPaneKey = { + [SIBLING_PANE_KEY]: { providerSession: candidate.providerSession, state: 'done' } + } + + const handler = getAgentResumePaneHandler(OWN_PANE_KEY, session.transport) + expect(handler?.(candidate)).toBe(true) + }) +}) + +describe('the restart this feature exists for', () => { + // TOO BROAD, fixed: the hook server republishes the recovering pane's OWN persisted row as + // `restoredUnconfirmed` (server-hydration.ts). Counting it as a claim filtered out the sole + // candidate, so a restart during working/blocked/waiting left a plain shell. + it('recovers a pane whose own nonterminal row came back restoredUnconfirmed', async () => { + const candidate = makeCandidate() + const session = buildSession(OWN_PANE_KEY) + storeState.agentStatusByPaneKey = { + [OWN_PANE_KEY]: { + providerSession: candidate.providerSession, + state: 'working', + restoredUnconfirmed: true + } + } + bindLayout('tab-1', OWN_LEAF, 'pty-1') + + await session.attemptAgentResumeRecovery() + expect(session.startFreshColdRestoreAgentResume).toHaveBeenCalledOnce() + }) +}) + +describe('a choice published by a retired binding', () => { + // Pending choices carried no binding identity, so a stale chooser reached the SUCCESSOR's + // handler and could replace its shell with a candidate scanned for the retired connection. + it('cannot reach the successor handler that replaced its owner', async () => { + const paneTransports = new Map() + const retired = buildSession('tab-1:leaf-stale-choice', {}, paneTransports) + fetchCandidates.mockResolvedValueOnce({ kind: 'complete', candidates: twoCandidates() }) + await retired.attemptAgentResumeRecovery() + + const choice = getPendingAgentResumeChoices('tab-1:leaf-stale-choice') + expect(choice?.owner).toBe(retired.transport) + + const successor = buildSession('tab-1:leaf-stale-choice', {}, paneTransports) + expect(getAgentResumePaneHandler('tab-1:leaf-stale-choice', choice!.owner)).toBeUndefined() + expect(getAgentResumePaneHandler('tab-1:leaf-stale-choice', successor.transport)).toBeDefined() + }) +}) + +describe('visibility lost mid-scan', () => { + // The contract is that a hidden pane does not spend its attempt and retries when revealed. The + // post-scan gate answers `pane-hidden` too, and it was spending the latch. + it('does not spend the attempt when the pane is hidden during the scan', async () => { + const session = buildSession('tab-1:leaf-hidden-midscan') + fetchCandidates.mockImplementationOnce(async () => { + session.deps.isVisibleRef.current = false + return { kind: 'complete', candidates: [makeCandidate()] } + }) + + await session.attemptAgentResumeRecovery() + expect(session.agentResumeRecoveryAttempted).toBe(false) + expect(session.startFreshColdRestoreAgentResume).not.toHaveBeenCalled() + + session.deps.isVisibleRef.current = true + await session.attemptAgentResumeRecovery() + expect(session.startFreshColdRestoreAgentResume).toHaveBeenCalledOnce() + }) +}) + +describe('folder workspaces', () => { + // AGENTS.md: a folder workspace is as valid as a git worktree and keeps its root on + // `folderWorkspace.folderPath`, so gating on `worktree.path` made those panes unrecoverable. + it('recovers a pane whose workspace is a folder, not a worktree', async () => { + const session = buildSession('tab-1:leaf-folder', { + worktree: undefined, + // Same path the fixture candidate names, so only the scope derivation is under test. + folderWorkspace: { projectGroupId: 'pg-1', folderPath: '/w' } + }) + await session.attemptAgentResumeRecovery() + expect(session.startFreshColdRestoreAgentResume).toHaveBeenCalledOnce() + }) + + it('still refuses a pane with neither representation', async () => { + const session = buildSession('tab-1:leaf-no-scope', { + worktree: undefined, + folderWorkspace: undefined + }) + await session.attemptAgentResumeRecovery() + expect(fetchCandidates).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-resume-recovery-install.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-resume-recovery-install.ts new file mode 100644 index 000000000000..182541099149 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-resume-recovery-install.ts @@ -0,0 +1,233 @@ +import { useAppStore } from '@/store' +import { fetchAgentResumeCandidates } from '@/lib/agent-resume-candidate-source' +import { recoverAgentSessionForPane } from '@/lib/agent-resume-recovery' +import { agentResumeSessionsClaimedByOtherPanes } from '@/lib/agent-resume-session-claims' +import { registerAgentResumePaneHandler } from '@/lib/agent-resume-pane-handlers' +import { setPendingAgentResumeChoices } from '@/lib/pending-agent-resume-choices' +import { + agentResumeSessionsReservedElsewhere, + reserveAgentResumeSession +} from '@/lib/agent-resume-session-reservations' +import { resolveAgentResumeLaunchTarget } from '@/lib/agent-resume-launch-target' +import { paneAgentResumeScopePath } from '@/lib/agent-resume-workspace-scope' +import type { AgentResumeCandidate } from '../../../../../shared/agent-resume-candidate' +import { isResumableTuiAgent } from '../../../../../shared/agent-session-resume' + +import { buildCandidateResumeStartup } from './candidate-resume-startup' +import type { ConnectPanePtySession } from './connect-pane-pty-session' + +/** Session ids another pane holds under THE PANE-IDENTITY CLAIM RULE, plus the ones another pane + * has reserved but not yet spawned. Resuming one into a second pane would put two agents on one + * transcript. */ +function claimedProviderSessionIds( + state: ReturnType, + paneKey: string +): Set { + const claimed = agentResumeSessionsReservedElsewhere(paneKey) + for (const sessionId of agentResumeSessionsClaimedByOtherPanes(state, paneKey)) { + claimed.add(sessionId) + } + return claimed +} + +/** Refusals that mean "we never got an answer", so the pane keeps its one attempt. Every other + * refusal is a real verdict about this pane and stays spent. */ +const UNSPENT_AGENT_RESUME_REFUSALS: ReadonlySet = new Set([ + // The host scan was cancelled, partial, truncated or unreachable. + 'scan-unverifiable', + // The contract is that a hidden pane does not spend its attempt and retries when revealed. The + // pre-scan return below covers a pane hidden at the start; the ~2s scan is long enough for the + // user to switch away inside it, and the post-scan gate answers `pane-hidden` for that too. + 'pane-hidden' +]) + +export function installAgentResumeRecovery(session: ConnectPanePtySession): void { + const bindingStillOwnsPane = (): boolean => + !session.disposed && + session.deps.paneTransportsRef.current.get(session.pane.id) === session.transport + + const resumeWithCandidate = (candidate: AgentResumeCandidate): boolean => { + if (!bindingStillOwnsPane()) { + return false + } + const state = useAppStore.getState() + const target = resolveAgentResumeLaunchTarget({ + projectRuntime: session.projectRuntime, + connectionId: session.connectionId, + executionHostId: session.executionHostId, + worktreePath: paneAgentResumeScopePath({ + worktreePath: session.worktree?.path, + folderWorkspacePath: session.folderWorkspace?.folderPath + }), + terminalWindowsShell: state.settings?.terminalWindowsShell, + tabShellOverride: session.shellOverride, + hostPlatform: candidate.executionHostPlatform + }) + const startup = buildCandidateResumeStartup({ + candidate, + cmdOverrides: state.settings?.agentCmdOverrides ?? {}, + agentDefaultArgs: state.settings?.agentDefaultArgs, + agentDefaultEnv: state.settings?.agentDefaultEnv, + platform: target.platform, + shell: target.shell + }) + if (!startup) { + return false + } + // EP-STATE: revalidate the identity that authorized this candidate, immediately before the + // spawn and in one synchronous step with the claim. The chooser's rows were scanned seconds + // ago, and the renderer-local reservation map is not the only way a candidate goes live — + // another pane's cold restore and an Agent Session History launch both reserve nothing here, + // so the host-owned status store is the evidence that settles it. + if ( + claimedProviderSessionIds(useAppStore.getState(), session.cacheKey).has( + candidate.providerSession.id + ) || + // Two panes that resolved the same sole candidate while both scans were in flight cannot + // both get past this line. + !reserveAgentResumeSession(candidate.providerSession.id, session.cacheKey) + ) { + return false + } + // The plain shell this connection just spawned still owns the pane's stable key, so a bare + // connect would REATTACH it instead of running the resume command: recovery would report + // success, close the chooser, and leave the same shell. reattach-result-handler only retires + // an adopted shell for a passive sleeping-record restore, and this startup has no record by + // design — so retire the binding here, the way that path does. + session.transport.disconnect() + const retiredPtyId = session.spawnedFreshPtyId + if (retiredPtyId) { + session.clearExitedPanePtyLayoutBinding(retiredPtyId) + session.deps.clearTabPtyId(session.deps.tabId, retiredPtyId) + } else { + session.syncPanePtyLayoutBinding(null) + } + // Held so disposal can tell "reserved, spawn still settling" from "reserved and claimed". + // Releasing in that window frees a transcript a sibling pane can then respawn. + const spawned = Promise.resolve(session.startFreshColdRestoreAgentResume(startup)).catch( + () => undefined + ) + session.agentResumeSpawnInFlight = spawned + void spawned.finally(() => { + if (session.agentResumeSpawnInFlight === spawned) { + session.agentResumeSpawnInFlight = null + } + }) + return true + } + + session.agentResumeRecoveryUnregister = registerAgentResumePaneHandler( + session.cacheKey, + session.transport, + resumeWithCandidate + ) + + // One shot: it re-arms from the same gate if the next attempt still finds no evidence, and the + // latch makes a late fire a no-op. Hidden panes and unreachable hosts keep their own retries. + const watchForPaneAgentEvidence = (): void => { + if (session.agentResumeRecoveryStatusUnsubscribe) { + return + } + session.agentResumeRecoveryStatusUnsubscribe = useAppStore.subscribe(() => { + if (session.agentResumeRecoveryAttempted || !bindingStillOwnsPane()) { + return + } + if (!isResumableTuiAgent(session.resolvePaneScopedTuiAgent?.() ?? null)) { + return + } + session.agentResumeRecoveryStatusUnsubscribe?.() + session.agentResumeRecoveryStatusUnsubscribe = null + void session.attemptAgentResumeRecovery?.() + }) + } + + session.attemptAgentResumeRecovery = async (): Promise => { + // Once per connection: a visibility flip must not re-ask the host, and a pane that already + // declined a choice must not be offered it again on every tab switch. + if (session.agentResumeRecoveryAttempted || !bindingStillOwnsPane()) { + return + } + // Only the plain shell this connection just spawned may be replaced; a reattached PTY may + // still be running the agent itself. Not latched: the spawn triggers its own attempt. + if (!session.spawnedFreshPtyId) { + return + } + // This pane was opened to run something specific, so its launchAgent names what the user just + // asked for — not a conversation that went missing. Recovery starts before the startup is + // delivered and automatic delivery records no input, so a scan finishing later would replace + // the requested agent with an older transcript. Latched: the request stands for this + // connection even after the command has been delivered and cleared. + if (session.paneStartup?.command) { + session.agentResumeRecoveryAttempted = true + return + } + // A hidden pane must not spend the latch: it retries when the user reveals it. + if (!session.deps.isVisibleRef.current) { + return + } + // Positive evidence THIS PANE hosted an agent. Never the tab-wide launch agent: it + // describes the tab's original pty only (terminal-pane-close-identity.ts), so a plain-shell + // split in an agent-launched tab would pass and have its shell destructively replaced. + const paneAgent = session.resolvePaneScopedTuiAgent?.() ?? null + if (!isResumableTuiAgent(paneAgent)) { + // A restored pane's only pane-scoped evidence can be the hook server's persisted status, + // which lands after onPtySpawn has already run this gate. An already-visible pane gets no + // later visibility flip, so without a watch it sits as a plain shell until the user + // switches away and back. Armed here rather than at install so only a pane actually + // waiting on hydration carries a subscription. + watchForPaneAgentEvidence() + return + } + const worktreePath = paneAgentResumeScopePath({ + worktreePath: session.worktree?.path, + folderWorkspacePath: session.folderWorkspace?.folderPath + }) + if (!worktreePath) { + return + } + session.agentResumeRecoveryAttempted = true + try { + const action = await recoverAgentSessionForPane({ + paneKey: session.cacheKey, + worktreePath, + executionHostId: session.executionHostId, + paneAgent, + readPaneState: () => { + const state = useAppStore.getState() + return { + paneHasOwnRecord: Boolean(session.getSleepingRecordForPane(state)), + paneIsVisible: session.deps.isVisibleRef.current, + // The same reading `isUntouchedFreshSpawnPty` uses: any input makes the shell theirs. + paneHasReceivedInput: Number.isFinite(session.lastTerminalInputAt) + } + }, + // The pane's own row, from the host-owned status store — never the tab's. + readPaneProviderSessionId: () => + useAppStore.getState().agentStatusByPaneKey[session.cacheKey]?.providerSession?.id ?? + null, + readClaimedSessionIds: () => + claimedProviderSessionIds(useAppStore.getState(), session.cacheKey), + fetchCandidates: (args) => + fetchAgentResumeCandidates({ + ...args, + listSessions: (request) => window.api.aiVault.listSessions(request) + }), + resume: resumeWithCandidate, + offerChoice: (paneKey, candidates) => { + // A choice that arrives after the pane is gone would outlive it on the stable pane key. + if (bindingStillOwnsPane()) { + setPendingAgentResumeChoices(paneKey, session.transport, candidates) + } + } + }) + if (action.kind === 'none' && UNSPENT_AGENT_RESUME_REFUSALS.has(action.reason)) { + session.agentResumeRecoveryAttempted = false + } + } catch (err) { + // A relay that never answered is not evidence about this pane, so the attempt is retried + // on the next reveal rather than disabled for the life of the connection. + session.agentResumeRecoveryAttempted = false + console.warn('[agent-resume] recovery attempt failed:', err) + } + } +} diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-resume-reservation-release.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-resume-reservation-release.ts new file mode 100644 index 000000000000..3f24bcdd3360 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-resume-reservation-release.ts @@ -0,0 +1,27 @@ +import { releaseAgentResumeSessionsForPane } from '@/lib/agent-resume-session-reservations' +import type { ConnectPanePtySession } from './connect-pane-pty-session' + +/** + * Hands a retired binding's resume reservation back, once it is safe to. + * + * Two things make "now" wrong. A successor may already own the stable pane key, and releasing + * its reservation would reopen the fork window. And a reservation whose spawn is still settling + * has no claim yet, so releasing it leaves a sibling pane free to reserve and respawn the same + * transcript — the fork the reservation map exists to prevent. The owner is therefore re-read at + * release time rather than at dispose time, because a deferred release can land after the slot + * changed hands. + */ +export function releaseAgentResumeReservationOnDispose(session: ConnectPanePtySession): void { + const releaseWhenOwned = (): void => { + const owner = session.deps.paneTransportsRef.current.get(session.pane.id) + if (!owner || owner === session.transport) { + releaseAgentResumeSessionsForPane(session.cacheKey) + } + } + const inFlight = session.agentResumeSpawnInFlight + if (inFlight) { + void inFlight.then(releaseWhenOwned, releaseWhenOwned) + return + } + releaseWhenOwned() +} diff --git a/src/renderer/src/components/terminal-pane/pty-connection/candidate-resume-startup.ts b/src/renderer/src/components/terminal-pane/pty-connection/candidate-resume-startup.ts new file mode 100644 index 000000000000..7fbf4f9a5a8f --- /dev/null +++ b/src/renderer/src/components/terminal-pane/pty-connection/candidate-resume-startup.ts @@ -0,0 +1,59 @@ +import { createBrowserUuid } from '@/lib/browser-uuid' +import { buildAgentResumeStartupPlan } from '@/lib/tui-agent-startup' +import type { AgentResumeCandidate } from '../../../../../shared/agent-resume-candidate' +import { + resolveTuiAgentLaunchArgs, + resolveTuiAgentLaunchEnv +} from '../../../../../shared/tui-agent-launch-defaults' +import type { TuiAgent } from '../../../../../shared/tui-agent' +import type { AgentStartupShell } from '../../../../../shared/tui-agent-startup-shell' + +import type { ColdRestoreAgentResumeStartup } from './fresh-spawn-types' + +/** + * Turns a session recovered from the host's index into a spawn payload. + * + * Unlike the cold-restore path there is no captured `launchConfig` to reuse — the handle that + * held it is exactly what was lost — so the pane's configured defaults for that agent apply. + * A resumed pane therefore comes back with default flags rather than the flags the original + * turn ran with; the resume itself is what matters, and inventing the old flags would be a + * guess about a launch nobody recorded. + */ +export function buildCandidateResumeStartup(args: { + candidate: AgentResumeCandidate + cmdOverrides: Partial> + agentDefaultArgs: Partial> | undefined + agentDefaultEnv: Partial>> | undefined + platform: NodeJS.Platform + /** Optional exactly as the plan builder takes it: absent means the host default. */ + shell?: AgentStartupShell +}): ColdRestoreAgentResumeStartup | null { + const { candidate } = args + const startupPlan = buildAgentResumeStartupPlan({ + agent: candidate.agent, + providerSession: candidate.providerSession, + cmdOverrides: args.cmdOverrides, + agentArgs: resolveTuiAgentLaunchArgs(candidate.agent, args.agentDefaultArgs), + agentEnv: resolveTuiAgentLaunchEnv(candidate.agent, args.agentDefaultEnv), + platform: args.platform, + ...(args.shell ? { shell: args.shell } : {}) + }) + if (!startupPlan) { + return null + } + const launchToken = createBrowserUuid() + return { + agent: candidate.agent, + command: startupPlan.launchCommand, + env: { ...startupPlan.env, ORCA_AGENT_LAUNCH_TOKEN: launchToken }, + launchConfig: startupPlan.launchConfig, + resumeProviderSession: candidate.providerSession, + launchToken, + // Neither is true here: this pane had no live entry and no record — that is why the + // recovery path ran at all. Saying otherwise would make the spawn consume a record + // that does not exist. + useLiveEntry: false, + hasSleepingRecord: false, + sleepingRecordEntry: null + } +} diff --git a/src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts b/src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts index e808a89dede0..92fbcfd72b45 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts @@ -23,6 +23,7 @@ import { import { installRunDeferredConnect } from './run-deferred-connect' import { installSleepingRecordAccess } from './sleeping-record-access' +import { installAgentResumeRecovery } from './agent-resume-recovery-install' import { installShellCommandInference } from './shell-command-inference' import { installInterruptInputIntent } from './interrupt-input-intent' import { installTerminalKeydownFit } from './terminal-keydown-fit' @@ -176,6 +177,9 @@ export function connectPanePty( installAgentTaskCompleteNotify(session) installDirectSshRetryStatus(session) installPtyInputRecovery(session) + // Must follow installPtyInputRecovery: it registers the chooser's pane handler under + // `session.transport`, which that installer is what assigns. + installAgentResumeRecovery(session) // Async reattach/exit callbacks can outlive the PaneManager that created // them. Keep their layout writes keyed by the durable leaf identity and // admit them only while this transport still owns the pane slot. diff --git a/src/renderer/src/components/terminal-pane/pty-connection/pane-agent-identity.ts b/src/renderer/src/components/terminal-pane/pty-connection/pane-agent-identity.ts index 19cd7cc374bd..40cd96b6a302 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/pane-agent-identity.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/pane-agent-identity.ts @@ -14,7 +14,10 @@ import { inspectRuntimeTerminalProcess } from '@/runtime/runtime-terminal-inspec import { parseAppSshPtyId } from '../../../../../shared/ssh-pty-id' import { dispatchTerminalCommandFinishedEvent } from '@/hooks/terminal-command-finished-event' import { getExecutionHostIdForWorktree } from '@/lib/worktree-runtime-owner' -import { resolveCommittedTitleAgentType } from '@/lib/pane-agent-evidence' +import { + resolveCommittedTitleAgentType, + resolvePaneScopedLaunchTuiAgent +} from '@/lib/pane-agent-evidence' import type { TuiAgent } from '../../../../../shared/tui-agent' import { isTuiAgent, TUI_AGENT_CONFIG } from '../../../../../shared/tui-agent-config' @@ -54,6 +57,20 @@ export function installPaneAgentIdentity(session: ConnectPanePtySession): void { const candidate = resolveLaunchAgentCandidate(useAppStore.getState()) return isTuiAgent(candidate) ? candidate : null } + /** The agent THIS PANE hosted, from pane-keyed evidence only. `resolveExpectedLaunchTuiAgent` + * also accepts the tab's `launchAgent`, which names the tab's original pty and leaks onto a + * plain-shell split; a destructive decision (replacing a live shell with a recovered + * conversation) may not rest on it. Null means no evidence, never "an ordinary shell". */ + session.resolvePaneScopedTuiAgent = (): TuiAgent | null => { + const state = useAppStore.getState() + return resolvePaneScopedLaunchTuiAgent({ + paneStartupLaunchAgent: session.paneStartup?.launchAgent, + paneStartupStatusAgent: session.paneStartup?.initialAgentStatus?.agent, + registeredLaunchAgent: state.agentLaunchConfigByPaneKey[session.cacheKey]?.identity.agentType, + statusEntryAgent: state.agentStatusByPaneKey[session.cacheKey]?.agentType, + foregroundAgent: state.paneForegroundAgentByPaneKey[session.cacheKey]?.agent + }) + } // Why: a launched/hook-known agent pane must confirm — not trust — a 133;D so a // full-screen agent's leaked nested-shell 133;D can't clear its tab identity, // even on a restore where no command-start read has recorded evidence yet. diff --git a/src/renderer/src/components/terminal-pane/pty-connection/pane-pty-visibility-bind.ts b/src/renderer/src/components/terminal-pane/pty-connection/pane-pty-visibility-bind.ts index ced77bdaa782..7e0bbe50c8be 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/pane-pty-visibility-bind.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/pane-pty-visibility-bind.ts @@ -186,6 +186,10 @@ export function installPanePtyVisibilityBind(session: ConnectPanePtySession): vo // pane slot. Its one-shot startup belongs to the successor, not here. return } + // Why here and not only on a visibility flip: the primary case is a tab that is already + // active when Orca opens, which never transitions hidden -> visible. The attempt latch + // keeps the two entry points from running twice. + void session.attemptAgentResumeRecovery?.() // Spend queued startup only after this pane owns a concrete PTY. try { session.deps.onQueuedStartupSpawned?.() diff --git a/src/renderer/src/components/terminal-pane/pty-connection/session-reconcile-dispose.ts b/src/renderer/src/components/terminal-pane/pty-connection/session-reconcile-dispose.ts index d1e57709107d..5779fddef276 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/session-reconcile-dispose.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/session-reconcile-dispose.ts @@ -1,3 +1,4 @@ +import { releaseAgentResumeReservationOnDispose } from './agent-resume-reservation-release' import { useAppStore } from '@/store' import { shouldReconcileDeadSession, @@ -7,6 +8,7 @@ import { import { cancelPendingSafeFitContinuations } from '@/lib/pane-manager/pane-tree-ops' import { PANE_PTY_RESIZE_HOLD_FLUSH_EVENT } from '@/lib/pane-manager/pane-pty-resize-hold' import { discardTerminalOutput } from '@/lib/pane-manager/pane-terminal-output-scheduler' +import { clearPendingAgentResumeChoicesForOwner } from '@/lib/pending-agent-resume-choices' import { getProviderSessionClaimKey, isPassiveCompletedHibernationEvidence @@ -108,6 +110,9 @@ export function installSessionReconcileDispose(session: ConnectPanePtySession): session.consumeHibernatedAgentWake() session.requestKnownWindowsShiftEnterReconfirmation() session.sampleVisiblePaneForegroundAgent() + // Why here: a pane that lost its resume handle recovers only once it is actually looked + // at, so a host restart never respawns a whole workspace behind the user's back. + void session.attemptAgentResumeRecovery?.() }, reassertPtySizeAfterWindowWake() { session.armVisibleRemoteViewportClaim() @@ -176,12 +181,24 @@ export function installSessionReconcileDispose(session: ConnectPanePtySession): session.spawnedFreshPtyId === ptyId && !Number.isFinite(session.lastTerminalInputAt), dispose() { session.disposed = true + // A replaced connection must not leave a resume handler pointing at a transport that no + // longer owns this pane. + session.agentResumeRecoveryUnregister?.() + // The hydration retry watches the store for the life of the connection; a retired binding + // must stop watching or it keeps re-asking on behalf of a pane it no longer owns. + session.agentResumeRecoveryStatusUnsubscribe?.() + session.agentResumeRecoveryStatusUnsubscribe = null + // Identity, not the pane slot, decides whose chooser this is: a published choice names the + // binding that scanned it, so a retired one is dropped here and a successor's is left be. + // Without that, the stale chooser stayed up and reached the successor's handler. + clearPendingAgentResumeChoicesForOwner(session.cacheKey, session.transport) session.startupTiming?.finish('disposed') // A successor can claim the numeric pane slot before this retired // binding's disposal callback runs; do not clear its pane-scoped error. const currentPaneTransport = session.deps.paneTransportsRef.current.get(session.pane.id) if (!currentPaneTransport || currentPaneTransport === session.transport) { session.deps.onPtyErrorClearedRef?.current?.(session.pane.id) + releaseAgentResumeReservationOnDispose(session) } // Why: a detached client stops observing the pane's bytes, so it must cede // agent-status authority back to the host on the next mirrored snapshot. diff --git a/src/renderer/src/i18n/agent-resume-chooser-locales.test.ts b/src/renderer/src/i18n/agent-resume-chooser-locales.test.ts new file mode 100644 index 000000000000..3d796a7565a1 --- /dev/null +++ b/src/renderer/src/i18n/agent-resume-chooser-locales.test.ts @@ -0,0 +1,53 @@ +/** + * The chooser is a BLOCKING decision surface: it decides which conversation a terminal resumes. + * A missing key falls back to the inline English default with nothing at runtime to signal the + * gap, so every shipped locale must carry the block, and none of them may ship the English source. + */ +import { describe, expect, it } from 'vitest' +import en from './locales/en.json' +import es from './locales/es.json' +import fr from './locales/fr.json' +import ja from './locales/ja.json' +import ko from './locales/ko.json' +import zh from './locales/zh.json' + +const CHOOSER_PATH = ['components', 'terminalPane', 'AgentResumeChooser'] as const +const KEYS = ['label', 'title', 'help', 'dismiss'] as const +const TRANSLATED = { es, fr, ja, ko, zh } + +function readChild(node: unknown, key: string): unknown { + if (typeof node !== 'object' || node === null) { + return undefined + } + for (const [name, value] of Object.entries(node)) { + if (name === key) { + return value + } + } + return undefined +} + +function chooserString(catalog: unknown, key: string): unknown { + return readChild([...CHOOSER_PATH].reduce(readChild, catalog), key) +} + +describe('AgentResumeChooser locale coverage', () => { + it('keeps the English source the component falls back to', () => { + expect(chooserString(en, 'label')).toBe('Choose a session to resume') + expect(chooserString(en, 'title')).toBe('Which session should this terminal resume?') + expect(chooserString(en, 'help')).toBe( + 'Press a number or Enter to resume, Esc for a plain shell.' + ) + expect(chooserString(en, 'dismiss')).toBe('Start a plain shell instead') + }) + + for (const [locale, catalog] of Object.entries(TRANSLATED)) { + it(`carries every chooser key in ${locale}, translated`, () => { + for (const key of KEYS) { + const value = chooserString(catalog, key) + expect(typeof value).toBe('string') + expect(value).not.toBe(chooserString(en, key)) + } + }) + } +}) diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index f49cdcce869e..e7f98b8f3c1b 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -2726,6 +2726,20 @@ } } }, + "terminalPane": { + "AgentResumeChooser": { + "age": { + "days_one": "{{count}}d older", + "days_other": "{{count}}d older", + "hours_one": "{{count}}h older", + "hours_other": "{{count}}h older", + "minutes_one": "{{count}}m older", + "minutes_other": "{{count}}m older", + "newest": "newest", + "unknown": "unknown" + } + } + }, "workspace": { "cleanup": { "browse": { diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index cd2e52898919..ad0b264aea7a 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -17905,6 +17905,22 @@ "copySessionId": "Copy Session ID", "copySessionIdSuccess": "Session ID copied", "copySessionIdError": "Unable to copy session ID" + }, + "AgentResumeChooser": { + "label": "Choose a session to resume", + "title": "Which session should this terminal resume?", + "help": "Press a number or Enter to resume, Esc for a plain shell.", + "dismiss": "Start a plain shell instead", + "age": { + "unknown": "unknown", + "newest": "newest", + "minutes_one": "{{count}}m older", + "minutes_other": "{{count}}m older", + "hours_one": "{{count}}h older", + "hours_other": "{{count}}h older", + "days_one": "{{count}}d older", + "days_other": "{{count}}d older" + } } }, "settings": { diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 7c0322c563e2..edb4efd772ee 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -14832,6 +14832,22 @@ "copySessionId": "Copiar ID de sesión", "copySessionIdSuccess": "ID de sesión copiado", "copySessionIdError": "No se pudo copiar el ID de sesión" + }, + "AgentResumeChooser": { + "label": "Elige una sesión para reanudar", + "title": "¿Qué sesión debe reanudar esta terminal?", + "help": "Pulsa un número o Enter para reanudar, Esc para una shell simple.", + "dismiss": "Iniciar una shell simple", + "age": { + "unknown": "desconocido", + "newest": "la más reciente", + "minutes_one": "{{count}} min más antigua", + "minutes_other": "{{count}} min más antiguas", + "hours_one": "{{count}} h más antigua", + "hours_other": "{{count}} h más antiguas", + "days_one": "{{count}} d más antigua", + "days_other": "{{count}} d más antiguas" + } } } }, diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index d685d2a2718e..dbd3c8eabb04 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -16413,6 +16413,24 @@ "days": "{{value0}} j", "underOneMinute": "<1 min" } + }, + "terminalPane": { + "AgentResumeChooser": { + "label": "Choisissez une session à reprendre", + "title": "Quelle session ce terminal doit-il reprendre ?", + "help": "Appuyez sur un chiffre ou Enter pour reprendre, Esc pour un shell simple.", + "dismiss": "Démarrer un shell simple", + "age": { + "unknown": "inconnu", + "newest": "la plus récente", + "minutes_one": "{{count}} min plus ancienne", + "minutes_other": "{{count}} min plus anciennes", + "hours_one": "{{count}} h plus ancienne", + "hours_other": "{{count}} h plus anciennes", + "days_one": "{{count}} j plus ancienne", + "days_other": "{{count}} j plus anciennes" + } + } } }, "dashboardPopout": { diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 6a3994208528..33d2d590d39f 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -14867,6 +14867,19 @@ "copySessionId": "セッション ID をコピー", "copySessionIdSuccess": "セッション ID をコピーしました", "copySessionIdError": "セッション ID のコピーに失敗しました" + }, + "AgentResumeChooser": { + "label": "再開するセッションを選択", + "title": "このターミナルで再開するセッションはどれですか?", + "help": "数字または Enter を押すと再開、Esc でシンプルなシェルを起動します。", + "dismiss": "代わりにシンプルなシェルを起動", + "age": { + "unknown": "不明", + "newest": "最新", + "minutes_other": "{{count}}分前", + "hours_other": "{{count}}時間前", + "days_other": "{{count}}日前" + } } } }, diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 636e1c699f25..d52362d6f44c 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -15005,6 +15005,19 @@ "copySessionId": "세션 ID 복사", "copySessionIdSuccess": "세션 ID를 복사했습니다", "copySessionIdError": "세션 ID를 복사하지 못했습니다" + }, + "AgentResumeChooser": { + "label": "재개할 세션 선택", + "title": "이 terminal에서 어떤 세션을 재개할까요?", + "help": "숫자 또는 Enter를 누르면 재개하고, Esc를 누르면 일반 셸을 시작합니다.", + "dismiss": "대신 일반 셸 시작", + "age": { + "unknown": "알 수 없음", + "newest": "최신", + "minutes_other": "{{count}}분 이전", + "hours_other": "{{count}}시간 이전", + "days_other": "{{count}}일 이전" + } } } }, diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 975f2c34b25a..02a6049d9023 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -14973,6 +14973,19 @@ "copySessionId": "复制会话 ID", "copySessionIdSuccess": "已复制会话 ID", "copySessionIdError": "复制会话 ID 失败" + }, + "AgentResumeChooser": { + "label": "选择要恢复的会话", + "title": "此终端应恢复哪个会话?", + "help": "按数字键或 Enter 恢复,按 Esc 启动普通 Shell。", + "dismiss": "改为启动普通 Shell", + "age": { + "unknown": "未知", + "newest": "最新", + "minutes_other": "{{count}} 分钟前", + "hours_other": "{{count}} 小时前", + "days_other": "{{count}} 天前" + } } } }, diff --git a/src/renderer/src/lib/agent-resume-candidate-resolver.test.ts b/src/renderer/src/lib/agent-resume-candidate-resolver.test.ts new file mode 100644 index 000000000000..6af6e23de6a2 --- /dev/null +++ b/src/renderer/src/lib/agent-resume-candidate-resolver.test.ts @@ -0,0 +1,392 @@ +import { describe, expect, it } from 'vitest' +import { + AGENT_RESUME_SUBSTANCE_FLOOR_MESSAGES, + type AgentResumeCandidate, + type AgentResumeResolution +} from '../../../shared/agent-resume-candidate' +import { RESUMABLE_TUI_AGENTS } from '../../../shared/agent-session-resume' +import { + resolveAgentResumeCandidate, + type ResolveAgentResumeCandidateArgs +} from './agent-resume-candidate-resolver' + +const WORKTREE = '/srv/repo/worktrees/feature-a' +const HOUR = 60 * 60 * 1000 +const T0 = 1_750_000_000_000 + +function candidate( + id: string, + overrides: Partial = {} +): AgentResumeCandidate { + return { + agent: 'codex', + providerSession: { key: 'session_id', id }, + cwd: WORKTREE, + title: id, + updatedAt: T0, + messageCount: 200, + branch: 'feature-a', + executionHostId: 'ssh:host-1', + executionHostPlatform: null, + ...overrides + } +} + +function resolve(overrides: Partial): AgentResumeResolution { + return resolveAgentResumeCandidate({ + candidates: [], + paneAgent: 'codex', + paneProviderSessionId: null, + worktreePath: WORKTREE, + claimedSessionIds: new Set(), + ...overrides + }) +} + +function summarize(resolution: AgentResumeResolution): string { + switch (resolution.kind) { + case 'resume': + return `resume:${resolution.candidate.providerSession.id}:${resolution.reason}` + case 'choose': + return `choose:${resolution.candidates.map((c) => c.providerSession.id).join(',')}` + case 'none': + return `none:${resolution.reason}` + } +} + +type Row = { name: string; args: Partial; expected: string } + +const rungs: Row[] = [ + { name: 'rung 1: no candidates at all', args: {}, expected: 'none:no-candidates' }, + { + name: 'rung 1: every survivor claimed by a live pane', + args: { + candidates: [candidate('a'), candidate('b')], + claimedSessionIds: new Set(['a', 'b']) + }, + expected: 'none:every-candidate-claimed' + }, + { + name: 'rung 1: claimed thin sessions are not "every candidate claimed"', + args: { + candidates: [candidate('a', { messageCount: 3 })], + claimedSessionIds: new Set(['a']) + }, + expected: 'none:no-candidates' + }, + { + name: 'rung 2: sole survivor', + args: { candidates: [candidate('a')] }, + expected: 'resume:a:sole-candidate' + }, + { + name: 'last rung: survivors ranked newest first', + args: { + candidates: [ + candidate('old', { updatedAt: T0 }), + candidate('new', { updatedAt: T0 + 2 * HOUR }), + candidate('mid', { updatedAt: T0 + HOUR }) + ] + }, + expected: 'choose:new,mid,old' + } +] + +const filters: Row[] = [ + { + name: 'filter: agent mismatch with a known pane agent', + args: { candidates: [candidate('a', { agent: 'gemini' }), candidate('b')] }, + expected: 'resume:b:sole-candidate' + }, + { + name: 'filter: unknown pane agent keeps every agent in play', + args: { paneAgent: null, candidates: [candidate('a', { agent: 'gemini' }), candidate('b')] }, + expected: 'choose:a,b' + }, + { + name: 'filter: cwd must equal the worktree path exactly', + args: { candidates: [candidate('a', { cwd: `${WORKTREE}/src` }), candidate('b')] }, + expected: 'resume:b:sole-candidate' + }, + { + // A trailing separator spells the same directory; only a DIFFERENT directory may miss. + name: 'filter: a trailing separator still names the worktree', + args: { candidates: [candidate('a', { cwd: `${WORKTREE}/` })] }, + expected: 'resume:a:sole-candidate' + }, + { + name: 'filter: below the substance floor', + args: { + candidates: [ + candidate('a', { messageCount: AGENT_RESUME_SUBSTANCE_FLOOR_MESSAGES - 1 }), + candidate('b', { messageCount: AGENT_RESUME_SUBSTANCE_FLOOR_MESSAGES }) + ] + }, + expected: 'resume:b:sole-candidate' + }, + { + name: 'filter: claimed by another live pane', + args: { candidates: [candidate('a'), candidate('b')], claimedSessionIds: new Set(['a']) }, + expected: 'resume:b:sole-candidate' + } +] + +const regressions: Row[] = [ + { + name: 'regression 1: a thin newer diagnostic never outranks a substantial older session', + args: { + candidates: [ + candidate('diagnostic', { messageCount: 39, updatedAt: T0 + HOUR }), + candidate('work', { messageCount: 758, updatedAt: T0 - 5 * HOUR }) + ] + }, + expected: 'resume:work:sole-candidate' + }, + { + name: 'regression 2: two substantial candidates with no tab affinity ask the user', + args: { + candidates: [ + candidate('a', { messageCount: 758 }), + candidate('b', { messageCount: 300, updatedAt: T0 - HOUR }) + ] + }, + expected: 'choose:a,b' + }, + { + name: 'regression 3: a claimed id is dropped, not resumed', + args: { + candidates: [candidate('a'), candidate('b'), candidate('c')], + claimedSessionIds: new Set(['a']) + }, + expected: 'choose:b,c' + }, + { + name: 'regression 3: a claimed newest candidate is never resumed', + args: { + candidates: [candidate('a'), candidate('b', { updatedAt: T0 + 10 * HOUR })], + claimedSessionIds: new Set(['a', 'b']) + }, + expected: 'none:every-candidate-claimed' + }, + { + name: 'regression 4: a sibling worktree whose path is a prefix never matches', + args: { + worktreePath: `${WORKTREE}-2`, + candidates: [candidate('sibling', { cwd: WORKTREE })] + }, + expected: 'none:no-candidates' + }, + { + name: 'regression 4: a basename-only match never matches', + args: { candidates: [candidate('other', { cwd: '/elsewhere/feature-a' })] }, + expected: 'none:no-candidates' + } +] + +const malformed: Row[] = [ + { + name: 'empty session id is dropped', + args: { candidates: [candidate('')] }, + expected: 'none:no-candidates' + }, + { + name: 'whitespace-padded session id is dropped rather than rewritten', + args: { candidates: [candidate(' a ')] }, + expected: 'none:no-candidates' + }, + { + name: 'unknown agent is dropped even when the pane agent is unknown', + args: { + paneAgent: null, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: simulates an untrusted host answer carrying a non-resumable agent. + candidates: [candidate('a', { agent: 'not-an-agent' as AgentResumeCandidate['agent'] })] + }, + expected: 'none:no-candidates' + }, + { + name: 'empty worktree path matches nothing', + args: { worktreePath: '', candidates: [candidate('a', { cwd: '' })] }, + expected: 'none:no-candidates' + }, + { + name: 'duplicate ids block selection', + args: { candidates: [candidate('a'), candidate('a', { updatedAt: T0 + HOUR })] }, + expected: 'none:ambiguous' + }, + { + name: 'duplicate id reported in a sibling cwd still blocks selection', + args: { candidates: [candidate('a'), candidate('a', { cwd: '/elsewhere' })] }, + expected: 'none:ambiguous' + }, + { + name: 'duplicate id does not let the rival win by default', + args: { candidates: [candidate('a'), candidate('a'), candidate('b')] }, + expected: 'none:ambiguous' + }, + { + name: 'non-finite updatedAt blocks selection', + args: { candidates: [candidate('a', { updatedAt: Number.NaN }), candidate('b')] }, + expected: 'none:ambiguous' + }, + { + name: 'negative updatedAt blocks selection', + args: { candidates: [candidate('a', { updatedAt: -5 })] }, + expected: 'none:ambiguous' + }, + { + name: 'negative messageCount blocks selection', + args: { candidates: [candidate('a', { messageCount: -1 }), candidate('b')] }, + expected: 'none:ambiguous' + }, + { + name: 'non-finite messageCount blocks selection', + args: { candidates: [candidate('a', { messageCount: Number.POSITIVE_INFINITY })] }, + expected: 'none:ambiguous' + }, + { + name: 'malformed evidence on a claimed session is irrelevant', + args: { + candidates: [candidate('a', { updatedAt: Number.NaN }), candidate('b')], + claimedSessionIds: new Set(['a']) + }, + expected: 'resume:b:sole-candidate' + }, + { + name: 'a candidate with an empty session id is dropped', + args: { candidates: [candidate('a'), candidate('', { messageCount: 500 }), candidate('b')] }, + expected: 'choose:a,b' + } +] + +describe('resolveAgentResumeCandidate', () => { + it.each([...rungs, ...filters, ...regressions, ...malformed])('$name', ({ args, expected }) => { + expect(summarize(resolve(args))).toBe(expected) + }) + + it.each(RESUMABLE_TUI_AGENTS)('resolves %s without an agent special case', (agent) => { + const result = resolve({ paneAgent: agent, candidates: [candidate('a', { agent })] }) + expect(summarize(result)).toBe('resume:a:sole-candidate') + }) + + it('never returns a claimed id', () => { + const candidates = [ + candidate('a'), + candidate('b', { updatedAt: T0 + 10 * HOUR }), + candidate('c', { updatedAt: T0 + 20 * HOUR }) + ] + const result = resolve({ candidates, claimedSessionIds: new Set(['a']) }) + const returned = result.kind === 'choose' ? result.candidates : [] + expect(returned.map((c) => c.providerSession.id)).not.toContain('a') + }) + + it('does not mutate the caller candidate order', () => { + const candidates = [candidate('old'), candidate('new', { updatedAt: T0 + HOUR })] + resolve({ candidates }) + expect(candidates.map((c) => c.providerSession.id)).toEqual(['old', 'new']) + }) + it("resumes the pane's own transcript started in a subdirectory of the workspace", () => { + // Agents are routinely started from a child directory. The status row names the session by + // identity, so exact-cwd scoping must not drop it and hand the pane a rival transcript. + const mine = candidate('mine', { cwd: `${WORKTREE}/packages/app`, messageCount: 3 }) + const rival = candidate('rival', { messageCount: 500 }) + expect(resolve({ candidates: [rival, mine], paneProviderSessionId: 'mine' })).toMatchObject({ + kind: 'resume', + candidate: mine, + reason: 'pane-record' + }) + }) + + it("resumes the pane's own transcript even when a rival is more substantial", () => { + // A restored status row names this pane's session by identity. Judging it on substance lets + // a thin-but-correct conversation lose to an unrelated substantial one, which forks it. + const mine = candidate('mine', { messageCount: 3 }) + const rival = candidate('rival', { messageCount: 500 }) + expect(resolve({ candidates: [rival, mine], paneProviderSessionId: 'mine' })).toMatchObject({ + kind: 'resume', + candidate: mine, + reason: 'pane-record' + }) + }) +}) + +describe('equivalent path spellings', () => { + it('matches a candidate whose cwd differs only in spelling', () => { + // Windows hands back `C:\repo` where the workspace records `C:/repo/`, and macOS hands back + // NFD where the agent recorded NFC. Both name one directory. + expect( + summarize( + resolve({ + worktreePath: 'C:/repo/app/', + candidates: [candidate('s1', { cwd: 'c:\\repo\\app' })] + }) + ) + ).toBe('resume:s1:sole-candidate') + }) + + it('still refuses a sibling worktree', () => { + expect( + summarize( + resolve({ + worktreePath: '/srv/repo/worktrees/feature-a', + candidates: [candidate('s1', { cwd: '/srv/repo/worktrees/feature-b' })] + }) + ) + ).toBe('none:no-candidates') + }) + + it('still refuses a parent of the worktree', () => { + expect( + summarize( + resolve({ + worktreePath: '/srv/repo/worktrees/feature-a', + candidates: [candidate('s1', { cwd: '/srv/repo/worktrees' })] + }) + ) + ).toBe('none:no-candidates') + }) +}) + +describe('a WSL workspace and its distro-side transcripts', () => { + // The workspace is stored as its UNC spelling; the agent running inside the distro records the + // Linux cwd. They normalize to different strings, so a single key discarded every WSL candidate + // and recovery never ran on WSL at all. + const WSL_UNC = '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo' + + it('matches a transcript reporting the distro Linux path', () => { + expect( + summarize( + resolve({ worktreePath: WSL_UNC, candidates: [candidate('s1', { cwd: '/home/me/repo' })] }) + ) + ).toBe('resume:s1:sole-candidate') + }) + + it('still matches a transcript reporting the UNC spelling', () => { + expect( + summarize( + resolve({ + worktreePath: WSL_UNC, + candidates: [candidate('s1', { cwd: '//wsl$/Ubuntu/home/me/repo' })] + }) + ) + ).toBe('resume:s1:sole-candidate') + }) + + it('still refuses a sibling worktree inside the distro', () => { + expect( + summarize( + resolve({ + worktreePath: WSL_UNC, + candidates: [candidate('s1', { cwd: '/home/me/repo-two' })] + }) + ) + ).toBe('none:no-candidates') + }) + + it('still refuses the parent of the distro path', () => { + expect( + summarize( + resolve({ worktreePath: WSL_UNC, candidates: [candidate('s1', { cwd: '/home/me' })] }) + ) + ).toBe('none:no-candidates') + }) +}) diff --git a/src/renderer/src/lib/agent-resume-candidate-resolver.ts b/src/renderer/src/lib/agent-resume-candidate-resolver.ts new file mode 100644 index 000000000000..d0a1d2594b8f --- /dev/null +++ b/src/renderer/src/lib/agent-resume-candidate-resolver.ts @@ -0,0 +1,168 @@ +import { + AGENT_RESUME_SUBSTANCE_FLOOR_MESSAGES, + type AgentResumeCandidate, + type AgentResumeResolution +} from '../../../shared/agent-resume-candidate' +import { + isResumableTuiAgent, + normalizeAgentProviderSession, + type ResumableTuiAgent +} from '../../../shared/agent-session-resume' +import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' +import { parseWslUncPath } from '../../../shared/wsl-paths' + +export type ResolveAgentResumeCandidateArgs = { + candidates: readonly AgentResumeCandidate[] + paneAgent: ResumableTuiAgent | null + /** The provider session THIS pane's own status row names, when the host restored one. Its + * transcript is the pane's by identity, so it is not a contender to be judged on substance. */ + paneProviderSessionId: string | null + worktreePath: string + claimedSessionIds: ReadonlySet +} + +/** Resolves which conversation a pane with no resume handle should resume. Refuses rather than + * guesses: resuming the wrong transcript forks it unrecoverably, while refusing costs only a + * bare shell. */ +export function resolveAgentResumeCandidate( + args: ResolveAgentResumeCandidateArgs +): AgentResumeResolution { + const { paneAgent, worktreePath, claimedSessionIds } = args + // Only a resumable identity counts; an id the shared parser would rewrite or reject cannot be + // passed to getAgentResumeArgv as-is. + const identified = args.candidates.filter(hasResumableIdentity) + const idCounts = new Map() + for (const candidate of identified) { + const id = candidate.providerSession.id + idCounts.set(id, (idCounts.get(id) ?? 0) + 1) + } + + // The pane's own transcript wins outright, and before scope: the host's pane-keyed status row + // names it by identity, so it is this pane's session wherever it was started — an agent run + // from a subdirectory of the workspace has a cwd the exact-scope filter below would drop. + // Judging it on substance would also let a thin-but-correct conversation lose to a substantial + // unrelated one. Either way the outcome is the wrong transcript, resumed automatically. + if (args.paneProviderSessionId !== null) { + const owned = identified.find( + (candidate) => + candidate.providerSession.id === args.paneProviderSessionId && + (paneAgent === null || candidate.agent === paneAgent) + ) + if (owned) { + return { kind: 'resume', candidate: owned, reason: 'pane-record' } + } + } + + const scopeKeys = agentResumeScopeKeys(worktreePath) + const scoped = identified.filter( + (candidate) => + (paneAgent === null || candidate.agent === paneAgent) && + scopeKeys.has(normalizeRuntimePathForComparison(candidate.cwd)) + ) + + const survivors: AgentResumeCandidate[] = [] + let tainted = false + let claimedSubstantial = 0 + for (const candidate of scoped) { + const substance = readSubstance(candidate.messageCount) + if (substance === 'thin') { + continue + } + if (claimedSessionIds.has(candidate.providerSession.id)) { + if (substance === 'substantial') { + claimedSubstantial += 1 + } + continue + } + // A contender whose evidence is corrupt or duplicated still exists; dropping it would let a + // rival win by default, so its presence blocks every selection. + if ( + substance === 'unknown' || + !isHostTimestamp(candidate.updatedAt) || + (idCounts.get(candidate.providerSession.id) ?? 0) > 1 + ) { + tainted = true + continue + } + survivors.push(candidate) + } + + if (tainted) { + return { kind: 'none', reason: 'ambiguous' } + } + if (survivors.length === 0) { + return { + kind: 'none', + reason: claimedSubstantial > 0 ? 'every-candidate-claimed' : 'no-candidates' + } + } + if (survivors.length === 1) { + return { kind: 'resume', candidate: survivors[0], reason: 'sole-candidate' } + } + + // Why no tab-session-match or lifetime-window rung: the renderer cannot source either. A tab + // carries no last provider session id — that handle is precisely what was lost — and its + // `createdAt` is a renderer-clock value, which this resolver may never compare to a host-clock + // `updatedAt`. Guessing across those clocks forks a transcript; the chooser asks instead. + // Display order only; the user decides. + const ranked = [...survivors].sort( + (a, b) => + b.updatedAt - a.updatedAt || + (a.providerSession.id < b.providerSession.id + ? -1 + : a.providerSession.id > b.providerSession.id + ? 1 + : 0) + ) + return { kind: 'choose', candidates: ranked } +} + +/** + * The normalized spellings that name THIS workspace directory, for equality against a candidate's + * cwd. + * + * Compared as normalized keys on BOTH sides, through the same normalizer the vault's own scope + * machinery uses: raw equality false-negatives on `C:\\repo` vs `C:/repo`, drive-letter casing, a + * trailing separator, and macOS NFD against an agent's NFC cwd. + * + * A WSL workspace is stored as its UNC spelling (`\\\\wsl.localhost\\Ubuntu\\home\\me\\repo`) while the + * transcripts inside the distro report cwd as `/home/me/repo`; they normalize to different strings, + * so a single key discarded every WSL candidate and recovery never ran there. Both spellings of one + * directory are admitted, the same representation pair + * main/ai-vault/session-scanner-scope-discovery.ts already expands for the scan itself. + * + * Still EQUALITY, not containment — a sibling worktree or the repo root must keep missing, which is + * what scopes the resume. + */ +function agentResumeScopeKeys(worktreePath: string): Set { + const keys = new Set() + if (worktreePath.length === 0) { + return keys + } + keys.add(normalizeRuntimePathForComparison(worktreePath)) + const wslWorktreePath = parseWslUncPath(worktreePath) + if (wslWorktreePath) { + keys.add(normalizeRuntimePathForComparison(wslWorktreePath.linuxPath)) + } + return keys +} + +function hasResumableIdentity(candidate: AgentResumeCandidate): boolean { + return ( + isResumableTuiAgent(candidate.agent) && + typeof candidate.cwd === 'string' && + candidate.cwd.length > 0 && + normalizeAgentProviderSession(candidate.providerSession)?.id === candidate.providerSession.id + ) +} + +function readSubstance(messageCount: number): 'thin' | 'substantial' | 'unknown' { + if (!Number.isInteger(messageCount) || messageCount < 0) { + return 'unknown' + } + return messageCount < AGENT_RESUME_SUBSTANCE_FLOOR_MESSAGES ? 'thin' : 'substantial' +} + +function isHostTimestamp(value: number | null | undefined): value is number { + return typeof value === 'number' && Number.isFinite(value) && value >= 0 +} diff --git a/src/renderer/src/lib/agent-resume-candidate-source.test.ts b/src/renderer/src/lib/agent-resume-candidate-source.test.ts new file mode 100644 index 000000000000..900546f15d64 --- /dev/null +++ b/src/renderer/src/lib/agent-resume-candidate-source.test.ts @@ -0,0 +1,301 @@ +import { describe, expect, it, vi } from 'vitest' +import { + AI_VAULT_SCAN_ISSUE_LIMIT, + type AiVaultScanIssue, + type AiVaultSession +} from '../../../shared/ai-vault-types' +import { DEFAULT_AI_VAULT_SCAN_LIMIT } from '../../../shared/ai-vault-session-depth' + +/** A host that honoured the uncapped request: the ordinary healthy answer. */ +const UNCAPPED = { appliedSessionDepth: 'unlimited' } as const +import { + fetchAgentResumeCandidates, + toAgentResumeCandidate, + toAgentResumeCandidates +} from './agent-resume-candidate-source' + +const BASE_SESSION: AiVaultSession = { + id: 'row-1', + executionHostId: 'local', + agent: 'claude', + sessionId: 'c4c95ae3-fdd1-4ab6-be99-478dd26c3a67', + title: 'Fix the ledger deadline', + cwd: '/home/ubuntu/Desktop/qbit', + branch: 'issue271', + model: null, + filePath: '/home/ubuntu/.claude/projects/x/y.jsonl', + codexHome: null, + createdAt: '2026-09-15T09:00:00.000Z', + updatedAt: '2026-09-15T09:40:00.000Z', + modifiedAt: '2026-09-15T09:41:00.000Z', + messageCount: 758, + totalTokens: 0, + previewMessages: [], + queuedMessageCount: 0, + subagentTranscriptCount: 0, + resumeCommand: 'claude --resume c4c95ae3-fdd1-4ab6-be99-478dd26c3a67', + subagent: null +} + +function session(overrides: Partial = {}): AiVaultSession { + return { ...BASE_SESSION, ...overrides } +} + +describe('toAgentResumeCandidate', () => { + it('maps an indexed session onto a candidate', () => { + const candidate = toAgentResumeCandidate(session(), 'ssh:ssh-1') + expect(candidate).toEqual({ + agent: 'claude', + providerSession: { + key: 'session_id', + id: 'c4c95ae3-fdd1-4ab6-be99-478dd26c3a67', + transcriptPath: '/home/ubuntu/.claude/projects/x/y.jsonl' + }, + cwd: '/home/ubuntu/Desktop/qbit', + title: 'Fix the ledger deadline', + updatedAt: Date.parse('2026-09-15T09:40:00.000Z'), + messageCount: 758, + branch: 'issue271', + executionHostId: 'ssh:ssh-1', + executionHostPlatform: null + }) + }) + + it('prefers the session updatedAt over the file mtime', () => { + const candidate = toAgentResumeCandidate(session(), null) + expect(candidate?.updatedAt).toBe(Date.parse('2026-09-15T09:40:00.000Z')) + }) + + it('falls back to the file mtime when updatedAt is absent', () => { + const candidate = toAgentResumeCandidate(session({ updatedAt: null }), null) + expect(candidate?.updatedAt).toBe(Date.parse('2026-09-15T09:41:00.000Z')) + }) + + // Why: the resolver must never select on a timestamp it cannot trust, and the host's + // answer crosses a trust boundary, so the bad row is refused at the entry point. + it('refuses a session whose timestamps are unparseable', () => { + expect(toAgentResumeCandidate(session({ updatedAt: 'never', modifiedAt: '' }), null)).toBeNull() + }) + + it('refuses an agent Orca cannot resume', () => { + expect(toAgentResumeCandidate(session({ agent: 'cursor' }), null)).toBeNull() + }) + + it('refuses a session with no cwd, because scope is what candidates are matched on', () => { + expect(toAgentResumeCandidate(session({ cwd: null }), null)).toBeNull() + }) + + it('refuses a session id the shared parser would reject', () => { + expect(toAgentResumeCandidate(session({ sessionId: '' }), null)).toBeNull() + expect(toAgentResumeCandidate(session({ sessionId: '-leading-dash' }), null)).toBeNull() + }) + + // Hardcoding `session_id` for every agent made Antigravity's candidate unusable: it passes + // isResumableTuiAgent, so it reached the chooser and then produced no resume argv at all. + it('reads Antigravity by conversation id', () => { + const candidate = toAgentResumeCandidate(session({ agent: 'antigravity' }), null) + expect(candidate?.providerSession).toEqual({ + key: 'conversation_id', + id: 'c4c95ae3-fdd1-4ab6-be99-478dd26c3a67' + }) + }) + + it('carries the transcript path the path-resuming agents need', () => { + const candidate = toAgentResumeCandidate(session({ agent: 'pi' }), null) + expect(candidate?.providerSession.transcriptPath).toBe( + '/home/ubuntu/.claude/projects/x/y.jsonl' + ) + }) + + // A candidate that cannot produce resume argv must never be offered: the chooser would + // dismiss itself and resume nothing. + it('refuses a path-resuming agent whose row has no transcript path', () => { + expect(toAgentResumeCandidate(session({ agent: 'pi', filePath: '' }), null)).toBeNull() + expect(toAgentResumeCandidate(session({ agent: 'prime-agent', filePath: '' }), null)).toBeNull() + }) + + it('drops unusable rows without discarding the usable ones beside them', () => { + const candidates = toAgentResumeCandidates( + [session(), session({ sessionId: '', id: 'row-2' }), session({ id: 'row-3' })], + null + ) + expect(candidates).toHaveLength(2) + }) +}) + +describe('fetchAgentResumeCandidates', () => { + it('asks only the host that owns the transcripts, scoped to the workspace', async () => { + const calls: unknown[] = [] + await fetchAgentResumeCandidates({ + worktreePath: '/home/ubuntu/Desktop/qbit', + executionHostId: 'ssh:ssh-1', + listSessions: async (request) => { + calls.push(request) + return { sessions: [session()], issues: [], scannedAt: '', ...UNCAPPED } + } + }) + expect(calls).toEqual([ + { + scopePaths: ['/home/ubuntu/Desktop/qbit'], + executionHostScope: 'ssh:ssh-1', + unlimited: true + } + ]) + }) + + // Why not "no candidates": loss of contact says nothing about the sessions, and a scan that + // answered about nothing must not let a subset be read as the sole candidate. + it('answers unverifiable when the host cannot be reached', async () => { + const scan = await fetchAgentResumeCandidates({ + worktreePath: '/home/ubuntu/Desktop/qbit', + executionHostId: 'ssh:ssh-1', + listSessions: async () => { + throw new Error('relay unreachable') + } + }) + expect(scan).toEqual({ kind: 'unverifiable', reason: 'no-contact' }) + }) + + // A cancelled scan resolves with an empty body by construction, which is the shape most + // likely to be misread as "this host holds nothing". + it('answers unverifiable for a cancelled scan', async () => { + const scan = await fetchAgentResumeCandidates({ + worktreePath: '/home/ubuntu/Desktop/qbit', + executionHostId: 'ssh:ssh-1', + listSessions: async () => ({ sessions: [], issues: [], scannedAt: '', cancelled: true }) + }) + expect(scan).toEqual({ kind: 'unverifiable', reason: 'cancelled' }) + }) + + it('answers unverifiable when the scan reports an unread path or host', async () => { + const scan = await fetchAgentResumeCandidates({ + worktreePath: '/home/ubuntu/Desktop/qbit', + executionHostId: 'ssh:ssh-1', + listSessions: async () => ({ + sessions: [session()], + issues: [{ agent: 'claude', kind: 'host', path: '/home', message: 'host unreachable' }], + scannedAt: '' + }) + }) + expect(scan).toEqual({ kind: 'unverifiable', reason: 'scan-issues' }) + }) + + // A lone notice is per-transcript commentary (a transcript with skipped records), and the scan + // that produced it still covered its scope. + it('treats a short notice-only issue list as a complete scan', async () => { + const scan = await fetchAgentResumeCandidates({ + worktreePath: '/home/ubuntu/Desktop/qbit', + executionHostId: 'ssh:ssh-1', + listSessions: async () => ({ + sessions: [session()], + issues: [{ agent: 'claude', kind: 'notice', path: '', message: 'records were skipped' }], + scannedAt: '', + ...UNCAPPED + }) + }) + expect(scan.kind).toBe('complete') + }) + + // The opposite reading of the same kind: a list AT the cap is one `recordSessionScanIssue` + // stopped appending to, so the rows that did not fit are gone. A stalled WSL distro records one + // refusal per discovered path, and only the overflow notice survives filtering — reading that as + // a clean scan lets the surviving subset be auto-resumed as a sole candidate. + it('refuses a scan whose issue list hit the cap, even when every surviving row is a notice', async () => { + const issues: AiVaultScanIssue[] = Array.from( + { length: AI_VAULT_SCAN_ISSUE_LIMIT }, + (_, index) => ({ + agent: 'claude', + kind: 'notice', + path: `/w/${index}`, + message: 'Additional scan issues were omitted.' + }) + ) + const scan = await fetchAgentResumeCandidates({ + worktreePath: '/home/ubuntu/Desktop/qbit', + executionHostId: 'ssh:ssh-1', + listSessions: async () => ({ sessions: [session()], issues, scannedAt: '', ...UNCAPPED }) + }) + expect(scan).toEqual({ kind: 'unverifiable', reason: 'scan-issues' }) + }) + + it('does not query at all without a workspace path', async () => { + let queried = false + const scan = await fetchAgentResumeCandidates({ + worktreePath: '', + executionHostId: null, + listSessions: async () => { + queried = true + return { sessions: [], issues: [], scannedAt: '', ...UNCAPPED } + } + }) + expect(queried).toBe(false) + expect(scan).toEqual({ kind: 'complete', candidates: [] }) + }) +}) + +describe('scan completeness', () => { + it('asks the host for an uncapped scan', async () => { + const listSessions = vi.fn().mockResolvedValue({ sessions: [], issues: [] }) + await fetchAgentResumeCandidates({ + worktreePath: '/srv/wt', + executionHostId: 'ssh:ssh-1', + listSessions + }) + expect(listSessions).toHaveBeenCalledWith({ + scopePaths: ['/srv/wt'], + executionHostScope: 'ssh:ssh-1', + unlimited: true + }) + }) + + it('accepts a 1000-session answer the host honoured uncapped', async () => { + // This PR's own motivating machine. The old row-count heuristic called it truncated forever, + // disabling auto-resume on exactly the hosts that accumulate the most transcripts. + const sessions = Array.from({ length: DEFAULT_AI_VAULT_SCAN_LIMIT }, (_, index) => + session({ id: `row-${index}`, sessionId: `c4c95ae3-fdd1-4ab6-be99-478dd26c3a${index}` }) + ) + const scan = await fetchAgentResumeCandidates({ + worktreePath: '/srv/wt', + executionHostId: null, + listSessions: vi.fn().mockResolvedValue({ sessions, issues: [], ...UNCAPPED }) + }) + expect(scan.kind).toBe('complete') + }) + + it('refuses an answer from a host that never says what depth it applied', async () => { + // A host older than the signal. Its silence is not proof it honoured `unlimited`, and a host + // capping BELOW the default was invisible to the old row-count check entirely. + const scan = await fetchAgentResumeCandidates({ + worktreePath: '/srv/wt', + executionHostId: null, + listSessions: vi.fn().mockResolvedValue({ sessions: [session()], issues: [] }) + }) + expect(scan).toEqual({ kind: 'unverifiable', reason: 'scan-truncated' }) + }) + + it('refuses an answer that filled the depth its host applied, however small', async () => { + const sessions = [ + session(), + session({ id: 'row-2', sessionId: 'c4c95ae3-fdd1-4ab6-be99-478dd26c3a68' }) + ] + const scan = await fetchAgentResumeCandidates({ + worktreePath: '/srv/wt', + executionHostId: null, + listSessions: vi + .fn() + .mockResolvedValue({ sessions, issues: [], appliedSessionDepth: sessions.length }) + }) + expect(scan).toEqual({ kind: 'unverifiable', reason: 'scan-truncated' }) + }) + + it('accepts an answer that did not fill the depth its host applied', async () => { + const scan = await fetchAgentResumeCandidates({ + worktreePath: '/srv/wt', + executionHostId: null, + listSessions: vi + .fn() + .mockResolvedValue({ sessions: [session()], issues: [], appliedSessionDepth: 50 }) + }) + expect(scan.kind).toBe('complete') + }) +}) diff --git a/src/renderer/src/lib/agent-resume-candidate-source.ts b/src/renderer/src/lib/agent-resume-candidate-source.ts new file mode 100644 index 000000000000..80b1c60bf692 --- /dev/null +++ b/src/renderer/src/lib/agent-resume-candidate-source.ts @@ -0,0 +1,206 @@ +import type { AgentResumeCandidate } from '../../../shared/agent-resume-candidate' +import { + AI_VAULT_SCAN_ISSUE_LIMIT, + type AiVaultListArgs, + type AiVaultListResult, + type AiVaultSession +} from '../../../shared/ai-vault-types' +import type { ExecutionHostId } from '../../../shared/execution-host' +import { + extractAgentProviderSession, + getAgentResumeArgv, + isResumableTuiAgent, + type AgentProviderSessionMetadata, + type ResumableTuiAgent +} from '../../../shared/agent-session-resume' + +/** Epoch ms from the host's ISO stamps, preferring the session's own `updatedAt` over the + * file mtime. Returns null rather than a guess: the resolver treats a bad timestamp as + * evidence it must not select on. */ +/** Per-agent resume identity, read through the one mapping that already knows it. Antigravity + * resumes by conversation id and Pi/Prime Agent by transcript path, so a hardcoded `session_id` + * would name a locator those agents cannot resume. */ +function readProviderSession( + session: AiVaultSession, + agent: ResumableTuiAgent +): AgentProviderSessionMetadata | null { + const transcriptPath = typeof session.filePath === 'string' ? session.filePath.trim() : '' + return extractAgentProviderSession(agent, { + session_id: session.sessionId, + sessionId: session.sessionId, + sessionID: session.sessionId, + conversationId: session.sessionId, + ...(transcriptPath ? { transcript_path: transcriptPath, session_file: transcriptPath } : {}) + }) +} + +function readHostTimestamp(session: AiVaultSession): number | null { + for (const raw of [session.updatedAt, session.modifiedAt]) { + if (typeof raw !== 'string' || raw.length === 0) { + continue + } + const parsed = Date.parse(raw) + if (Number.isFinite(parsed) && parsed >= 0) { + return parsed + } + } + return null +} + +/** + * One indexed session -> one candidate, or null when the host's answer cannot support a + * resume. The vault answer crosses a trust boundary (a remote host produced it), so every + * field the resolver will act on is validated here at the entry point rather than deeper in. + */ +export function toAgentResumeCandidate( + session: AiVaultSession, + executionHostId: ExecutionHostId | null +): AgentResumeCandidate | null { + if (!isResumableTuiAgent(session.agent)) { + return null + } + const providerSession = readProviderSession(session, session.agent) + if (!providerSession) { + return null + } + // Refuse rather than offer: a candidate the resume argv builder cannot express would dismiss + // the chooser and resume nothing. + if (!getAgentResumeArgv(session.agent, providerSession)) { + return null + } + const cwd = typeof session.cwd === 'string' ? session.cwd : '' + if (cwd.length === 0) { + return null + } + const updatedAt = readHostTimestamp(session) + if (updatedAt === null) { + return null + } + return { + agent: session.agent, + providerSession, + cwd, + title: typeof session.title === 'string' ? session.title : '', + updatedAt, + messageCount: session.messageCount, + branch: typeof session.branch === 'string' ? session.branch : null, + executionHostId, + executionHostPlatform: session.executionHostPlatform ?? null + } +} + +export function toAgentResumeCandidates( + sessions: readonly AiVaultSession[], + executionHostId: ExecutionHostId | null +): AgentResumeCandidate[] { + const candidates: AgentResumeCandidate[] = [] + for (const session of sessions) { + const candidate = toAgentResumeCandidate(session, executionHostId) + if (candidate) { + candidates.push(candidate) + } + } + return candidates +} + +/** A scan that answered for the whole scope, or one whose answer may be a subset. + * `unverifiable` is never "no candidates": an incomplete scan says nothing about what the host + * holds, so resuming its subset could fork the wrong transcript + * (docs/reference/ssh-execution-boundary.md). */ +export type AgentResumeCandidateScan = + | { kind: 'complete'; candidates: AgentResumeCandidate[] } + | { + kind: 'unverifiable' + reason: 'cancelled' | 'scan-issues' | 'no-contact' | 'scan-truncated' + } + +/** True only for an answer that covered the scope. `cancelled` is an empty body by construction, + * and any non-notice issue means some path or host the scan needed went unread. */ +function scanIncompleteReason( + result: Pick +): 'cancelled' | 'scan-issues' | 'scan-truncated' | null { + if (result.cancelled === true) { + return 'cancelled' + } + const issues = result.issues ?? [] + // A `notice` is not a failure, but a list AT the cap is one the scanner stopped appending to, so + // the rows that did not fit were DROPPED (src/main/ai-vault/session-scan-issues.ts). A stalled + // WSL distro or unreachable remote root records one refusal per discovered path, and filtering + // notices out of that list answers about the handful that survived, not the scan. The list's own + // completeness is what fails here, so the answer is unverifiable rather than empty. + if (issues.length >= AI_VAULT_SCAN_ISSUE_LIMIT) { + return 'scan-issues' + } + if (issues.some((issue) => issue.kind !== 'notice')) { + return 'scan-issues' + } + return truncatedScanReason(result) +} + +/** + * Whether the answer may be a slice, read from the depth the host says it applied. + * + * Counting rows cannot answer this. The request asks for `unlimited`, so a host that honours it + * and holds 1000+ sessions returns the same shape as one that silently capped at 1000 — the old + * check called the first truncated forever, disabling auto-resume on exactly the machines that + * accumulate the most transcripts, and never saw a host capping BELOW the default at all. + * + * A host older than `appliedSessionDepth` sends nothing, and that silence is not proof the request + * was honoured. It fails safe: refusing costs a bare shell, which is the pre-feature behaviour, + * while reading a slice as the whole lets the resolver auto-resume a candidate that is only sole + * because the rest were cut — forking a transcript unrecoverably. + */ +function truncatedScanReason( + result: Pick +): 'scan-truncated' | null { + const depth = result.appliedSessionDepth + if (depth === undefined) { + return 'scan-truncated' + } + if (depth === 'unlimited') { + return null + } + return (result.sessions ?? []).length >= depth ? 'scan-truncated' : null +} + +/** + * Asks the pane's execution host which sessions it holds for this workspace. + * + * Addresses exactly one host — the one that owns the transcripts — because a session id + * names a transcript on the machine that captured it. A failure, a cancellation and a partial + * scan all answer `unverifiable`: the caller then leaves a plain shell, which is the pre-feature + * behaviour, and never a wrong resume. + */ +export async function fetchAgentResumeCandidates(args: { + worktreePath: string + executionHostId: ExecutionHostId | null + listSessions: ( + request: Pick & { + executionHostScope?: ExecutionHostId + } + ) => Promise> +}): Promise { + if (args.worktreePath.length === 0) { + return { kind: 'complete', candidates: [] } + } + try { + const result = await args.listSessions({ + scopePaths: [args.worktreePath], + ...(args.executionHostId ? { executionHostScope: args.executionHostId } : {}), + // Uncapped: the default depth slices a recency-sorted list, and the in-scope bypass that + // survives it covers Claude files only. One worktree's transcripts are a small set. + unlimited: true + }) + const incomplete = scanIncompleteReason(result) + if (incomplete) { + return { kind: 'unverifiable', reason: incomplete } + } + return { + kind: 'complete', + candidates: toAgentResumeCandidates(result.sessions ?? [], args.executionHostId) + } + } catch { + // Loss of contact is not evidence about the sessions; it only means we cannot offer one. + return { kind: 'unverifiable', reason: 'no-contact' } + } +} diff --git a/src/renderer/src/lib/agent-resume-launch-target.test.ts b/src/renderer/src/lib/agent-resume-launch-target.test.ts index c26541331f27..377f2a9ce065 100644 --- a/src/renderer/src/lib/agent-resume-launch-target.test.ts +++ b/src/renderer/src/lib/agent-resume-launch-target.test.ts @@ -89,6 +89,19 @@ describe('resolveAgentResumeLaunchTarget on a Windows client', () => { ).resolves.toEqual({ platform: 'linux', shell: undefined }) }) + it('quotes for the SSH host its own scan row named, not for Linux', async () => { + // SSH is a transport, not a platform. A Windows SSH host quoted for POSIX produces a resume + // argv its own shell rejects, and those hosts are supported. + await expect( + resolveWith({ + connectionId: 'ssh-1', + executionHostId: 'ssh:ssh-1', + hostPlatform: 'win32', + terminalWindowsShell: 'cmd.exe' + }) + ).resolves.toEqual({ platform: 'win32', shell: undefined }) + }) + it('does not describe a remote runtime host with the local Windows shell setting', async () => { await expect( resolveWith({ diff --git a/src/renderer/src/lib/agent-resume-launch-target.ts b/src/renderer/src/lib/agent-resume-launch-target.ts index 90a6a243afb0..f947c3fa072b 100644 --- a/src/renderer/src/lib/agent-resume-launch-target.ts +++ b/src/renderer/src/lib/agent-resume-launch-target.ts @@ -22,6 +22,9 @@ export type AgentResumeLaunchTargetArgs = { terminalWindowsShell: string | null | undefined /** Per-tab Windows shell override, which beats the global setting at spawn time. */ tabShellOverride?: string | null + /** The remote host's own platform when its scan row reported one. Beats the SSH fallback + * below: a Windows SSH host quoted for POSIX produces a resume argv its shell rejects. */ + hostPlatform?: NodeJS.Platform | null } function resolveResumeLaunchPlatform(args: AgentResumeLaunchTargetArgs): NodeJS.Platform { @@ -31,6 +34,10 @@ function resolveResumeLaunchPlatform(args: AgentResumeLaunchTargetArgs): NodeJS. if (args.projectRuntime?.status === 'resolved' && args.projectRuntime.runtime.kind === 'wsl') { return 'linux' } + // The host said what it is; SSH is a transport, not a platform. + if (args.hostPlatform) { + return args.hostPlatform + } if (args.connectionId || (args.worktreePath && isWslUncPath(args.worktreePath))) { return 'linux' } diff --git a/src/renderer/src/lib/agent-resume-pane-decision.test.ts b/src/renderer/src/lib/agent-resume-pane-decision.test.ts new file mode 100644 index 000000000000..2f3b255da9ed --- /dev/null +++ b/src/renderer/src/lib/agent-resume-pane-decision.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, it } from 'vitest' +import type { + AgentResumeCandidate, + AgentResumeResolution +} from '../../../shared/agent-resume-candidate' +import { decideAgentResumeForPane, type AgentResumePaneInputs } from './agent-resume-pane-decision' + +const candidate: AgentResumeCandidate = { + agent: 'claude', + providerSession: { key: 'session_id', id: 'a521d69e-9181-481c-ab8e-998a1881b731' }, + cwd: '/home/ubuntu/Desktop/qbit', + title: 'Round 6', + updatedAt: 1_789_000_000_000, + messageCount: 758, + branch: null, + executionHostId: 'ssh:ssh-1', + executionHostPlatform: null +} + +const resumeResolution: AgentResumeResolution = { + kind: 'resume', + candidate, + reason: 'sole-candidate' +} + +function inputs(overrides: Partial = {}): AgentResumePaneInputs { + return { + paneHasOwnRecord: false, + paneIsVisible: true, + paneHasReceivedInput: false, + resolution: resumeResolution, + ...overrides + } +} + +describe('decideAgentResumeForPane', () => { + it('resumes a visible, untouched pane the resolver decided for', () => { + expect(decideAgentResumeForPane(inputs())).toEqual({ kind: 'resume', candidate }) + }) + + it('offers the choice when the resolver refused to decide', () => { + const resolution: AgentResumeResolution = { kind: 'choose', candidates: [candidate] } + expect(decideAgentResumeForPane(inputs({ resolution }))).toEqual({ + kind: 'choose', + candidates: [candidate] + }) + }) + + // Why: the synchronous cold-restore path already resumes that record. Acting here too + // would put two panes on one transcript, which forks it unrecoverably. + it('stands down when the pane has its own record', () => { + expect(decideAgentResumeForPane(inputs({ paneHasOwnRecord: true }))).toEqual({ + kind: 'none', + reason: 'pane-owns-record' + }) + }) + + // Why: panes mount hidden and in bulk. After a host restart this must not respawn a whole + // workspace at once, nor queue a chooser behind every hidden tab. + it('stands down on a hidden pane', () => { + expect(decideAgentResumeForPane(inputs({ paneIsVisible: false }))).toEqual({ + kind: 'none', + reason: 'pane-hidden' + }) + }) + + // Why: respawning replaces the shell. Once the user has typed, the shell is theirs. + it('stands down once the user has typed into the shell', () => { + expect(decideAgentResumeForPane(inputs({ paneHasReceivedInput: true }))).toEqual({ + kind: 'none', + reason: 'pane-in-use' + }) + }) + + it('stands down when the resolver found nothing', () => { + const resolution: AgentResumeResolution = { kind: 'none', reason: 'no-candidates' } + expect(decideAgentResumeForPane(inputs({ resolution }))).toEqual({ + kind: 'none', + reason: 'resolver-refused' + }) + }) + + it('checks the destructive gates before the resolver verdict', () => { + const decision = decideAgentResumeForPane( + inputs({ paneHasReceivedInput: true, paneIsVisible: false }) + ) + // Hidden is checked first; either refusal is correct, but it must never resume. + expect(decision.kind).toBe('none') + }) +}) diff --git a/src/renderer/src/lib/agent-resume-pane-decision.ts b/src/renderer/src/lib/agent-resume-pane-decision.ts new file mode 100644 index 000000000000..8e4e58c9a344 --- /dev/null +++ b/src/renderer/src/lib/agent-resume-pane-decision.ts @@ -0,0 +1,65 @@ +import type { + AgentResumeCandidate, + AgentResumeResolution +} from '../../../shared/agent-resume-candidate' + +export type AgentResumePaneAction = + /** Respawn this pane with the candidate's resume argv. */ + | { kind: 'resume'; candidate: AgentResumeCandidate } + /** Last rung: offer the choice in the pane. */ + | { kind: 'choose'; candidates: readonly AgentResumeCandidate[] } + | { kind: 'none'; reason: AgentResumePaneRefusal } + +export type AgentResumePaneRefusal = + | 'pane-owns-record' + | 'pane-hidden' + | 'pane-in-use' + | 'resolver-refused' + /** Another pane reserved the same conversation between the host scan and the respawn. */ + | 'session-claimed' + /** The host scan was cancelled, partial, or unreachable, so it answered about nothing. */ + | 'scan-unverifiable' + +export type AgentResumePaneInputs = { + /** The pane's own sleeping record already answered; the synchronous cold-restore path owns it. */ + paneHasOwnRecord: boolean + paneIsVisible: boolean + /** Any byte the user has sent to this pane's shell since it spawned. */ + paneHasReceivedInput: boolean + resolution: AgentResumeResolution +} + +/** + * Whether a pane with no resume handle should be respawned onto a recovered session. + * + * This runs AFTER the pane's plain shell has spawned, not instead of it. Holding every fresh + * spawn behind a host round trip would tax the common case — a plain terminal in a workspace + * that never ran an agent — for a recovery that only some panes need. So the shell appears at + * its normal speed and a recovered session replaces it by respawning, which keeps the rule + * that a resume only ever rides a spawn and is never typed into a live shell. + * + * Replacing a shell is destructive, so three gates guard it, and each one answers 'none': + * - the pane already has its own record, so the synchronous path owns it and a second resume + * here would fork the same transcript into two panes; + * - the pane is hidden, so nothing is respawned in bulk behind the user's back (the concern + * `restoreOnTabOpenOnly` already encodes: one wake must not respawn a whole workspace); + * - the user has already typed into the shell, which makes it theirs. + */ +export function decideAgentResumeForPane(inputs: AgentResumePaneInputs): AgentResumePaneAction { + if (inputs.paneHasOwnRecord) { + return { kind: 'none', reason: 'pane-owns-record' } + } + if (!inputs.paneIsVisible) { + return { kind: 'none', reason: 'pane-hidden' } + } + if (inputs.paneHasReceivedInput) { + return { kind: 'none', reason: 'pane-in-use' } + } + if (inputs.resolution.kind === 'resume') { + return { kind: 'resume', candidate: inputs.resolution.candidate } + } + if (inputs.resolution.kind === 'choose') { + return { kind: 'choose', candidates: inputs.resolution.candidates } + } + return { kind: 'none', reason: 'resolver-refused' } +} diff --git a/src/renderer/src/lib/agent-resume-pane-handlers.ts b/src/renderer/src/lib/agent-resume-pane-handlers.ts new file mode 100644 index 000000000000..97620b8d9c2e --- /dev/null +++ b/src/renderer/src/lib/agent-resume-pane-handlers.ts @@ -0,0 +1,58 @@ +import type { AgentResumeCandidate } from '../../../shared/agent-resume-candidate' + +/** What a pane can do with a chosen session. Registered by the pane's pty connection while it + * is bound, so the chooser can reach the live connection without threading it through React. */ +export type AgentResumePaneHandler = (candidate: AgentResumeCandidate) => boolean + +type RegisteredHandler = { + /** The pty binding that registered this handler; a caller must name the same one. */ + owner: object + handler: AgentResumePaneHandler +} + +const handlersByPaneKey = new Map() + +/** Returns an unregister function; a pane must call it on dispose, or a replaced connection + * would leave a handler pointing at a transport that no longer owns the pane. + * + * The owner is nullable because it reaches here through an index-signature session bag, which let + * a registration that ran before the transport existed type-check and file the handler under + * `undefined` — where no real owner could ever match it. Admitting absence in the type is what + * makes that refusal reachable instead of silent. */ +export function registerAgentResumePaneHandler( + paneKey: string, + owner: object | undefined, + handler: AgentResumePaneHandler +): () => void { + if (!owner) { + console.warn('[agent-resume] refusing a pane handler with no owner:', paneKey) + return () => {} + } + handlersByPaneKey.set(paneKey, { owner, handler }) + return () => { + if (handlersByPaneKey.get(paneKey)?.handler === handler) { + handlersByPaneKey.delete(paneKey) + } + } +} + +/** The handler `owner` registered, or undefined. Naming the owner is what stops a chooser + * published for a retired binding from invoking the successor that replaced it: the pane key is + * the same on both sides of a reconnect, and the binding identity is not. + * + * Identity, not equality: an absent owner must not match an absent registration. */ +export function getAgentResumePaneHandler( + paneKey: string, + owner: object | undefined +): AgentResumePaneHandler | undefined { + const registered = handlersByPaneKey.get(paneKey) + if (!registered || !owner || registered.owner !== owner) { + return undefined + } + return registered.handler +} + +/** Test seam. */ +export function resetAgentResumePaneHandlers(): void { + handlersByPaneKey.clear() +} diff --git a/src/renderer/src/lib/agent-resume-recovery.test.ts b/src/renderer/src/lib/agent-resume-recovery.test.ts new file mode 100644 index 000000000000..d1d512fb4d0a --- /dev/null +++ b/src/renderer/src/lib/agent-resume-recovery.test.ts @@ -0,0 +1,176 @@ +import { describe, expect, it, vi } from 'vitest' +import type { AgentResumeCandidate } from '../../../shared/agent-resume-candidate' +import type { AgentResumeCandidateScan } from './agent-resume-candidate-source' +import { + recoverAgentSessionForPane, + type AgentResumePaneGateState, + type RecoverAgentSessionArgs +} from './agent-resume-recovery' + +function makeCandidate(overrides: Partial = {}): AgentResumeCandidate { + return { + agent: 'claude', + providerSession: { key: 'session_id', id: 'a521d69e-9181-481c-ab8e-998a1881b731' }, + cwd: '/w', + title: 'Round 6', + updatedAt: 1_789_000_000_000, + messageCount: 758, + branch: null, + executionHostId: null, + executionHostPlatform: null, + ...overrides + } +} + +function scan(candidates: AgentResumeCandidate[]): AgentResumeCandidateScan { + return { kind: 'complete', candidates } +} + +const OPEN_GATES: AgentResumePaneGateState = { + paneHasOwnRecord: false, + paneIsVisible: true, + paneHasReceivedInput: false +} + +function makeArgs(overrides: Partial = {}): RecoverAgentSessionArgs { + return { + paneKey: 'tab:leaf', + worktreePath: '/w', + executionHostId: null, + paneAgent: 'claude', + readPaneState: () => OPEN_GATES, + readClaimedSessionIds: () => new Set(), + fetchCandidates: async () => scan([makeCandidate()]), + resume: vi.fn(() => true), + offerChoice: vi.fn(), + ...overrides + } +} + +describe('recoverAgentSessionForPane', () => { + it('resumes a sole substantial candidate', async () => { + const args = makeArgs() + const decision = await recoverAgentSessionForPane(args) + expect(decision.kind).toBe('resume') + expect(args.resume).toHaveBeenCalledOnce() + }) + + it('offers a choice when the resolver refuses to decide', async () => { + const offerChoice = vi.fn() + const args = makeArgs({ + offerChoice, + fetchCandidates: async () => + scan([ + makeCandidate(), + makeCandidate({ + providerSession: { key: 'session_id', id: 'b171319f-6711-4537-89be-00f26ccc7e32' }, + updatedAt: 1_788_000_000_000 + }) + ]) + }) + const decision = await recoverAgentSessionForPane(args) + expect(decision.kind).toBe('choose') + expect(offerChoice).toHaveBeenCalledWith('tab:leaf', expect.any(Array)) + }) + + // Why: asking the host costs seconds of transcript scanning. A pane the gates already + // refuse must not pay for an answer nobody will act on. + it.each([ + ['hidden', { ...OPEN_GATES, paneIsVisible: false }], + ['already in use', { ...OPEN_GATES, paneHasReceivedInput: true }], + ['already holding a record', { ...OPEN_GATES, paneHasOwnRecord: true }] + ])('never asks the host for a pane that is %s', async (_label, state) => { + const fetchCandidates = vi.fn(async () => scan([makeCandidate()])) + const decision = await recoverAgentSessionForPane( + makeArgs({ readPaneState: () => state, fetchCandidates }) + ) + expect(fetchCandidates).not.toHaveBeenCalled() + expect(decision.kind).toBe('none') + }) + + // Why: the scan is long enough for the user to start typing. Replacing a shell someone is + // using is the one outcome this path must never produce. + it('stands down when the user types while the host is answering', async () => { + let typed = false + const resume = vi.fn(() => true) + const decision = await recoverAgentSessionForPane( + makeArgs({ + resume, + readPaneState: () => ({ ...OPEN_GATES, paneHasReceivedInput: typed }), + fetchCandidates: async () => { + typed = true + return scan([makeCandidate()]) + } + }) + ) + expect(decision).toEqual({ kind: 'none', reason: 'pane-in-use' }) + expect(resume).not.toHaveBeenCalled() + }) + + it('stands down when the pane is hidden while the host is answering', async () => { + let visible = true + const decision = await recoverAgentSessionForPane( + makeArgs({ + readPaneState: () => ({ ...OPEN_GATES, paneIsVisible: visible }), + fetchCandidates: async () => { + visible = false + return scan([makeCandidate()]) + } + }) + ) + expect(decision).toEqual({ kind: 'none', reason: 'pane-hidden' }) + }) + + it('does nothing when the host returns no usable candidate', async () => { + const args = makeArgs({ fetchCandidates: async () => scan([]) }) + const decision = await recoverAgentSessionForPane(args) + expect(decision).toEqual({ kind: 'none', reason: 'resolver-refused' }) + expect(args.resume).not.toHaveBeenCalled() + }) + + // EP-STATE: the ~2s scan is exactly the window in which a sibling pane claims the session + // this pane resolved, so the set that decides must be the one read after the await. + it('re-reads the claim set after the host answers', async () => { + const claimed = new Set() + const args = makeArgs({ + readClaimedSessionIds: () => claimed, + fetchCandidates: async () => { + claimed.add('a521d69e-9181-481c-ab8e-998a1881b731') + return scan([makeCandidate()]) + } + }) + const decision = await recoverAgentSessionForPane(args) + expect(decision).toEqual({ kind: 'none', reason: 'resolver-refused' }) + expect(args.resume).not.toHaveBeenCalled() + }) + + // The final claim is the reservation inside `resume`; a refusal means another pane won it. + it('reports a refused reservation instead of resuming', async () => { + const args = makeArgs({ resume: vi.fn(() => false) }) + const decision = await recoverAgentSessionForPane(args) + expect(decision).toEqual({ kind: 'none', reason: 'session-claimed' }) + }) + + it('never offers a session another live pane already holds', async () => { + const args = makeArgs({ + readClaimedSessionIds: () => new Set(['a521d69e-9181-481c-ab8e-998a1881b731']) + }) + const decision = await recoverAgentSessionForPane(args) + expect(decision.kind).toBe('none') + expect(args.resume).not.toHaveBeenCalled() + }) + + // D: an incomplete scan is `unverifiable`, not "no candidates" — its subset could name the + // wrong conversation as the sole survivor (docs/reference/ssh-execution-boundary.md). + it.each([ + ['cancelled', { kind: 'unverifiable', reason: 'cancelled' } as const], + ['partial', { kind: 'unverifiable', reason: 'scan-issues' } as const], + ['unreachable', { kind: 'unverifiable', reason: 'no-contact' } as const] + ])('refuses to resolve on a %s scan', async (_label, result) => { + const args = makeArgs({ fetchCandidates: async () => result }) + const decision = await recoverAgentSessionForPane(args) + expect(decision).toEqual({ kind: 'none', reason: 'scan-unverifiable' }) + expect(args.resume).not.toHaveBeenCalled() + expect(args.offerChoice).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/lib/agent-resume-recovery.ts b/src/renderer/src/lib/agent-resume-recovery.ts new file mode 100644 index 000000000000..814def2505b4 --- /dev/null +++ b/src/renderer/src/lib/agent-resume-recovery.ts @@ -0,0 +1,89 @@ +import type { + AgentResumeCandidate, + AgentResumeResolution +} from '../../../shared/agent-resume-candidate' +import type { ExecutionHostId } from '../../../shared/execution-host' +import type { ResumableTuiAgent } from '../../../shared/agent-session-resume' +import type { AgentResumeCandidateScan } from './agent-resume-candidate-source' +import { resolveAgentResumeCandidate } from './agent-resume-candidate-resolver' +import { decideAgentResumeForPane, type AgentResumePaneAction } from './agent-resume-pane-decision' + +/** The three destructive gates, read live rather than captured — asking the host takes + * seconds, and the pane can be hidden or typed into while the answer is in flight. */ +export type AgentResumePaneGateState = { + paneHasOwnRecord: boolean + paneIsVisible: boolean + paneHasReceivedInput: boolean +} + +export type RecoverAgentSessionArgs = { + paneKey: string + worktreePath: string + executionHostId: ExecutionHostId | null + paneAgent: ResumableTuiAgent | null + /** The provider session the authoritative status store names for THIS pane, if any. */ + readPaneProviderSessionId?: () => string | null + readPaneState: () => AgentResumePaneGateState + /** Read AFTER the host scan, never before: the scan takes ~2s, and a sibling pane can claim + * or reserve a session inside that window. */ + readClaimedSessionIds: () => ReadonlySet + fetchCandidates: (args: { + worktreePath: string + executionHostId: ExecutionHostId | null + }) => Promise + /** Reserves the candidate and respawns; false means another pane reserved it first. */ + resume: (candidate: AgentResumeCandidate) => boolean + offerChoice: (paneKey: string, candidates: readonly AgentResumeCandidate[]) => void +} + +/** Only the gates are being consulted; every gate outranks this placeholder verdict. */ +const GATES_ONLY: AgentResumeResolution = { kind: 'none', reason: 'no-candidates' } + +/** + * Recovers a pane whose resume handle was lost, after its plain shell has spawned. + * + * The gates are checked BEFORE the host is asked, because asking is not free: the answer comes + * from a scan of the host's transcripts, measured at ~2s on a host holding 1200 of them. A hidden + * pane, a pane the user is already typing in, and a pane that still owns its record cost nothing. + * + * They are then checked AGAIN against freshly read state, because that scan is long enough for + * the user to have typed into the shell or switched away — and replacing a shell someone is + * using is the one outcome this whole path must never produce. + */ +export async function recoverAgentSessionForPane( + args: RecoverAgentSessionArgs +): Promise { + const preGate = decideAgentResumeForPane({ ...args.readPaneState(), resolution: GATES_ONLY }) + if (preGate.kind === 'none' && preGate.reason !== 'resolver-refused') { + return preGate + } + + const scan = await args.fetchCandidates({ + worktreePath: args.worktreePath, + executionHostId: args.executionHostId + }) + // An incomplete scan is `unverifiable`, not "no candidates": its subset could name the wrong + // conversation as the sole survivor, and its emptiness is no evidence of absence. The caller + // keeps the attempt unspent so a reachable host can still answer. + if (scan.kind !== 'complete') { + return { kind: 'none', reason: 'scan-unverifiable' } + } + const resolution = resolveAgentResumeCandidate({ + candidates: scan.candidates, + paneAgent: args.paneAgent, + paneProviderSessionId: args.readPaneProviderSessionId?.() ?? null, + worktreePath: args.worktreePath, + claimedSessionIds: args.readClaimedSessionIds() + }) + + const decision = decideAgentResumeForPane({ ...args.readPaneState(), resolution }) + if (decision.kind === 'resume') { + // The claim set above is a read; this is the check-and-reserve that decides it. + if (!args.resume(decision.candidate)) { + return { kind: 'none', reason: 'session-claimed' } + } + } else if (decision.kind === 'choose') { + args.offerChoice(args.paneKey, decision.candidates) + } + return decision +} diff --git a/src/renderer/src/lib/agent-resume-session-claims.test.ts b/src/renderer/src/lib/agent-resume-session-claims.test.ts new file mode 100644 index 000000000000..d5bc2b80d003 --- /dev/null +++ b/src/renderer/src/lib/agent-resume-session-claims.test.ts @@ -0,0 +1,154 @@ +/** + * Both directions of THE PANE-IDENTITY CLAIM RULE, which replaced `entry.state !== 'done'`: + * + * - too BROAD: after a host restart the recovering pane's own persisted row comes back as + * `restoredUnconfirmed` with its provider session, and counting it made the pane filter out the + * one candidate it was trying to recover; + * - too NARROW: `done` means "task complete but pane live", so excluding those rows let a live + * idle sibling's transcript be resumed into a second pane. + */ +import { describe, expect, it } from 'vitest' +import type { AgentStatusEntry } from '../../../shared/agent-status-types' +import { + agentResumeSessionsClaimedByOtherPanes, + resolveAgentResumePaneLiveness, + type AgentResumeClaimState +} from './agent-resume-session-claims' + +const PANE = 'tab-1:1a1c4f4a-3c0f-4a31-9c1e-1d6f1a0b2c30' +const SIBLING = 'tab-2:2b2c4f4a-3c0f-4a31-9c1e-1d6f1a0b2c31' +const PANE_LEAF = '1a1c4f4a-3c0f-4a31-9c1e-1d6f1a0b2c30' +const SIBLING_LEAF = '2b2c4f4a-3c0f-4a31-9c1e-1d6f1a0b2c31' + +function row(id: string, state: AgentStatusEntry['state'], extra: Partial = {}) { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the rule reads only `providerSession` and the pane key; every other AgentStatusEntry field is untouched by it. + return { + state, + providerSession: { key: 'session_id', id }, + ...extra + } as AgentStatusEntry +} + +function stateWith( + agentStatusByPaneKey: Record, + ptyIdsByLeafId: Record>, + sleepingAgentSessionsByPaneKey: AgentResumeClaimState['sleepingAgentSessionsByPaneKey'] = {} +): AgentResumeClaimState { + return { + agentStatusByPaneKey, + sleepingAgentSessionsByPaneKey, + terminalLayoutsByTabId: Object.fromEntries( + Object.entries(ptyIdsByLeafId).map(([tabId, bindings]) => [ + tabId, + { ptyIdsByLeafId: bindings } + ]) + ) + } +} + +describe('pane liveness', () => { + it('reads a bound leaf as live, an unbound leaf of a held tab as unverifiable, a gone tab as exited', () => { + const state = stateWith( + {}, + { 'tab-1': { [PANE_LEAF]: 'pty-1' }, 'tab-2': { [SIBLING_LEAF]: undefined } } + ) + + expect(resolveAgentResumePaneLiveness(state, PANE)).toBe('live') + expect(resolveAgentResumePaneLiveness(state, SIBLING)).toBe('unverifiable') + expect( + resolveAgentResumePaneLiveness(state, 'tab-gone:3c3c4f4a-3c0f-4a31-9c1e-1d6f1a0b2c32') + ).toBe('exited') + }) +}) + +describe('the pane-identity claim rule', () => { + // TOO BROAD, fixed: the restart scenario. The pane's own `working` row is republished as + // `restoredUnconfirmed` and must not claim the session the pane is trying to get back. + it("never treats the recovering pane's own republished row as a claim against it", () => { + const state = stateWith( + { [PANE]: row('session-own', 'working', { restoredUnconfirmed: true }) }, + { 'tab-1': { [PANE_LEAF]: 'pty-1' } } + ) + + expect(agentResumeSessionsClaimedByOtherPanes(state, PANE)).toEqual(new Set()) + }) + + it("does not claim the pane's own row for any state, including done", () => { + for (const state of ['working', 'blocked', 'waiting', 'done'] as const) { + const claims = agentResumeSessionsClaimedByOtherPanes( + stateWith({ [PANE]: row('session-own', state) }, { 'tab-1': { [PANE_LEAF]: 'pty-1' } }), + PANE + ) + expect(claims).toEqual(new Set()) + } + }) + + // TOO NARROW, fixed: `done` is "task complete but pane live", so a live idle sibling still owns + // its transcript. Resuming it here would put two agents on one conversation. + it('claims a done-but-live sibling', () => { + const state = stateWith( + { [SIBLING]: row('session-sibling', 'done') }, + { 'tab-1': { [PANE_LEAF]: 'pty-1' }, 'tab-2': { [SIBLING_LEAF]: 'pty-2' } } + ) + + expect(agentResumeSessionsClaimedByOtherPanes(state, PANE)).toEqual( + new Set(['session-sibling']) + ) + }) + + it('claims a sibling whose liveness is only unverifiable, because contact loss is not death', () => { + const state = stateWith( + { [SIBLING]: row('session-sibling', 'done', { restoredUnconfirmed: true }) }, + { 'tab-1': { [PANE_LEAF]: 'pty-1' }, 'tab-2': {} } + ) + + expect(agentResumeSessionsClaimedByOtherPanes(state, PANE)).toEqual( + new Set(['session-sibling']) + ) + }) + + it('releases a session whose pane this renderer no longer holds', () => { + const state = stateWith( + { [SIBLING]: row('session-sibling', 'working') }, + { 'tab-1': { [PANE_LEAF]: 'pty-1' } } + ) + + expect(agentResumeSessionsClaimedByOtherPanes(state, PANE)).toEqual(new Set()) + }) + + it('ignores a row that carries no provider session', () => { + const state = stateWith( + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a row with no providerSession is the shape the rule must skip; no other field is read. + { [SIBLING]: { state: 'working' } as AgentStatusEntry }, + { 'tab-2': { [SIBLING_LEAF]: 'pty-2' } } + ) + + expect(agentResumeSessionsClaimedByOtherPanes(state, PANE)).toEqual(new Set()) + }) + it('claims a session another pane has queued but not yet spawned', () => { + // A status row appears only after a spawn. Between queueing a cold restore and that spawn the + // session is invisible to a status-only claim set, and resuming it here forks the transcript. + const claimed = agentResumeSessionsClaimedByOtherPanes( + stateWith( + {}, + { 'tab-1': { 'leaf-other': 'pty-1' } }, + { + 'tab-1:leaf-other': { + paneKey: 'tab-1:leaf-other', + tabId: 'tab-1', + worktreeId: 'repo::/w', + connectionId: null, + agent: 'claude', + providerSession: { key: 'session_id', id: 'queued-1' }, + prompt: '', + state: 'done', + capturedAt: 1, + updatedAt: 2 + } + } + ), + 'tab-1:leaf-mine' + ) + expect(claimed.has('queued-1')).toBe(true) + }) +}) diff --git a/src/renderer/src/lib/agent-resume-session-claims.ts b/src/renderer/src/lib/agent-resume-session-claims.ts new file mode 100644 index 000000000000..2e944727c3d2 --- /dev/null +++ b/src/renderer/src/lib/agent-resume-session-claims.ts @@ -0,0 +1,82 @@ +import type { AgentStatusEntry } from '../../../shared/agent-status-types' +import type { SleepingAgentSessionRecord } from '../../../shared/agent-session-resume' +import { parsePaneKey } from '../../../shared/stable-pane-id' + +/** Only the terminal maps the rule reads; a plain shape so the rule is testable without a store. */ +export type AgentResumeClaimState = { + agentStatusByPaneKey: Readonly> + /** A pane's queued resume. It names a session before any status row does, so a status-only + * claim set is blind for the whole window between queueing and spawn. */ + sleepingAgentSessionsByPaneKey: Readonly> + terminalLayoutsByTabId: Readonly< + Record } | undefined> + > +} + +/** The three verdicts docs/reference/ssh-execution-boundary.md allows about a pane, with no + * synonyms: a bound PTY is `live`, a tab this renderer still holds but cannot see a binding for is + * `unverifiable` (mid cold restore, or a host mirror that has not published the handle yet), and + * only a tab the renderer no longer holds at all is `exited`. */ +export type AgentResumePaneLiveness = 'live' | 'unverifiable' | 'exited' + +export function resolveAgentResumePaneLiveness( + state: AgentResumeClaimState, + paneKey: string +): AgentResumePaneLiveness { + const pane = parsePaneKey(paneKey) + if (!pane) { + return 'unverifiable' + } + const layout = state.terminalLayoutsByTabId[pane.tabId] + if (!layout) { + return 'exited' + } + return layout.ptyIdsByLeafId?.[pane.leafId] ? 'live' : 'unverifiable' +} + +/** + * THE PANE-IDENTITY CLAIM RULE: which provider sessions a recovering pane must not resume. + * + * Liveness is never derived from `state`, in either direction: + * - `state !== 'done'` is too BROAD. After a host restart the hook server republishes the + * recovering pane's own persisted row as `restoredUnconfirmed`, provider session included + * (main/agent-hooks/server/server-hydration.ts). Counting it made the pane treat ITS OWN + * session as claimed, so the sole candidate was filtered out and a restart during + * `working`/`blocked`/`waiting` left a plain shell — the feature's primary scenario. + * - `state !== 'done'` is also too NARROW. `done` means "task complete but pane live" + * (agent-status.ts), not exited, so excluding every `done` row let a live idle pane's + * transcript be resumed into a second pane: two agents on one transcript. + * + * So ownership comes from pane identity and liveness from the pane's own terminal binding: + * - a row whose pane key IS the recovering pane's is never a claim against it, whatever its state; + * - any other pane's row is a claim whenever that pane is `live` or `unverifiable`, whatever its + * state — loss of contact is not death, and a wrong resume forks a transcript unrecoverably; + * - only a pane this renderer positively no longer holds releases its session. + */ +export function agentResumeSessionsClaimedByOtherPanes( + state: AgentResumeClaimState, + paneKey: string +): Set { + const claimed = new Set() + for (const [rowPaneKey, entry] of Object.entries(state.agentStatusByPaneKey)) { + if (!entry?.providerSession || rowPaneKey === paneKey) { + continue + } + if (resolveAgentResumePaneLiveness(state, rowPaneKey) !== 'exited') { + claimed.add(entry.providerSession.id) + } + } + // A status row appears only after a spawn, so another pane that has QUEUED this session — its + // own sleeping record, awaiting a cold restore — is invisible above for the whole window in + // which resuming it here would fork the transcript. Same identity and liveness rule. + // Absent before the store hydrates; no queued records is not the same as an error. + for (const [rowPaneKey, record] of Object.entries(state.sleepingAgentSessionsByPaneKey ?? {})) { + if (!record?.providerSession || rowPaneKey === paneKey) { + continue + } + if (resolveAgentResumePaneLiveness(state, rowPaneKey) !== 'exited') { + claimed.add(record.providerSession.id) + } + } + return claimed +} diff --git a/src/renderer/src/lib/agent-resume-session-reservations.ts b/src/renderer/src/lib/agent-resume-session-reservations.ts new file mode 100644 index 000000000000..3d40c43c6679 --- /dev/null +++ b/src/renderer/src/lib/agent-resume-session-reservations.ts @@ -0,0 +1,51 @@ +/** + * Which pane has committed to respawning onto which conversation, in this renderer. + * + * Why a reservation and not the live claim set: a pane's claim only appears once its resumed + * agent reports a status, seconds after the spawn. Two panes revealed together both finish + * their host scan inside that window, so the claim set says "unclaimed" to both and they fork + * one transcript. Reserving is synchronous, so exactly one of them can win. + * + * Renderer-scoped by design: it guards the panes this client is about to spawn. A session + * already live somewhere else is excluded by the claim set the resolver reads. + */ +const paneKeyBySessionId = new Map() + +/** Check-and-reserve in one synchronous step; false means another pane got there first. */ +export function reserveAgentResumeSession(sessionId: string, paneKey: string): boolean { + const holder = paneKeyBySessionId.get(sessionId) + if (holder !== undefined && holder !== paneKey) { + return false + } + paneKeyBySessionId.set(sessionId, paneKey) + return true +} + +/** Session ids reserved by some other pane, which this pane must not be offered. */ +export function agentResumeSessionsReservedElsewhere(paneKey: string): Set { + const reserved = new Set() + for (const [sessionId, holder] of paneKeyBySessionId) { + if (holder !== paneKey) { + reserved.add(sessionId) + } + } + return reserved +} + +/** Released on dispose: the pane that held the reservation no longer exists. */ +export function releaseAgentResumeSessionsForPane(paneKey: string): void { + const stale: string[] = [] + for (const [sessionId, holder] of paneKeyBySessionId) { + if (holder === paneKey) { + stale.push(sessionId) + } + } + for (const sessionId of stale) { + paneKeyBySessionId.delete(sessionId) + } +} + +/** Test seam. */ +export function resetAgentResumeSessionReservations(): void { + paneKeyBySessionId.clear() +} diff --git a/src/renderer/src/lib/agent-resume-workspace-scope.ts b/src/renderer/src/lib/agent-resume-workspace-scope.ts new file mode 100644 index 000000000000..399cbf417258 --- /dev/null +++ b/src/renderer/src/lib/agent-resume-workspace-scope.ts @@ -0,0 +1,21 @@ +/** + * The directory a pane's agent sessions would have run in. + * + * Read from EITHER workspace representation: a folder workspace is not a git worktree and keeps + * its root on `folderWorkspace.folderPath`, so gating recovery on `worktree.path` alone made + * every agent pane in a folder workspace permanently unrecoverable (AGENTS.md requires folder + * workspaces be considered alongside worktrees). Null when neither names a path — the scan has + * no scope to ask about, and guessing one would scope the resume to the wrong directory. + */ +export function paneAgentResumeScopePath(source: { + worktreePath?: string | null + folderWorkspacePath?: string | null +}): string | null { + for (const raw of [source.worktreePath, source.folderWorkspacePath]) { + const path = typeof raw === 'string' ? raw.trim() : '' + if (path.length > 0) { + return path + } + } + return null +} diff --git a/src/renderer/src/lib/pane-agent-evidence.test.ts b/src/renderer/src/lib/pane-agent-evidence.test.ts index 0bd618e29406..3efe1f406065 100644 --- a/src/renderer/src/lib/pane-agent-evidence.test.ts +++ b/src/renderer/src/lib/pane-agent-evidence.test.ts @@ -8,6 +8,7 @@ import { isExplicitAgentStatusFresh, resolveCommittedTitleAgentType, resolvePaneAgentActivity, + resolvePaneScopedLaunchTuiAgent, resolveTitleActivityLabel } from './pane-agent-evidence' @@ -145,3 +146,31 @@ describe('resolvePaneAgentActivity', () => { expect(decision.source).toBe('hook') }) }) + +describe('resolvePaneScopedLaunchTuiAgent', () => { + it("has no tab-wide source at all, so a sibling pane's identity cannot leak in", () => { + expect(resolvePaneScopedLaunchTuiAgent({})).toBeNull() + }) + + it("accepts this pane's own hook status row", () => { + expect(resolvePaneScopedLaunchTuiAgent({ statusEntryAgent: 'claude' })).toBe('claude') + }) + + it('prefers the pane startup over weaker pane-scoped readings', () => { + expect( + resolvePaneScopedLaunchTuiAgent({ + paneStartupLaunchAgent: 'codex', + statusEntryAgent: 'claude' + }) + ).toBe('codex') + }) + + it('skips a reading that names no known TUI agent', () => { + expect( + resolvePaneScopedLaunchTuiAgent({ + paneStartupLaunchAgent: 'bash', + statusEntryAgent: 'claude' + }) + ).toBe('claude') + }) +}) diff --git a/src/renderer/src/lib/pane-agent-evidence.ts b/src/renderer/src/lib/pane-agent-evidence.ts index 67dbbf85c6f6..6d605bb1e2b0 100644 --- a/src/renderer/src/lib/pane-agent-evidence.ts +++ b/src/renderer/src/lib/pane-agent-evidence.ts @@ -2,6 +2,7 @@ import type { AgentStatus } from '../../../shared/agent-detection' import { detectAgentStatusFromTitle, getAgentLabel } from '../../../shared/agent-detection' import { resolveExplicitTerminalTitleAgentType } from '../../../shared/terminal-title-agent-type' import type { TuiAgent } from '../../../shared/tui-agent' +import { isTuiAgent } from '../../../shared/tui-agent-config' import { AGENT_STATUS_STALE_AFTER_MS, agentStatusEvidenceObservedAt, @@ -127,3 +128,35 @@ export function resolvePaneAgentActivity( livePtyRequired: false } } + +/** Evidence that THIS PANE hosted an agent, every field read under the pane's own key, strongest + * first. A tab-wide value is deliberately absent: `tab.launchAgent` names the tab's ORIGINAL pty + * (terminal-pane-close-identity.ts), so a plain-shell split in an agent-launched tab would + * inherit it — and a destructive decision, such as replacing a live shell with a recovered + * conversation, may not rest on another pane's identity. */ +export type PaneScopedAgentEvidence = { + /** The launch agent this pane's own startup carried. */ + paneStartupLaunchAgent?: string | null + /** The initial agent status this pane's own startup carried. */ + paneStartupStatusAgent?: string | null + /** The launch config registered under this pane key. */ + registeredLaunchAgent?: string | null + /** This pane's own hook status row. */ + statusEntryAgent?: string | null + /** This pane's own command/foreground inference. */ + foregroundAgent?: string | null +} + +/** Null means no pane-scoped evidence — never "an ordinary shell". */ +export function resolvePaneScopedLaunchTuiAgent( + evidence: PaneScopedAgentEvidence +): TuiAgent | null { + const candidates = [ + evidence.paneStartupLaunchAgent, + evidence.paneStartupStatusAgent, + evidence.registeredLaunchAgent, + evidence.statusEntryAgent, + evidence.foregroundAgent + ] + return candidates.find((candidate) => isTuiAgent(candidate)) ?? null +} diff --git a/src/renderer/src/lib/pending-agent-resume-choices.test.ts b/src/renderer/src/lib/pending-agent-resume-choices.test.ts new file mode 100644 index 000000000000..c770bb4b2495 --- /dev/null +++ b/src/renderer/src/lib/pending-agent-resume-choices.test.ts @@ -0,0 +1,95 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { AgentResumeCandidate } from '../../../shared/agent-resume-candidate' +import { + clearPendingAgentResumeChoices, + clearPendingAgentResumeChoicesForOwner, + getPendingAgentResumeChoices, + resetPendingAgentResumeChoices, + setPendingAgentResumeChoices, + subscribePendingAgentResumeChoices +} from './pending-agent-resume-choices' + +const candidate: AgentResumeCandidate = { + agent: 'claude', + providerSession: { key: 'session_id', id: 'a521d69e-9181-481c-ab8e-998a1881b731' }, + cwd: '/home/ubuntu/Desktop/qbit', + title: 'Round 6', + updatedAt: 1_789_000_000_000, + messageCount: 758, + branch: null, + executionHostId: null, + executionHostPlatform: null +} + +/** Stands in for a pty binding's transport: the choice's owner is an opaque identity. */ +const OWNER = {} + +afterEach(() => { + resetPendingAgentResumeChoices() +}) + +describe('pending agent resume choices', () => { + it('holds candidates per pane and notifies that pane only', () => { + const paneA = vi.fn() + const paneB = vi.fn() + subscribePendingAgentResumeChoices('pane-a', paneA) + subscribePendingAgentResumeChoices('pane-b', paneB) + + setPendingAgentResumeChoices('pane-a', OWNER, [candidate]) + + expect(getPendingAgentResumeChoices('pane-a')).toEqual({ + owner: OWNER, + candidates: [candidate] + }) + expect(getPendingAgentResumeChoices('pane-b')).toBeUndefined() + expect(paneA).toHaveBeenCalledTimes(1) + expect(paneB).not.toHaveBeenCalled() + }) + + // Why: useSyncExternalStore re-renders on every notify and compares by identity, so an + // unchanged read must keep the same reference. + it('keeps a stable reference while unchanged', () => { + setPendingAgentResumeChoices('pane-a', OWNER, [candidate]) + expect(getPendingAgentResumeChoices('pane-a')).toBe(getPendingAgentResumeChoices('pane-a')) + }) + + it('treats an empty candidate list as nothing pending', () => { + const listener = vi.fn() + subscribePendingAgentResumeChoices('pane-a', listener) + setPendingAgentResumeChoices('pane-a', OWNER, [candidate]) + listener.mockClear() + + setPendingAgentResumeChoices('pane-a', OWNER, []) + + expect(getPendingAgentResumeChoices('pane-a')).toBeUndefined() + expect(listener).toHaveBeenCalledTimes(1) + }) + + it('does not notify when clearing a pane that had nothing pending', () => { + const listener = vi.fn() + subscribePendingAgentResumeChoices('pane-a', listener) + clearPendingAgentResumeChoices('pane-a') + expect(listener).not.toHaveBeenCalled() + }) + + // Finding: a published choice carried no binding identity, so a chooser left over from a + // retired connection could act on the successor that replaced it under the same pane key. + it('retires only the owner it was published for', () => { + const successor = {} + setPendingAgentResumeChoices('pane-a', successor, [candidate]) + + clearPendingAgentResumeChoicesForOwner('pane-a', OWNER) + expect(getPendingAgentResumeChoices('pane-a')?.owner).toBe(successor) + + clearPendingAgentResumeChoicesForOwner('pane-a', successor) + expect(getPendingAgentResumeChoices('pane-a')).toBeUndefined() + }) + + it('stops notifying after unsubscribe', () => { + const listener = vi.fn() + const unsubscribe = subscribePendingAgentResumeChoices('pane-a', listener) + unsubscribe() + setPendingAgentResumeChoices('pane-a', OWNER, [candidate]) + expect(listener).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/lib/pending-agent-resume-choices.ts b/src/renderer/src/lib/pending-agent-resume-choices.ts new file mode 100644 index 000000000000..6fd08283795e --- /dev/null +++ b/src/renderer/src/lib/pending-agent-resume-choices.ts @@ -0,0 +1,88 @@ +import type { AgentResumeCandidate } from '../../../shared/agent-resume-candidate' + +/** + * Panes whose resolver refused to decide and are showing the chooser. + * + * Deliberately not a store slice: this is transient per-pane UI state that never persists + * and never crosses a host boundary, and keeping it out of the persisted session state means + * a pending choice can never be written to disk and revived against a stale session list. + * + * Every choice carries the identity of the pty binding that scanned it. The pane key is stable + * across a reconnect, so without that identity a chooser published for a retired connection + * stayed on screen and reached the SUCCESSOR's handler — replacing a live shell with a session + * scanned for a connection that no longer owns the pane. + */ +export type PendingAgentResumeChoice = { + /** The pty binding these candidates were scanned for; nothing else may act on them. */ + owner: object + candidates: readonly AgentResumeCandidate[] +} + +const choiceByPaneKey = new Map() +const listenersByPaneKey = new Map void>>() + +function notify(paneKey: string): void { + for (const listener of listenersByPaneKey.get(paneKey) ?? []) { + listener() + } +} + +export function setPendingAgentResumeChoices( + paneKey: string, + owner: object, + candidates: readonly AgentResumeCandidate[] +): void { + if (candidates.length === 0) { + clearPendingAgentResumeChoices(paneKey) + return + } + choiceByPaneKey.set(paneKey, { owner, candidates }) + notify(paneKey) +} + +export function clearPendingAgentResumeChoices(paneKey: string): void { + if (!choiceByPaneKey.delete(paneKey)) { + return + } + notify(paneKey) +} + +/** Dispose path: retire this binding's own choice and leave a successor's alone. */ +export function clearPendingAgentResumeChoicesForOwner(paneKey: string, owner: object): void { + if (choiceByPaneKey.get(paneKey)?.owner !== owner) { + return + } + clearPendingAgentResumeChoices(paneKey) +} + +/** Stable identity while unchanged, so `useSyncExternalStore` does not loop. */ +export function getPendingAgentResumeChoices( + paneKey: string +): PendingAgentResumeChoice | undefined { + return choiceByPaneKey.get(paneKey) +} + +export function subscribePendingAgentResumeChoices( + paneKey: string, + listener: () => void +): () => void { + const listeners = listenersByPaneKey.get(paneKey) ?? new Set<() => void>() + listeners.add(listener) + listenersByPaneKey.set(paneKey, listeners) + return () => { + const current = listenersByPaneKey.get(paneKey) + if (!current) { + return + } + current.delete(listener) + if (current.size === 0) { + listenersByPaneKey.delete(paneKey) + } + } +} + +/** Test seam; production code clears per pane as choices are consumed or panes unmount. */ +export function resetPendingAgentResumeChoices(): void { + choiceByPaneKey.clear() + listenersByPaneKey.clear() +} diff --git a/src/renderer/src/lib/use-pending-agent-resume-choices.ts b/src/renderer/src/lib/use-pending-agent-resume-choices.ts new file mode 100644 index 000000000000..0679e28b84fe --- /dev/null +++ b/src/renderer/src/lib/use-pending-agent-resume-choices.ts @@ -0,0 +1,21 @@ +import { useCallback, useSyncExternalStore } from 'react' +import { + getPendingAgentResumeChoices, + subscribePendingAgentResumeChoices, + type PendingAgentResumeChoice +} from './pending-agent-resume-choices' + +/** The choice pending for one pane — its candidates and the binding that scanned them — or + * undefined when it has none. */ +export function usePendingAgentResumeChoices( + paneKey: string +): PendingAgentResumeChoice | undefined { + const subscribe = useCallback( + (listener: () => void) => subscribePendingAgentResumeChoices(paneKey, listener), + [paneKey] + ) + const read = useCallback(() => getPendingAgentResumeChoices(paneKey), [paneKey]) + // Why getServerSnapshot === read: the store holds no pending choice during SSR/test hydration, + // and both reads answer undefined, so one function is correct for both. + return useSyncExternalStore(subscribe, read, read) +} diff --git a/src/shared/agent-resume-candidate.ts b/src/shared/agent-resume-candidate.ts new file mode 100644 index 000000000000..1a68aeaa6a1a --- /dev/null +++ b/src/shared/agent-resume-candidate.ts @@ -0,0 +1,51 @@ +import type { ExecutionHostId } from './execution-host' +import type { AgentProviderSessionMetadata, ResumableTuiAgent } from './agent-session-resume' + +/** One resumable conversation an execution host holds for a workspace, normalized from + * whichever source named it: the pane's own sleeping record, or that host's session index. */ +export type AgentResumeCandidate = { + agent: ResumableTuiAgent + providerSession: AgentProviderSessionMetadata + /** Host-reported directory the session ran in; the scope the candidate was matched on. */ + cwd: string + title: string + /** Last activity, epoch ms on the HOST's clock — never comparable to a client timestamp. */ + updatedAt: number + messageCount: number + branch: string | null + /** Stamped by the desktop from the host it addressed, never trusted from the answer. */ + executionHostId: ExecutionHostId | null + /** The host's own platform, as its scan row reported it. Null when it did not say — an SSH + * connection is not evidence of Linux, and resume commands are quoted per platform. */ + executionHostPlatform: NodeJS.Platform | null +} + +/** Which rung answered. Diagnostics and tests read this; it is never shown to the user. */ +export type AgentResumeResolutionReason = + | 'pane-record' + | 'sole-candidate' + | 'no-candidates' + | 'every-candidate-claimed' + | 'ambiguous' + +export type AgentResumeResolution = + | { + kind: 'resume' + candidate: AgentResumeCandidate + reason: Extract + } + /** Last rung: several candidates survived every filter and no evidence separates them. */ + | { kind: 'choose'; candidates: readonly AgentResumeCandidate[] } + | { + kind: 'none' + reason: Extract< + AgentResumeResolutionReason, + 'no-candidates' | 'every-candidate-claimed' | 'ambiguous' + > + } + +/** Below this, a transcript is a probe or an aborted start rather than work worth resuming. + * Resuming the wrong session forks it unrecoverably, so a thin transcript that merely sorts + * newest must never outrank a substantial one (a 39-line diagnostic beat a 758-line session + * in the field before this floor existed). */ +export const AGENT_RESUME_SUBSTANCE_FLOOR_MESSAGES = 50 diff --git a/src/shared/ai-vault-session-depth.ts b/src/shared/ai-vault-session-depth.ts index 8499d4c0dc64..bfe456612380 100644 --- a/src/shared/ai-vault-session-depth.ts +++ b/src/shared/ai-vault-session-depth.ts @@ -2,11 +2,11 @@ import { createNormalizedPathInsideOrEqualMatcher, normalizeRuntimePathForComparison } from './cross-platform-path' -import type { AiVaultListArgs, AiVaultListResult } from './ai-vault-types' +import type { AiVaultListArgs, AiVaultListResult, AiVaultSessionDepth } from './ai-vault-types' export const DEFAULT_AI_VAULT_SCAN_LIMIT = 1000 -export type AiVaultSessionDepth = number | 'unlimited' +export type { AiVaultSessionDepth } export function requestedAiVaultSessionDepth( args?: Pick @@ -56,5 +56,10 @@ export function truncateAiVaultListResult( } } } - return { ...result, sessions: result.sessions.filter((session) => selectedIds.has(session.id)) } + // The narrowing bound is now the one this answer was actually cut to. + return { + ...result, + sessions: result.sessions.filter((session) => selectedIds.has(session.id)), + appliedSessionDepth: depth + } } diff --git a/src/shared/ai-vault-types.ts b/src/shared/ai-vault-types.ts index b2635555bf67..b167f19c496e 100644 --- a/src/shared/ai-vault-types.ts +++ b/src/shared/ai-vault-types.ts @@ -196,10 +196,22 @@ export function isAiVaultSessionRecoverableEmpty( ) } +/** How many scan issues one scan reports before the rest are dropped. A list AT this length is an + * overflowed list: `recordSessionScanIssue` collapses everything past it into a single notice, so + * the rows that did not fit are gone and the list no longer describes the whole scan. Shared + * because a reader deciding whether an answer covered its scope has to know the bound. */ +export const AI_VAULT_SCAN_ISSUE_LIMIT = 500 + +/** A bound on how many sessions a scan returns, or `'unlimited'` for none. Defined here beside the + * result that reports it; `ai-vault-session-depth.ts` owns the normalization. */ +export type AiVaultSessionDepth = number | 'unlimited' + export type AiVaultScanIssue = { executionHostId?: ExecutionHostId agent: AiVaultAgent - // 'notice' rows are scanner commentary (issue-list overflow), never a failure. + // 'notice' is not a failure, but it is not a clean bill of health either: it marks both a + // per-transcript remark and the overflow row that says issues were DROPPED. Read + // `issues.length >= AI_VAULT_SCAN_ISSUE_LIMIT` for the second, never the kind alone. kind?: 'host' | 'scope' | 'notice' path: string message: string @@ -222,6 +234,17 @@ export type AiVaultListResult = { scannedAt: string /** Set only by the desktop IPC boundary: this scan was superseded, so its empty body means "nothing to apply". */ cancelled?: true + /** + * The session depth the answering scan actually applied: `'unlimited'` for an uncapped answer, a + * number for one bounded at that many rows. + * + * Optional because hosts update independently of clients, and a host that predates this field + * sends nothing. Absent therefore means "this answer's coverage cannot be proved" — never + * "complete". Counting the returned sessions cannot stand in for it: a host that honours + * `unlimited` and holds 1000+ sessions looks identical to one that silently capped at 1000, and + * a host capping BELOW that is invisible either way. + */ + appliedSessionDepth?: AiVaultSessionDepth } export function aiVaultAgentLabel(agent: AiVaultAgent): string {