diff --git a/src/cli/format.test.ts b/src/cli/format.test.ts new file mode 100644 index 000000000..6bed14237 --- /dev/null +++ b/src/cli/format.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it } from 'vitest' +import { RuntimeRpcFailureError } from './runtime-client' +import { formatCliError, formatWorktreeList } from './format' +import type { RuntimeWorktreeRecord } from '../shared/runtime-types' + +function worktree(overrides: Partial = {}): RuntimeWorktreeRecord { + const base: RuntimeWorktreeRecord = { + id: 'repo::/tmp/repo/child', + repoId: 'repo', + path: '/tmp/repo/child', + head: 'abc123', + branch: 'feature/child', + isBare: false, + isMainWorktree: false, + parentWorktreeId: null, + childWorktreeIds: [], + lineage: null, + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + git: { + path: '/tmp/repo/child', + head: 'abc123', + branch: 'feature/child', + isBare: false, + isMainWorktree: false + }, + displayName: '', + comment: '' + } + return { ...base, ...overrides } +} + +describe('formatCliError', () => { + it('prints runtime next steps for structured lineage errors', () => { + const error = new RuntimeRpcFailureError({ + id: 'req_1', + ok: false, + error: { + code: 'LINEAGE_PARENT_NOT_FOUND', + message: 'Parent workspace was not found.', + data: { + nextSteps: [ + 'Run `orca worktree list` and pass a valid --parent-worktree selector.', + 'Retry with --no-parent to create without lineage.', + 123 + ] + } + }, + _meta: { runtimeId: 'runtime-1' } + }) + + expect(formatCliError(error)).toBe( + [ + 'Parent workspace was not found.', + 'Next step: Run `orca worktree list` and pass a valid --parent-worktree selector.', + 'Next step: Retry with --no-parent to create without lineage.' + ].join('\n') + ) + }) +}) + +describe('formatWorktreeList', () => { + it('includes parent and child workspace relationships in text output', () => { + const output = formatWorktreeList({ + worktrees: [ + worktree({ + id: 'repo::/tmp/repo/parent', + path: '/tmp/repo/parent', + branch: 'feature/parent', + childWorktreeIds: ['repo::/tmp/repo/child'] + }), + worktree({ + parentWorktreeId: 'repo::/tmp/repo/parent' + }) + ], + totalCount: 2, + truncated: false + }) + + expect(output).toContain('parentWorktreeId: null') + expect(output).toContain('childWorktreeIds: repo::/tmp/repo/child') + expect(output).toContain('parentWorktreeId: repo::/tmp/repo/parent') + expect(output).toContain('childWorktreeIds: []') + }) +}) diff --git a/src/cli/format.ts b/src/cli/format.ts index f032bb180..9518dfde6 100644 --- a/src/cli/format.ts +++ b/src/cli/format.ts @@ -60,6 +60,18 @@ export function formatCliError(error: unknown): string { ) { return `${message}\nOrca is not running. Run 'orca open' first.` } + if (error instanceof RuntimeRpcFailureError) { + const data = error.response.error.data + const nextSteps = + data && typeof data === 'object' && Array.isArray((data as { nextSteps?: unknown }).nextSteps) + ? (data as { nextSteps: unknown[] }).nextSteps.filter( + (step): step is string => typeof step === 'string' + ) + : [] + if (nextSteps.length > 0) { + return `${message}\n${nextSteps.map((step) => `Next step: ${step}`).join('\n')}` + } + } return message } @@ -250,10 +262,10 @@ export function formatWorktreeList(result: RuntimeWorktreeListResult): string { return 'No worktrees found.' } const body = result.worktrees - .map( - (worktree) => - `${String(worktree.id)} ${String(worktree.branch)} ${String(worktree.path)}\ndisplayName: ${String(worktree.displayName ?? '')}\nlinkedIssue: ${String(worktree.linkedIssue ?? 'null')}\ncomment: ${String(worktree.comment ?? '')}` - ) + .map((worktree) => { + const childCount = worktree.childWorktreeIds?.length ?? 0 + return `${String(worktree.id)} ${String(worktree.branch)} ${String(worktree.path)}\ndisplayName: ${String(worktree.displayName ?? '')}\nparentWorktreeId: ${String(worktree.parentWorktreeId ?? 'null')}\nchildWorktreeIds: ${childCount > 0 ? worktree.childWorktreeIds.join(',') : '[]'}\nlinkedIssue: ${String(worktree.linkedIssue ?? 'null')}\ncomment: ${String(worktree.comment ?? '')}` + }) .join('\n\n') return result.truncated ? `${body}\n\ntruncated: showing ${result.worktrees.length} of ${result.totalCount}` diff --git a/src/cli/handlers/orchestration.ts b/src/cli/handlers/orchestration.ts index 4520d3388..5398c55aa 100644 --- a/src/cli/handlers/orchestration.ts +++ b/src/cli/handlers/orchestration.ts @@ -207,12 +207,18 @@ export const ORCHESTRATION_HANDLERS: Record = { }, 'orchestration task-create': async ({ flags, client, json }) => { + const callerTerminalHandle = + typeof process.env.ORCA_TERMINAL_HANDLE === 'string' && + process.env.ORCA_TERMINAL_HANDLE.length > 0 + ? process.env.ORCA_TERMINAL_HANDLE + : undefined const result = await client.call<{ task: { id: string; status: string } }>( 'orchestration.taskCreate', { spec: getRequiredStringFlag(flags, 'spec'), deps: getOptionalStringFlag(flags, 'deps'), - parent: getOptionalStringFlag(flags, 'parent') + parent: getOptionalStringFlag(flags, 'parent'), + callerTerminalHandle } ) printResult(result, json, (r) => `Created ${r.task.id} [${r.task.status}]`) diff --git a/src/cli/handlers/worktree.ts b/src/cli/handlers/worktree.ts index 5dfe9873d..b4065387b 100644 --- a/src/cli/handlers/worktree.ts +++ b/src/cli/handlers/worktree.ts @@ -1,10 +1,12 @@ import type { RuntimeWorktreeListResult, RuntimeWorktreePsResult, - RuntimeWorktreeRecord + RuntimeWorktreeRecord, + RuntimeWorktreeCreateResult } from '../../shared/runtime-types' import type { CommandHandler } from '../dispatch' import { formatWorktreeList, formatWorktreePs, formatWorktreeShow, printResult } from '../format' +import { RuntimeClientError } from '../runtime-client' import { getOptionalNullableNumberFlag, getOptionalNumberFlag, @@ -12,7 +14,11 @@ import { getOptionalStringFlag, getRequiredStringFlag } from '../flags' -import { getRequiredWorktreeSelector, resolveCurrentWorktreeSelector } from '../selectors' +import { + getOptionalWorktreeSelector, + getRequiredWorktreeSelector, + resolveCurrentWorktreeSelector +} from '../selectors' type HookWarningResult = { warning?: string @@ -24,6 +30,48 @@ function printHookWarning(result: HookWarningResult, json: boolean): void { } } +function printLineageSummary(result: RuntimeWorktreeCreateResult, json: boolean): void { + if (json) { + return + } + for (const warning of result.warnings ?? []) { + console.error(`warning: ${warning.message}`) + } + if (result.lineage) { + const source = + result.lineage.capture.source === 'terminal-context' + ? 'terminal' + : result.lineage.capture.source === 'cwd-context' + ? 'cwd' + : result.lineage.capture.source === 'orchestration-context' + ? 'orchestration' + : result.lineage.capture.source === 'explicit-cli-flag' + ? 'explicit flag' + : 'manual action' + console.error( + `parent: ${result.lineage.parentWorktreeId} (${result.lineage.capture.confidence} from ${source})` + ) + } else { + console.error('parent: none') + } +} + +function assertParentFlagsCompatible(flags: Map): void { + if (flags.has('parent-worktree') && flags.get('no-parent') === true) { + throw new RuntimeClientError( + 'invalid_argument', + 'Choose either --parent-worktree or --no-parent, not both.' + ) + } + const parentWorktree = flags.get('parent-worktree') + if ( + flags.has('parent-worktree') && + (typeof parentWorktree !== 'string' || parentWorktree === '') + ) { + throw new RuntimeClientError('invalid_argument', 'Missing required --parent-worktree') + } +} + export const WORKTREE_HANDLERS: Record = { 'worktree ps': async ({ flags, client, json }) => { const result = await client.call('worktree.ps', { @@ -50,28 +98,56 @@ export const WORKTREE_HANDLERS: Record = { }) printResult(result, json, formatWorktreeShow) }, - 'worktree create': async ({ flags, client, json }) => { - const result = await client.call<{ worktree: RuntimeWorktreeRecord; warning?: string }>( - 'worktree.create', - { - repo: getRequiredStringFlag(flags, 'repo'), - name: getRequiredStringFlag(flags, 'name'), - baseBranch: getOptionalStringFlag(flags, 'base-branch'), - linkedIssue: getOptionalNumberFlag(flags, 'issue'), - comment: getOptionalStringFlag(flags, 'comment'), - runHooks: flags.get('run-hooks') === true, - activate: flags.get('activate') === true || flags.get('run-hooks') === true - } + 'worktree create': async ({ flags, client, cwd, json }) => { + assertParentFlagsCompatible(flags) + const callerTerminalHandle = + typeof process.env.ORCA_TERMINAL_HANDLE === 'string' && + process.env.ORCA_TERMINAL_HANDLE.length > 0 + ? process.env.ORCA_TERMINAL_HANDLE + : undefined + const explicitParentWorktree = await getOptionalWorktreeSelector( + flags, + 'parent-worktree', + cwd, + client ) + const noParent = flags.get('no-parent') === true + let cwdParentWorktree: string | undefined + if (!explicitParentWorktree && !noParent) { + try { + // Why: agent shells can lose ORCA_TERMINAL_HANDLE while still running + // inside an Orca worktree. Cwd keeps CLI-created children nestable. + cwdParentWorktree = await resolveCurrentWorktreeSelector(cwd, client) + } catch { + cwdParentWorktree = undefined + } + } + const result = await client.call('worktree.create', { + repo: getRequiredStringFlag(flags, 'repo'), + name: getRequiredStringFlag(flags, 'name'), + baseBranch: getOptionalStringFlag(flags, 'base-branch'), + linkedIssue: getOptionalNumberFlag(flags, 'issue'), + comment: getOptionalStringFlag(flags, 'comment'), + runHooks: flags.get('run-hooks') === true, + activate: flags.get('activate') === true || flags.get('run-hooks') === true, + parentWorktree: explicitParentWorktree, + ...(cwdParentWorktree ? { cwdParentWorktree } : {}), + noParent, + callerTerminalHandle + }) printHookWarning(result.result, json) + printLineageSummary(result.result, json) printResult(result, json, formatWorktreeShow) }, 'worktree set': async ({ flags, client, cwd, json }) => { + assertParentFlagsCompatible(flags) const result = await client.call<{ worktree: RuntimeWorktreeRecord }>('worktree.set', { worktree: await getRequiredWorktreeSelector(flags, 'worktree', cwd, client), displayName: getOptionalStringFlag(flags, 'display-name'), linkedIssue: getOptionalNullableNumberFlag(flags, 'issue'), - comment: getOptionalStringFlag(flags, 'comment') + comment: getOptionalStringFlag(flags, 'comment'), + parentWorktree: await getOptionalWorktreeSelector(flags, 'parent-worktree', cwd, client), + noParent: flags.get('no-parent') === true }) printResult(result, json, formatWorktreeShow) }, diff --git a/src/cli/help.ts b/src/cli/help.ts index b12930695..9c54fed81 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -152,10 +152,10 @@ Common Commands: orca environment show --environment [--json] orca environment rm --environment [--json] orca worktree list [--repo ] [--limit ] [--json] - orca worktree create --repo --name [--base-branch ] [--issue ] [--comment ] [--run-hooks] [--activate] [--json] + orca worktree create --repo --name [--base-branch ] [--issue ] [--comment ] [--parent-worktree ] [--no-parent] [--run-hooks] [--activate] [--json] orca worktree show --worktree [--json] orca worktree current [--json] - orca worktree set --worktree [--display-name ] [--issue ] [--comment ] [--json] + orca worktree set --worktree [--display-name ] [--issue ] [--comment ] [--parent-worktree |--no-parent] [--json] orca worktree rm --worktree [--force] [--run-hooks] [--json] orca worktree ps [--limit ] [--json] orca terminal list [--worktree ] [--limit ] [--json] @@ -178,6 +178,8 @@ Selectors: --repo Registered repo selector such as id:, name:, or path: --worktree Worktree selector such as id:, branch:, issue:, path:, or active/current --terminal Runtime-issued terminal handle returned by \`orca terminal list --json\` + --parent-worktree Parent worktree selector; create infers one from the Orca terminal or current directory by default + --no-parent Force worktree creation/update to have no parent lineage Terminal Send Options: --text Text to send to the terminal @@ -344,8 +346,11 @@ export function formatFlagHelp(flag: string): string { limit: '--limit Maximum number of rows to return', 'mouse-button': '--mouse-button Mouse button: left, right, or middle', name: '--name Name for the new worktree', + 'no-parent': '--no-parent Force no parent lineage', 'no-screenshot': '--no-screenshot Skip screenshot capture after the operation', pages: '--pages Number of scroll pages', + 'parent-worktree': + '--parent-worktree Parent worktree selector; create infers one by default', path: '--path Filesystem path to the repo', query: '--query Search text for matching refs', ref: '--ref Base ref to persist for the repo', diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 6758745bd..b5d8b372e 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -107,6 +107,7 @@ describe('orca cli worktree awareness', () => { beforeEach(() => { callMock.mockReset() + delete process.env.ORCA_TERMINAL_HANDLE serveOrcaAppMock.mockReset() getDefaultUserDataPathMock.mockClear() addEnvironmentFromPairingCodeMock.mockReset() @@ -246,13 +247,175 @@ describe('orca cli worktree awareness', () => { worktree: `path:${path.resolve('/tmp/repo/feature')}`, displayName: undefined, linkedIssue: undefined, - comment: 'hello' + comment: 'hello', + parentWorktree: undefined, + noParent: false + }) + }) + + it('passes parent lineage through worktree.set', async () => { + queueFixtures( + callMock, + okFixture('req_set_parent', { + worktree: { + ...buildWorktree('/tmp/repo/child', 'feature/child'), + parentWorktreeId: 'repo::/tmp/repo/parent', + childWorktreeIds: [], + lineage: { + worktreeId: 'repo::/tmp/repo/child', + worktreeInstanceId: 'child-instance', + parentWorktreeId: 'repo::/tmp/repo/parent', + parentWorktreeInstanceId: 'parent-instance', + origin: 'manual', + capture: { source: 'manual-action', confidence: 'explicit' }, + createdAt: 1 + } + } + }) + ) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main( + [ + 'worktree', + 'set', + '--worktree', + 'id:repo::/tmp/repo/child', + '--parent-worktree', + 'id:repo::/tmp/repo/parent', + '--json' + ], + '/tmp/repo' + ) + + expect(callMock).toHaveBeenCalledWith('worktree.set', { + worktree: 'id:repo::/tmp/repo/child', + displayName: undefined, + linkedIssue: undefined, + comment: undefined, + parentWorktree: 'id:repo::/tmp/repo/parent', + noParent: false + }) + }) + + it('resolves current for explicit parent-worktree on set', async () => { + queueFixtures( + callMock, + worktreeListFixture([buildWorktree('/tmp/repo/parent', 'feature/parent')]), + okFixture('req_set_parent', { + worktree: { + ...buildWorktree('/tmp/repo/child', 'feature/child'), + parentWorktreeId: 'repo::/tmp/repo/parent', + childWorktreeIds: [], + lineage: null + } + }) + ) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main( + [ + 'worktree', + 'set', + '--worktree', + 'id:repo::/tmp/repo/child', + '--parent-worktree', + 'current', + '--json' + ], + '/tmp/repo/parent/src' + ) + + expect(callMock).toHaveBeenNthCalledWith(2, 'worktree.set', { + worktree: 'id:repo::/tmp/repo/child', + displayName: undefined, + linkedIssue: undefined, + comment: undefined, + parentWorktree: `path:${path.resolve('/tmp/repo/parent')}`, + noParent: false + }) + }) + + it('rejects contradictory parent flags on worktree.set before resolving selectors', async () => { + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) + const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const priorExitCode = process.exitCode + + await main( + [ + 'worktree', + 'set', + '--worktree', + 'id:repo::/tmp/repo/child', + '--parent-worktree', + 'current', + '--no-parent', + '--json' + ], + '/tmp/not-managed' + ) + + expect(callMock).not.toHaveBeenCalled() + expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain( + 'Choose either --parent-worktree or --no-parent, not both.' + ) + expect(process.exitCode).toBe(1) + + process.exitCode = priorExitCode + }) + + it('rejects bare parent-worktree on worktree.set', async () => { + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) + const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const priorExitCode = process.exitCode + + await main( + ['worktree', 'set', '--worktree', 'id:repo::/tmp/repo/child', '--parent-worktree', '--json'], + '/tmp/repo' + ) + + expect(callMock).not.toHaveBeenCalled() + expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain( + 'Missing required --parent-worktree' + ) + expect(process.exitCode).toBe(1) + + process.exitCode = priorExitCode + }) + + it('passes parent removal through worktree.set', async () => { + queueFixtures( + callMock, + okFixture('req_clear_parent', { + worktree: { + ...buildWorktree('/tmp/repo/child', 'feature/child'), + parentWorktreeId: null, + childWorktreeIds: [], + lineage: null + } + }) + ) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main( + ['worktree', 'set', '--worktree', 'id:repo::/tmp/repo/child', '--no-parent', '--json'], + '/tmp/repo' + ) + + expect(callMock).toHaveBeenCalledWith('worktree.set', { + worktree: 'id:repo::/tmp/repo/child', + displayName: undefined, + linkedIssue: undefined, + comment: undefined, + parentWorktree: undefined, + noParent: true }) }) it('passes explicit activation through worktree.create', async () => { queueFixtures( callMock, + worktreeListFixture([buildWorktree('/tmp/repo', 'main', 'abc', 'repo-1')]), okFixture('req_create', { worktree: buildWorktree('/tmp/repo/feature', 'feature', 'abc', 'repo-1') }) @@ -264,14 +427,247 @@ describe('orca cli worktree awareness', () => { '/tmp/repo' ) - expect(callMock).toHaveBeenCalledWith('worktree.create', { + expect(callMock).toHaveBeenNthCalledWith(2, 'worktree.create', { repo: 'id:repo-1', name: 'feature', baseBranch: undefined, linkedIssue: undefined, comment: undefined, runHooks: false, - activate: true + activate: true, + parentWorktree: undefined, + cwdParentWorktree: `path:${path.resolve('/tmp/repo')}`, + noParent: false, + callerTerminalHandle: undefined + }) + }) + + it('passes an explicit parent through worktree.create without cwd inference', async () => { + queueFixtures( + callMock, + okFixture('req_create', { + worktree: { + ...buildWorktree('/tmp/repo/child', 'child', 'abc', 'repo-1'), + parentWorktreeId: 'repo-1::/tmp/repo/parent', + lineage: { + worktreeId: 'repo-1::/tmp/repo/child', + worktreeInstanceId: 'child-instance', + parentWorktreeId: 'repo-1::/tmp/repo/parent', + parentWorktreeInstanceId: 'parent-instance', + origin: 'cli', + capture: { source: 'explicit-cli-flag', confidence: 'explicit' }, + createdAt: 1 + } + }, + lineage: { + worktreeId: 'repo-1::/tmp/repo/child', + worktreeInstanceId: 'child-instance', + parentWorktreeId: 'repo-1::/tmp/repo/parent', + parentWorktreeInstanceId: 'parent-instance', + origin: 'cli', + capture: { source: 'explicit-cli-flag', confidence: 'explicit' }, + createdAt: 1 + }, + warnings: [] + }) + ) + vi.spyOn(console, 'log').mockImplementation(() => {}) + vi.spyOn(console, 'error').mockImplementation(() => {}) + + await main( + [ + 'worktree', + 'create', + '--repo', + 'id:repo-1', + '--name', + 'child', + '--parent-worktree', + 'id:repo-1::/tmp/repo/parent', + '--json' + ], + '/tmp/repo/parent/src' + ) + + expect(callMock).toHaveBeenCalledTimes(1) + expect(callMock).toHaveBeenCalledWith('worktree.create', { + repo: 'id:repo-1', + name: 'child', + baseBranch: undefined, + linkedIssue: undefined, + comment: undefined, + runHooks: false, + activate: false, + parentWorktree: 'id:repo-1::/tmp/repo/parent', + noParent: false, + callerTerminalHandle: undefined + }) + }) + + it('resolves current for explicit parent-worktree on create', async () => { + queueFixtures( + callMock, + worktreeListFixture([buildWorktree('/tmp/repo/parent', 'feature/parent', 'abc', 'repo-1')]), + okFixture('req_create', { + worktree: buildWorktree('/tmp/repo/child', 'child', 'abc', 'repo-1'), + lineage: null, + warnings: [] + }) + ) + vi.spyOn(console, 'log').mockImplementation(() => {}) + vi.spyOn(console, 'error').mockImplementation(() => {}) + + await main( + [ + 'worktree', + 'create', + '--repo', + 'id:repo-1', + '--name', + 'child', + '--parent-worktree', + 'current', + '--json' + ], + '/tmp/repo/parent/src' + ) + + expect(callMock).toHaveBeenNthCalledWith(2, 'worktree.create', { + repo: 'id:repo-1', + name: 'child', + baseBranch: undefined, + linkedIssue: undefined, + comment: undefined, + runHooks: false, + activate: false, + parentWorktree: `path:${path.resolve('/tmp/repo/parent')}`, + noParent: false, + callerTerminalHandle: undefined + }) + }) + + it('rejects contradictory parent flags on worktree.create before resolving selectors', async () => { + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) + const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const priorExitCode = process.exitCode + + await main( + [ + 'worktree', + 'create', + '--repo', + 'id:repo-1', + '--name', + 'child', + '--parent-worktree', + 'current', + '--no-parent', + '--json' + ], + '/tmp/not-managed' + ) + + expect(callMock).not.toHaveBeenCalled() + expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain( + 'Choose either --parent-worktree or --no-parent, not both.' + ) + expect(process.exitCode).toBe(1) + + process.exitCode = priorExitCode + }) + + it('rejects bare parent-worktree on worktree.create', async () => { + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) + const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const priorExitCode = process.exitCode + + await main( + [ + 'worktree', + 'create', + '--repo', + 'id:repo-1', + '--name', + 'child', + '--parent-worktree', + '--json' + ], + '/tmp/repo' + ) + + expect(callMock).not.toHaveBeenCalled() + expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain( + 'Missing required --parent-worktree' + ) + expect(process.exitCode).toBe(1) + + process.exitCode = priorExitCode + }) + + it('passes no-parent through worktree.create and skips cwd inference', async () => { + queueFixtures( + callMock, + okFixture('req_create', { + worktree: buildWorktree('/tmp/repo/child', 'child', 'abc', 'repo-1'), + lineage: null, + warnings: [] + }) + ) + vi.spyOn(console, 'log').mockImplementation(() => {}) + vi.spyOn(console, 'error').mockImplementation(() => {}) + + await main( + ['worktree', 'create', '--repo', 'id:repo-1', '--name', 'child', '--no-parent', '--json'], + '/tmp/repo/parent/src' + ) + + expect(callMock).toHaveBeenCalledTimes(1) + expect(callMock).toHaveBeenCalledWith('worktree.create', { + repo: 'id:repo-1', + name: 'child', + baseBranch: undefined, + linkedIssue: undefined, + comment: undefined, + runHooks: false, + activate: false, + parentWorktree: undefined, + noParent: true, + callerTerminalHandle: undefined + }) + }) + + it('passes caller terminal handle through worktree.create with cwd fallback', async () => { + process.env.ORCA_TERMINAL_HANDLE = 'term_parent' + queueFixtures( + callMock, + worktreeListFixture([buildWorktree('/tmp/repo', 'main', 'abc', 'repo-1')]), + okFixture('req_create', { + worktree: buildWorktree('/tmp/repo/child', 'child', 'abc', 'repo-1'), + lineage: null, + warnings: [] + }) + ) + vi.spyOn(console, 'log').mockImplementation(() => {}) + vi.spyOn(console, 'error').mockImplementation(() => {}) + + await main( + ['worktree', 'create', '--repo', 'id:repo-1', '--name', 'child', '--json'], + '/tmp/repo' + ) + + expect(callMock).toHaveBeenCalledTimes(2) + expect(callMock).toHaveBeenNthCalledWith(2, 'worktree.create', { + repo: 'id:repo-1', + name: 'child', + baseBranch: undefined, + linkedIssue: undefined, + comment: undefined, + runHooks: false, + activate: false, + parentWorktree: undefined, + cwdParentWorktree: `path:${path.resolve('/tmp/repo')}`, + noParent: false, + callerTerminalHandle: 'term_parent' }) }) @@ -464,6 +860,7 @@ describe('orca cli worktree awareness', () => { it('opts into setup and activation when worktree.create runs hooks', async () => { queueFixtures( callMock, + worktreeListFixture([buildWorktree('/tmp/repo', 'main', 'abc', 'repo-1')]), okFixture('req_create', { worktree: buildWorktree('/tmp/repo/feature', 'feature', 'abc', 'repo-1') }) @@ -475,14 +872,18 @@ describe('orca cli worktree awareness', () => { '/tmp/repo' ) - expect(callMock).toHaveBeenCalledWith('worktree.create', { + expect(callMock).toHaveBeenNthCalledWith(2, 'worktree.create', { repo: 'id:repo-1', name: 'feature', baseBranch: undefined, linkedIssue: undefined, comment: undefined, runHooks: true, - activate: true + activate: true, + parentWorktree: undefined, + cwdParentWorktree: `path:${path.resolve('/tmp/repo')}`, + noParent: false, + callerTerminalHandle: undefined }) }) @@ -598,6 +999,30 @@ describe('orca cli worktree awareness', () => { errSpy.mockRestore() }) + it('passes the caller terminal handle through orchestration task-create', async () => { + process.env.ORCA_TERMINAL_HANDLE = 'term_creator' + callMock.mockResolvedValueOnce({ + id: 'req_task_create', + ok: true, + result: { + task: { id: 'task_1', status: 'ready' } + }, + _meta: { + runtimeId: 'runtime-1' + } + }) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main(['orchestration', 'task-create', '--spec', 'spawn child workspace'], '/tmp/repo') + + expect(callMock).toHaveBeenCalledWith('orchestration.taskCreate', { + spec: 'spawn child workspace', + deps: undefined, + parent: undefined, + callerTerminalHandle: 'term_creator' + }) + }) + it('passes dev mode to injected orchestration dispatches', async () => { process.env.ORCA_TERMINAL_HANDLE = 'term_sender' process.env.ORCA_USER_DATA_PATH = '/tmp/orca-dev' diff --git a/src/cli/specs/core.ts b/src/cli/specs/core.ts index afbb9dcd9..bcfd3695c 100644 --- a/src/cli/specs/core.ts +++ b/src/cli/specs/core.ts @@ -91,7 +91,7 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [ path: ['worktree', 'create'], summary: 'Create a new Orca-managed worktree', usage: - 'orca worktree create --repo --name [--base-branch ] [--issue ] [--comment ] [--run-hooks] [--activate] [--json]', + 'orca worktree create --repo --name [--base-branch ] [--issue ] [--comment ] [--parent-worktree ] [--no-parent] [--run-hooks] [--activate] [--json]', allowedFlags: [ ...GLOBAL_FLAGS, 'repo', @@ -99,10 +99,14 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [ 'base-branch', 'issue', 'comment', + 'parent-worktree', + 'no-parent', 'run-hooks', 'activate' ], notes: [ + 'By default, Orca records the new worktree as a child of the caller workspace when it can infer one from the Orca terminal or current directory.', + 'Pass --parent-worktree to choose a parent explicitly, or --no-parent to force no lineage.', 'By default this creates the worktree and its first terminal without switching the active Orca workspace.', 'Repo-defined setup hooks follow the repository setup policy; pass --run-hooks to force them.', 'Pass --activate when the CLI caller intentionally wants to reveal the new worktree in the app.', @@ -113,8 +117,16 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [ path: ['worktree', 'set'], summary: 'Update Orca metadata for a worktree', usage: - 'orca worktree set --worktree [--display-name ] [--issue ] [--comment ] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'worktree', 'display-name', 'issue', 'comment'] + 'orca worktree set --worktree [--display-name ] [--issue ] [--comment ] [--parent-worktree |--no-parent] [--json]', + allowedFlags: [ + ...GLOBAL_FLAGS, + 'worktree', + 'display-name', + 'issue', + 'comment', + 'parent-worktree', + 'no-parent' + ] }, { path: ['worktree', 'rm'], diff --git a/src/cli/test-fixtures.ts b/src/cli/test-fixtures.ts index 637041bbb..a8e7d8f91 100644 --- a/src/cli/test-fixtures.ts +++ b/src/cli/test-fixtures.ts @@ -12,6 +12,9 @@ type WorktreeFixture = { repoId: string path: string branch: string + parentWorktreeId: string | null + childWorktreeIds: string[] + lineage: null linkedIssue: null git: { path: string @@ -35,6 +38,9 @@ export function buildWorktree( repoId, path, branch, + parentWorktreeId: null, + childWorktreeIds: [], + lineage: null, linkedIssue: null, git: { path, head, branch, isBare: false, isMainWorktree: false }, displayName: '', diff --git a/src/main/ipc/worktree-logic.ts b/src/main/ipc/worktree-logic.ts index 266718fb9..570c74e21 100644 --- a/src/main/ipc/worktree-logic.ts +++ b/src/main/ipc/worktree-logic.ts @@ -176,6 +176,7 @@ export function mergeWorktree( const branchShort = git.branch.replace(/^refs\/heads\//, '') return { id: `${repoId}::${git.path}`, + ...(meta?.instanceId !== undefined ? { instanceId: meta.instanceId } : {}), repoId, path: git.path, head: git.head, diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index 27883eec8..90ebf6fe5 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -10,6 +10,7 @@ import type { BrowserWindow } from 'electron' import { join } from 'path' import { existsSync } from 'fs' +import { randomUUID } from 'crypto' import type { Store } from '../persistence' import type { CreateWorktreeArgs, @@ -430,6 +431,10 @@ export async function createRemoteWorktree( ) } const metaUpdates: Partial = { + // Why: path-derived worktree IDs can be reused after external deletion. + // Fresh creations must rotate instance identity so stale lineage cannot + // attach to the new occupant of the same path. + instanceId: randomUUID(), lastActivityAt: now, // Why: grants the new worktree a short grace window at the top of the // Recent sort. During worktree creation (git fetch + add can take several @@ -716,6 +721,10 @@ export async function createLocalWorktree( const worktreeId = `${repo.id}::${created.path}` const now = Date.now() const metaUpdates: Partial = { + // Why: path-derived worktree IDs can be reused after external deletion. + // Fresh creations must rotate instance identity so stale lineage cannot + // attach to the new occupant of the same path. + instanceId: randomUUID(), // Stamp activity so the worktree sorts into its final position // immediately — prevents scroll-to-reveal racing with a later // bumpWorktreeActivity that would re-sort the list. diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index 71d3b459c..3a004a009 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -155,7 +155,9 @@ describe('registerWorktreeHandlers', () => { getWorktreeMeta: vi.fn(), getAllWorktreeMeta: vi.fn(), setWorktreeMeta: vi.fn(), - removeWorktreeMeta: vi.fn() + removeWorktreeMeta: vi.fn(), + getAllWorktreeLineage: vi.fn(), + removeWorktreeLineage: vi.fn() } let runtimeStub: { resolveRemoteTrackingBase: ReturnType @@ -205,6 +207,8 @@ describe('registerWorktreeHandlers', () => { store.getAllWorktreeMeta, store.setWorktreeMeta, store.removeWorktreeMeta, + store.getAllWorktreeLineage, + store.removeWorktreeLineage, killAllProcessesForWorktreeMock, getLocalPtyProviderMock ]) { @@ -244,6 +248,7 @@ describe('registerWorktreeHandlers', () => { store.getWorktreeMeta.mockReturnValue(undefined) store.getAllWorktreeMeta.mockReturnValue({}) store.setWorktreeMeta.mockReturnValue({}) + store.getAllWorktreeLineage.mockReturnValue({}) getGitUsernameMock.mockReturnValue('') getDefaultBaseRefMock.mockReturnValue('origin/main') getDefaultRemoteMock.mockResolvedValue('origin') @@ -628,6 +633,104 @@ describe('registerWorktreeHandlers', () => { }) }) + it('prunes stale child lineage after a successful SSH worktree scan proves the child is missing', async () => { + const repo = { + id: 'repo-ssh', + path: '/remote/repo', + displayName: 'ssh', + badgeColor: '#000', + addedAt: 0, + connectionId: 'conn-1' + } + const provider = { + listWorktrees: vi.fn().mockResolvedValue([ + { + path: '/remote/live', + head: 'abc123', + branch: 'refs/heads/live', + isBare: false, + isMainWorktree: false + }, + { + path: '/remote/live-child', + head: 'def456', + branch: 'refs/heads/live-child', + isBare: false, + isMainWorktree: false + } + ]) + } + store.getRepos.mockReturnValue([repo]) + store.getRepo.mockReturnValue(repo) + getSshGitProviderMock.mockReturnValue(provider) + store.getAllWorktreeLineage.mockReturnValue({ + 'repo-ssh::/remote/missing-child': { + parentWorktreeId: 'repo-ssh::/remote/live' + }, + 'repo-ssh::/remote/live-child': { + parentWorktreeId: 'repo-ssh::/remote/missing-parent', + parentWorktreeInstanceId: 'old-parent-instance' + }, + 'repo-ssh::/remote/live': { + parentWorktreeId: 'other-repo::/elsewhere' + } + }) + store.getWorktreeMeta.mockImplementation((worktreeId: string) => + worktreeId === 'repo-ssh::/remote/missing-parent' + ? { instanceId: 'old-parent-instance' } + : undefined + ) + + await handlers['worktrees:list'](null, { repoId: 'repo-ssh' }) + + expect(store.removeWorktreeLineage).toHaveBeenCalledWith('repo-ssh::/remote/missing-child') + expect(store.removeWorktreeLineage).not.toHaveBeenCalledWith('repo-ssh::/remote/live-child') + expect(store.removeWorktreeLineage).not.toHaveBeenCalledWith('repo-ssh::/remote/live') + expect(store.setWorktreeMeta).toHaveBeenCalledWith( + 'repo-ssh::/remote/missing-parent', + expect.objectContaining({ instanceId: expect.any(String) }) + ) + }) + + it('does not repeatedly rotate already-invalid missing parent metadata', async () => { + const repo = { + id: 'repo-ssh', + path: '/remote/repo', + displayName: 'ssh', + badgeColor: '#000', + addedAt: 0, + connectionId: 'conn-1' + } + const provider = { + listWorktrees: vi.fn().mockResolvedValue([ + { + path: '/remote/live-child', + head: 'def456', + branch: 'refs/heads/live-child', + isBare: false, + isMainWorktree: false + } + ]) + } + store.getRepos.mockReturnValue([repo]) + store.getRepo.mockReturnValue(repo) + getSshGitProviderMock.mockReturnValue(provider) + store.getAllWorktreeLineage.mockReturnValue({ + 'repo-ssh::/remote/live-child': { + parentWorktreeId: 'repo-ssh::/remote/missing-parent', + parentWorktreeInstanceId: 'old-parent-instance' + } + }) + store.getWorktreeMeta.mockReturnValue({ instanceId: 'rotated-parent-instance' }) + + await handlers['worktrees:list'](null, { repoId: 'repo-ssh' }) + + expect(store.setWorktreeMeta).not.toHaveBeenCalledWith( + 'repo-ssh::/remote/missing-parent', + expect.objectContaining({ instanceId: expect.any(String) }) + ) + }) + it('does not await a cold fetch when the remote-tracking base exists locally', async () => { const remoteBase = { remote: 'origin', @@ -1098,6 +1201,7 @@ describe('registerWorktreeHandlers', () => { comment: '', linkedIssue: null, linkedPR: null, + instanceId: 'existing-instance', isArchived: false, isUnread: false, isPinned: false, @@ -1114,6 +1218,44 @@ describe('registerWorktreeHandlers', () => { expect(listed[0].lastActivityAt).toBe(42) }) + it('backfills instanceId on discovery for persisted metadata from older profiles', async () => { + listWorktreesMock.mockResolvedValue([ + { + path: '/workspace/existing-wt', + head: 'abc123', + branch: 'refs/heads/feature', + isBare: false, + isMainWorktree: false + } + ]) + store.getWorktreeMeta.mockReturnValue({ + displayName: '', + comment: '', + linkedIssue: null, + linkedPR: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 42 + }) + store.setWorktreeMeta.mockReturnValue({ + instanceId: 'new-instance', + lastActivityAt: 42 + }) + + const listed = (await handlers['worktrees:list'](null, { repoId: 'repo-1' })) as { + id: string + instanceId?: string + }[] + + expect(store.setWorktreeMeta).toHaveBeenCalledWith( + 'repo-1::/workspace/existing-wt', + expect.objectContaining({ instanceId: expect.any(String) }) + ) + expect(listed[0].instanceId).toBe('new-instance') + }) + it('stamps lastActivityAt on first discovery for folder-mode repos', async () => { // Why: folder repos produce a synthetic worktree that flows through the // same list path. Without the stamp, adding a folder puts its card at the diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index a22ad1d25..5f6c9b2b1 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -2,6 +2,7 @@ import type { BrowserWindow } from 'electron' import { ipcMain } from 'electron' import { rm } from 'fs/promises' +import { randomUUID } from 'crypto' import type { Store } from '../persistence' import { isFolderRepo } from '../../shared/repo-kind' import { deleteWorktreeHistoryDir } from '../terminal-history' @@ -66,6 +67,12 @@ import { function resolveWorktreeMetaWithDiscoveryStamp(store: Store, worktreeId: string): WorktreeMeta { const existing = store.getWorktreeMeta(worktreeId) if (existing) { + if (!existing.instanceId) { + // Why: profiles created before lineage shipped already have WorktreeMeta + // rows. Backfill on authoritative discovery so upgraded workspaces can + // immediately participate in instance-validated lineage. + return store.setWorktreeMeta(worktreeId, { instanceId: randomUUID() }) + } return existing } return store.setWorktreeMeta(worktreeId, { lastActivityAt: Date.now() }) @@ -104,6 +111,40 @@ function rememberLocalWorktreeRoots( ]) } +function pruneLineageForMissingRepoWorktrees( + store: Store, + repo: Repo, + gitWorktrees: GitWorktreeInfo[] +): void { + if ( + typeof store.getAllWorktreeLineage !== 'function' || + typeof store.removeWorktreeLineage !== 'function' + ) { + return + } + const liveIds = new Set(gitWorktrees.map((worktree) => `${repo.id}::${worktree.path}`)) + const repoPrefix = `${repo.id}::` + for (const [childId, lineage] of Object.entries(store.getAllWorktreeLineage())) { + if (childId.startsWith(repoPrefix) && !liveIds.has(childId)) { + // Why: path-derived IDs can disappear and later be reused by a different + // checkout. Once a successful scan proves the child is gone, drop its + // lineage so a future same-path worktree cannot inherit it. Missing + // parents stay readable so the UI can show the repairable "Missing + // parent" state. + store.removeWorktreeLineage(childId) + } + if (lineage.parentWorktreeId.startsWith(repoPrefix) && !liveIds.has(lineage.parentWorktreeId)) { + const parentMeta = store.getWorktreeMeta(lineage.parentWorktreeId) + if (!parentMeta || parentMeta.instanceId === lineage.parentWorktreeInstanceId) { + // Why: keep the child lineage so the UI can show "Missing parent", but + // rotate the absent parent's stale identity once. If a different + // checkout later reuses that path, the old lineage stays invalid. + store.setWorktreeMeta(lineage.parentWorktreeId, { instanceId: randomUUID() }) + } + } + } +} + type SshWorktreeMetaCandidate = { path: string meta: WorktreeMeta @@ -179,6 +220,8 @@ export function registerWorktreeHandlers( ipcMain.removeHandler('worktrees:resolvePrBase') ipcMain.removeHandler('worktrees:remove') ipcMain.removeHandler('worktrees:updateMeta') + ipcMain.removeHandler('worktrees:listLineage') + ipcMain.removeHandler('worktrees:updateLineage') ipcMain.removeHandler('worktrees:persistSortOrder') ipcMain.removeHandler('hooks:check') ipcMain.removeHandler('hooks:createIssueCommandRunner') @@ -225,6 +268,7 @@ export function registerWorktreeHandlers( gitWorktrees = await listRepoWorktrees(repo) } rememberLocalWorktreeRoots(store, repo, gitWorktrees) + pruneLineageForMissingRepoWorktrees(store, repo, gitWorktrees) loggedWorktreeListFailures.delete(`${repo.id}:${repo.path}`) return gitWorktrees.map((gw) => { const worktreeId = `${repo.id}::${gw.path}` @@ -292,6 +336,7 @@ export function registerWorktreeHandlers( gitWorktrees = await listRepoWorktrees(repo) } rememberLocalWorktreeRoots(store, repo, gitWorktrees) + pruneLineageForMissingRepoWorktrees(store, repo, gitWorktrees) loggedWorktreeListFailures.delete(`${repo.id}:${repo.path}`) return gitWorktrees.map((gw) => { const worktreeId = `${repo.id}::${gw.path}` @@ -743,6 +788,27 @@ export function registerWorktreeHandlers( } ) + ipcMain.handle('worktrees:listLineage', async () => { + await runtime.hydrateInferredWorktreeLineage() + return store.getAllWorktreeLineage() + }) + + ipcMain.handle( + 'worktrees:updateLineage', + async (_event, args: { worktreeId: string; parentWorktreeId?: string; noParent?: boolean }) => { + await runtime.updateManagedWorktreeMeta(args.worktreeId, { + lineage: + args.noParent === true + ? { noParent: true } + : args.parentWorktreeId + ? { parentWorktree: `id:${args.parentWorktreeId}` } + : undefined + }) + notifyWorktreesChanged(mainWindow, parseWorktreeId(args.worktreeId).repoId) + return store.getWorktreeLineage(args.worktreeId) ?? null + } + ) + // Why: the renderer continuously snapshots the computed sidebar order into // sortOrder so that it can be restored on cold start (when ephemeral signals // like running jobs and live terminals are gone). A single batch call avoids diff --git a/src/main/persistence.test.ts b/src/main/persistence.test.ts index 5846a1e45..1bea0d38d 100644 --- a/src/main/persistence.test.ts +++ b/src/main/persistence.test.ts @@ -5,7 +5,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { writeFileSync, readFileSync, rmSync, mkdtempSync, mkdirSync, existsSync } from 'fs' import { join } from 'path' import { tmpdir } from 'os' -import type { Repo, TerminalTab, WorkspaceSessionState } from '../shared/types' +import type { Repo, TerminalTab, WorktreeLineage, WorkspaceSessionState } from '../shared/types' import { isTerminalLeafId, makePaneKey } from '../shared/stable-pane-id' import { MAX_BROWSER_HISTORY_ENTRIES } from '../shared/workspace-session-browser-history' @@ -79,6 +79,17 @@ const makeTerminalTab = (overrides: Partial = {}): TerminalTab => ( ...overrides }) +const makeWorktreeLineage = (overrides: Partial = {}): WorktreeLineage => ({ + worktreeId: 'r1::/path/child', + worktreeInstanceId: 'child-instance', + parentWorktreeId: 'r1::/path/parent', + parentWorktreeInstanceId: 'parent-instance', + origin: 'manual', + capture: { source: 'manual-action', confidence: 'explicit' }, + createdAt: 1, + ...overrides +}) + function makeSessionWithTerminalBuffers(): WorkspaceSessionState { return { activeRepoId: 'local-repo', @@ -471,6 +482,40 @@ describe('Store', () => { expect(store.getWorktreeMeta('r2::/other')!.displayName).toBe('other') }) + it('removeRepo deletes child and parent lineage for the repo', async () => { + const store = await createStore() + store.addRepo(makeRepo({ id: 'r1' })) + store.addRepo(makeRepo({ id: 'r2', path: '/repo2' })) + + store.setWorktreeLineage( + 'r1::/path/child', + makeWorktreeLineage({ + worktreeId: 'r1::/path/child', + parentWorktreeId: 'r1::/path/parent' + }) + ) + store.setWorktreeLineage( + 'r2::/other-child', + makeWorktreeLineage({ + worktreeId: 'r2::/other-child', + parentWorktreeId: 'r1::/path/parent' + }) + ) + store.setWorktreeLineage( + 'r2::/other', + makeWorktreeLineage({ + worktreeId: 'r2::/other', + parentWorktreeId: 'r2::/parent' + }) + ) + + store.removeRepo('r1') + + expect(store.getWorktreeLineage('r1::/path/child')).toBeUndefined() + expect(store.getWorktreeLineage('r2::/other-child')).toBeUndefined() + expect(store.getWorktreeLineage('r2::/other')).toBeDefined() + }) + // ── 7. updateRepo ────────────────────────────────────────────────── it('updateRepo modifies the repo in place', async () => { @@ -3001,6 +3046,35 @@ describe('Store', () => { expect(store.getWorktreeMeta('b')).toBeDefined() }) + it('stores and removes worktree lineage independently from metadata', async () => { + const store = await createStore() + const lineage = makeWorktreeLineage() + + store.setWorktreeMeta(lineage.worktreeId, { displayName: 'child' }) + store.setWorktreeLineage(lineage.worktreeId, lineage) + + expect(store.getWorktreeLineage(lineage.worktreeId)).toEqual(lineage) + expect(store.getAllWorktreeLineage()).toEqual({ [lineage.worktreeId]: lineage }) + + store.removeWorktreeLineage(lineage.worktreeId) + + expect(store.getWorktreeLineage(lineage.worktreeId)).toBeUndefined() + expect(store.getWorktreeMeta(lineage.worktreeId)).toBeDefined() + }) + + it('removeWorktreeMeta deletes that worktree lineage entry', async () => { + const store = await createStore() + const lineage = makeWorktreeLineage() + + store.setWorktreeMeta(lineage.worktreeId, { displayName: 'child' }) + store.setWorktreeLineage(lineage.worktreeId, lineage) + + store.removeWorktreeMeta(lineage.worktreeId) + + expect(store.getWorktreeMeta(lineage.worktreeId)).toBeUndefined() + expect(store.getWorktreeLineage(lineage.worktreeId)).toBeUndefined() + }) + // ── Rolling backups (issue #1158) ────────────────────────────────── describe('rolling backups', () => { diff --git a/src/main/persistence.ts b/src/main/persistence.ts index e400700b6..5df4b254f 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -33,6 +33,7 @@ import type { Repo, SparsePreset, WorktreeMeta, + WorktreeLineage, GlobalSettings, OnboardingChecklistState, OnboardingOutcome, @@ -1112,6 +1113,7 @@ export class Store { result = { ...defaults, ...parsed, + worktreeLineageById: parsed.worktreeLineageById ?? {}, settings: { ...defaults.settings, ...parsed.settings, @@ -1585,6 +1587,11 @@ export class Store { delete this.state.worktreeMeta[key] } } + for (const [childId, lineage] of Object.entries(this.state.worktreeLineageById)) { + if (childId.startsWith(prefix) || lineage.parentWorktreeId.startsWith(prefix)) { + delete this.state.worktreeLineageById[childId] + } + } this.scheduleSave() } @@ -1867,6 +1874,9 @@ export class Store { setWorktreeMeta(worktreeId: string, meta: Partial): WorktreeMeta { const existing = this.state.worktreeMeta[worktreeId] || getDefaultWorktreeMeta() const updated = { ...existing, ...meta } + if (!updated.instanceId) { + updated.instanceId = randomUUID() + } this.state.worktreeMeta[worktreeId] = updated this.scheduleSave() return updated @@ -1874,6 +1884,26 @@ export class Store { removeWorktreeMeta(worktreeId: string): void { delete this.state.worktreeMeta[worktreeId] + delete this.state.worktreeLineageById[worktreeId] + this.scheduleSave() + } + + getWorktreeLineage(worktreeId: string): WorktreeLineage | undefined { + return this.state.worktreeLineageById[worktreeId] + } + + getAllWorktreeLineage(): Record { + return this.state.worktreeLineageById + } + + setWorktreeLineage(worktreeId: string, lineage: WorktreeLineage): WorktreeLineage { + this.state.worktreeLineageById[worktreeId] = lineage + this.scheduleSave() + return lineage + } + + removeWorktreeLineage(worktreeId: string): void { + delete this.state.worktreeLineageById[worktreeId] this.scheduleSave() } @@ -2559,6 +2589,7 @@ export class Store { function getDefaultWorktreeMeta(): WorktreeMeta { return { + instanceId: randomUUID(), displayName: '', comment: '', linkedIssue: null, diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 0b89b417f..62e4e3551 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -1,6 +1,6 @@ /* eslint-disable max-lines -- Why: runtime behavior is stateful and cross-cutting, so these tests stay in one file to preserve the end-to-end invariants around handles, waits, and graph sync. */ import { afterEach, describe, expect, it, vi } from 'vitest' -import type { WorktreeMeta } from '../../shared/types' +import type { WorktreeLineage, WorktreeMeta } from '../../shared/types' import { addWorktree, listWorktrees, removeWorktree } from '../git/worktree' import { createSetupRunnerScript, @@ -25,23 +25,41 @@ const { removeWorktreeMock, computeWorktreePathMock, ensurePathWithinWorkspaceMock, + sshGitProviders, + getSshGitProviderMock, + registerSshGitProviderMock, + unregisterSshGitProviderMock, invalidateAuthorizedRootsCacheMock -} = vi.hoisted(() => ({ - MOCK_GIT_WORKTREES: [ - { - path: '/tmp/worktree-a', - head: 'abc', - branch: 'feature/foo', - isBare: false, - isMainWorktree: false - } - ], - addWorktreeMock: vi.fn(), - removeWorktreeMock: vi.fn(), - computeWorktreePathMock: vi.fn(), - ensurePathWithinWorkspaceMock: vi.fn(), - invalidateAuthorizedRootsCacheMock: vi.fn() -})) +} = vi.hoisted(() => { + // Why: SSH runtime tests register providers through the public dispatcher API, + // so the mock needs the same registry semantics as the real module. + const sshGitProviders = new Map() + + return { + MOCK_GIT_WORKTREES: [ + { + path: '/tmp/worktree-a', + head: 'abc', + branch: 'feature/foo', + isBare: false, + isMainWorktree: false + } + ], + addWorktreeMock: vi.fn(), + removeWorktreeMock: vi.fn(), + computeWorktreePathMock: vi.fn(), + ensurePathWithinWorkspaceMock: vi.fn(), + sshGitProviders, + getSshGitProviderMock: vi.fn((connectionId: string) => sshGitProviders.get(connectionId)), + registerSshGitProviderMock: vi.fn((connectionId: string, provider: unknown) => { + sshGitProviders.set(connectionId, provider) + }), + unregisterSshGitProviderMock: vi.fn((connectionId: string) => { + sshGitProviders.delete(connectionId) + }), + invalidateAuthorizedRootsCacheMock: vi.fn() + } +}) vi.mock('../git/worktree', () => ({ listWorktrees: vi.fn().mockResolvedValue(MOCK_GIT_WORKTREES), @@ -49,6 +67,12 @@ vi.mock('../git/worktree', () => ({ removeWorktree: removeWorktreeMock })) +vi.mock('../providers/ssh-git-dispatch', () => ({ + getSshGitProvider: getSshGitProviderMock, + registerSshGitProvider: registerSshGitProviderMock, + unregisterSshGitProvider: unregisterSshGitProviderMock +})) + vi.mock('../hooks', () => ({ createSetupRunnerScript: vi.fn(), getEffectiveHooks: vi.fn().mockReturnValue(null), @@ -93,6 +117,19 @@ afterEach(() => { vi.mocked(listWorktrees).mockResolvedValue(MOCK_GIT_WORKTREES) vi.mocked(addWorktree).mockReset() vi.mocked(removeWorktree).mockReset() + sshGitProviders.clear() + getSshGitProviderMock.mockReset() + getSshGitProviderMock.mockImplementation((connectionId: string) => + sshGitProviders.get(connectionId) + ) + registerSshGitProviderMock.mockReset() + registerSshGitProviderMock.mockImplementation((connectionId: string, provider: unknown) => { + sshGitProviders.set(connectionId, provider) + }) + unregisterSshGitProviderMock.mockReset() + unregisterSshGitProviderMock.mockImplementation((connectionId: string) => { + sshGitProviders.delete(connectionId) + }) vi.mocked(createSetupRunnerScript).mockReset() vi.mocked(getEffectiveHooks).mockReset() vi.mocked(hasHooksFile).mockReset() @@ -152,6 +189,24 @@ function createRuntime(): OrcaRuntimeService { return new OrcaRuntimeService(store) } +function makeWorktreeMeta(overrides: Partial = {}): WorktreeMeta { + return { + displayName: '', + comment: '', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + linkedGitLabMR: null, + linkedGitLabIssue: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + ...overrides + } +} + function deferred(): { promise: Promise resolve: (value: T) => void @@ -1955,6 +2010,8 @@ describe('OrcaRuntimeService', () => { repo: 'repo', path: '/tmp/worktree-a', branch: 'feature/foo', + parentWorktreeId: null, + childWorktreeIds: [], displayName: 'foo', linkedIssue: 123, linkedPR: null, @@ -2151,6 +2208,955 @@ describe('OrcaRuntimeService', () => { await expect(runtime.searchRepoRefs('id:repo-1', 'main', -5)).rejects.toThrow('invalid_limit') }) + it('resolves SSH worktrees when manually updating lineage', async () => { + const remoteRepo = { + id: 'remote-repo', + path: '/home/user/repo', + displayName: 'remote', + badgeColor: 'blue', + addedAt: 1, + connectionId: 'ssh-1' + } + const childId = `${remoteRepo.id}::/home/user/repo-child` + const parentId = `${remoteRepo.id}::/home/user/repo-parent` + const metaById: Record = { + [childId]: makeWorktreeMeta({ instanceId: 'child-instance' }), + [parentId]: makeWorktreeMeta({ instanceId: 'parent-instance' }) + } + const setWorktreeLineage = vi.fn((_worktreeId, lineage) => lineage) + const listSshWorktrees = vi.fn().mockResolvedValue([ + { + path: '/home/user/repo-child', + head: 'abc', + branch: 'feature/child', + isBare: false, + isMainWorktree: false + }, + { + path: '/home/user/repo-parent', + head: 'def', + branch: 'feature/parent', + isBare: false, + isMainWorktree: false + } + ]) + getSshGitProviderMock.mockReturnValue({ listWorktrees: listSshWorktrees }) + const runtimeStore = { + ...store, + getRepo: (id: string) => (id === remoteRepo.id ? remoteRepo : undefined), + getRepos: () => [remoteRepo], + getAllWorktreeMeta: () => metaById, + getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], + setWorktreeMeta: (worktreeId: string, meta: Partial) => { + metaById[worktreeId] = { ...metaById[worktreeId], ...meta } + return metaById[worktreeId] + }, + getWorktreeLineage: () => undefined, + setWorktreeLineage + } + const runtime = new OrcaRuntimeService(runtimeStore as never) + + await runtime.updateManagedWorktreeMeta(`id:${childId}`, { + lineage: { parentWorktree: `id:${parentId}` } + }) + + expect(listSshWorktrees).toHaveBeenCalledWith(remoteRepo.path) + expect(setWorktreeLineage).toHaveBeenCalledWith( + childId, + expect.objectContaining({ + worktreeId: childId, + worktreeInstanceId: 'child-instance', + parentWorktreeId: parentId, + parentWorktreeInstanceId: 'parent-instance', + origin: 'manual' + }) + ) + }) + + it('ignores stale instance-mismatched lineage when validating manual cycle repairs', async () => { + const parentPath = '/tmp/worktree-a' + const childPath = '/tmp/worktree-b' + const parentId = `${TEST_REPO_ID}::${parentPath}` + const childId = `${TEST_REPO_ID}::${childPath}` + const metaById: Record = { + [parentId]: makeWorktreeMeta({ instanceId: 'new-parent-instance' }), + [childId]: makeWorktreeMeta({ instanceId: 'child-instance' }) + } + const setWorktreeLineage = vi.fn((_worktreeId, lineage) => lineage) + const runtimeStore = { + ...store, + getAllWorktreeMeta: () => metaById, + getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], + setWorktreeMeta: (worktreeId: string, meta: Partial) => { + metaById[worktreeId] = { ...metaById[worktreeId], ...meta } + return metaById[worktreeId] + }, + getWorktreeLineage: (worktreeId: string) => + worktreeId === parentId + ? { + worktreeId: parentId, + worktreeInstanceId: 'old-parent-instance', + parentWorktreeId: childId, + parentWorktreeInstanceId: 'child-instance', + origin: 'manual' as const, + capture: { source: 'manual-action' as const, confidence: 'explicit' as const }, + createdAt: 1 + } + : undefined, + setWorktreeLineage + } + vi.mocked(listWorktrees).mockResolvedValue([ + { + path: parentPath, + head: 'abc', + branch: 'feature/a', + isBare: false, + isMainWorktree: false + }, + { + path: childPath, + head: 'def', + branch: 'feature/b', + isBare: false, + isMainWorktree: false + } + ]) + const runtime = new OrcaRuntimeService(runtimeStore as never) + + await runtime.updateManagedWorktreeMeta(`id:${childId}`, { + lineage: { parentWorktree: `id:${parentId}` } + }) + + expect(setWorktreeLineage).toHaveBeenCalledWith( + childId, + expect.objectContaining({ + worktreeId: childId, + worktreeInstanceId: 'child-instance', + parentWorktreeId: parentId, + parentWorktreeInstanceId: 'new-parent-instance' + }) + ) + }) + + it('backfills instanceId during runtime selector resolution for upgraded metadata', async () => { + const parentPath = '/tmp/worktree-parent' + const childPath = '/tmp/worktree-child' + const parentId = `${TEST_REPO_ID}::${parentPath}` + const childId = `${TEST_REPO_ID}::${childPath}` + const metaById: Record = { + [parentId]: makeWorktreeMeta(), + [childId]: makeWorktreeMeta({ instanceId: 'child-instance' }) + } + const runtimeStore = { + ...store, + getAllWorktreeMeta: () => metaById, + getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], + setWorktreeMeta: (worktreeId: string, meta: Partial) => { + metaById[worktreeId] = { + ...metaById[worktreeId], + ...meta, + instanceId: meta.instanceId ?? metaById[worktreeId]?.instanceId ?? 'backfilled-instance' + } + return metaById[worktreeId] + }, + getWorktreeLineage: () => undefined, + setWorktreeLineage: vi.fn((_worktreeId: string, lineage) => lineage) + } + vi.mocked(listWorktrees).mockResolvedValue([ + { + path: parentPath, + head: 'abc', + branch: 'feature/parent', + isBare: false, + isMainWorktree: false + }, + { + path: childPath, + head: 'def', + branch: 'feature/child', + isBare: false, + isMainWorktree: false + } + ]) + const runtime = new OrcaRuntimeService(runtimeStore as never) + + await runtime.updateManagedWorktreeMeta(`id:${childId}`, { + lineage: { parentWorktree: `id:${parentId}` } + }) + + expect(runtimeStore.setWorktreeLineage).toHaveBeenCalledWith( + childId, + expect.objectContaining({ + worktreeInstanceId: 'child-instance', + parentWorktreeInstanceId: 'backfilled-instance' + }) + ) + }) + + it('rotates a missing parent instance during runtime selector scans before same-path reuse', async () => { + const parentPath = '/tmp/worktree-parent' + const childPath = '/tmp/worktree-child' + const parentId = `${TEST_REPO_ID}::${parentPath}` + const childId = `${TEST_REPO_ID}::${childPath}` + const metaById: Record = { + [parentId]: makeWorktreeMeta({ instanceId: 'old-parent-instance' }), + [childId]: makeWorktreeMeta({ instanceId: 'child-instance' }) + } + const lineageById: Record = { + [childId]: { + worktreeId: childId, + worktreeInstanceId: 'child-instance', + parentWorktreeId: parentId, + parentWorktreeInstanceId: 'old-parent-instance', + origin: 'manual' as const, + capture: { source: 'manual-action' as const, confidence: 'explicit' as const }, + createdAt: 1 + } + } + const setWorktreeLineage = vi.fn((_worktreeId: string, lineage) => lineage) + const runtimeStore = { + ...store, + getAllWorktreeMeta: () => metaById, + getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], + setWorktreeMeta: (worktreeId: string, meta: Partial) => { + metaById[worktreeId] = { ...metaById[worktreeId], ...meta } + return metaById[worktreeId] + }, + getWorktreeLineage: (worktreeId: string) => lineageById[worktreeId], + getAllWorktreeLineage: () => lineageById, + removeWorktreeLineage: vi.fn((worktreeId: string) => { + delete lineageById[worktreeId] + }), + setWorktreeLineage + } + vi.mocked(listWorktrees) + .mockResolvedValueOnce([ + { + path: childPath, + head: 'def', + branch: 'feature/child', + isBare: false, + isMainWorktree: false + } + ]) + .mockResolvedValue([ + { + path: childPath, + head: 'def', + branch: 'feature/child', + isBare: false, + isMainWorktree: false + }, + { + path: parentPath, + head: 'abc', + branch: 'feature/parent', + isBare: false, + isMainWorktree: false + } + ]) + const runtime = new OrcaRuntimeService(runtimeStore as never) + + await runtime.showManagedWorktree(`id:${childId}`) + const rotatedParentInstance = metaById[parentId].instanceId + expect(rotatedParentInstance).toBeTruthy() + expect(rotatedParentInstance).not.toBe('old-parent-instance') + await runtime.updateManagedWorktreeMeta(`id:${childId}`, { comment: 'rescanned' }) + expect(metaById[parentId].instanceId).toBe(rotatedParentInstance) + + await runtime.updateManagedWorktreeMeta(`id:${childId}`, { comment: 'touch' }) + await runtime.updateManagedWorktreeMeta(`id:${childId}`, { + lineage: { parentWorktree: `id:${parentId}` } + }) + + expect(setWorktreeLineage).toHaveBeenCalledWith( + childId, + expect.objectContaining({ + worktreeInstanceId: 'child-instance', + parentWorktreeInstanceId: rotatedParentInstance + }) + ) + }) + + it('does not prune lineage when a runtime local worktree scan fails', async () => { + const parentPath = '/tmp/worktree-parent' + const childPath = '/tmp/worktree-child' + const parentId = `${TEST_REPO_ID}::${parentPath}` + const childId = `${TEST_REPO_ID}::${childPath}` + const metaById: Record = { + [parentId]: makeWorktreeMeta({ instanceId: 'parent-instance' }), + [childId]: makeWorktreeMeta({ instanceId: 'child-instance' }) + } + const lineageById: Record = { + [childId]: { + worktreeId: childId, + worktreeInstanceId: 'child-instance', + parentWorktreeId: parentId, + parentWorktreeInstanceId: 'parent-instance', + origin: 'manual', + capture: { source: 'manual-action', confidence: 'explicit' }, + createdAt: 1 + } + } + const removeWorktreeLineage = vi.fn((worktreeId: string) => { + delete lineageById[worktreeId] + }) + const runtimeStore = { + ...store, + getAllWorktreeMeta: () => metaById, + getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], + setWorktreeMeta: vi.fn((worktreeId: string, meta: Partial) => { + metaById[worktreeId] = { ...metaById[worktreeId], ...meta } + return metaById[worktreeId] + }), + getAllWorktreeLineage: () => lineageById, + removeWorktreeLineage + } + vi.mocked(listWorktrees).mockRejectedValueOnce(new Error('git unavailable')) + const runtime = new OrcaRuntimeService(runtimeStore as never) + + await expect(runtime.showManagedWorktree(`id:${childId}`)).rejects.toThrow('selector_not_found') + + expect(removeWorktreeLineage).not.toHaveBeenCalled() + expect(runtimeStore.setWorktreeMeta).not.toHaveBeenCalled() + expect(lineageById[childId]).toBeTruthy() + expect(metaById[parentId].instanceId).toBe('parent-instance') + }) + + it('does not prune lineage when an SSH runtime provider is unavailable', async () => { + const remoteRepo = { + id: 'remote-repo', + path: '/home/user/repo', + displayName: 'remote', + badgeColor: 'blue', + addedAt: 1, + connectionId: 'ssh-1' + } + const parentId = `${remoteRepo.id}::/home/user/repo-parent` + const childId = `${remoteRepo.id}::/home/user/repo-child` + const metaById: Record = { + [parentId]: makeWorktreeMeta({ instanceId: 'parent-instance' }), + [childId]: makeWorktreeMeta({ instanceId: 'child-instance' }) + } + const lineageById: Record = { + [childId]: { + worktreeId: childId, + worktreeInstanceId: 'child-instance', + parentWorktreeId: parentId, + parentWorktreeInstanceId: 'parent-instance', + origin: 'manual', + capture: { source: 'manual-action', confidence: 'explicit' }, + createdAt: 1 + } + } + const removeWorktreeLineage = vi.fn((worktreeId: string) => { + delete lineageById[worktreeId] + }) + const runtimeStore = { + ...store, + getRepo: (id: string) => (id === remoteRepo.id ? remoteRepo : undefined), + getRepos: () => [remoteRepo], + getAllWorktreeMeta: () => metaById, + getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], + setWorktreeMeta: vi.fn((worktreeId: string, meta: Partial) => { + metaById[worktreeId] = { ...metaById[worktreeId], ...meta } + return metaById[worktreeId] + }), + getAllWorktreeLineage: () => lineageById, + removeWorktreeLineage + } + const runtime = new OrcaRuntimeService(runtimeStore as never) + + await expect(runtime.showManagedWorktree(`id:${childId}`)).rejects.toThrow('selector_not_found') + + expect(removeWorktreeLineage).not.toHaveBeenCalled() + expect(runtimeStore.setWorktreeMeta).not.toHaveBeenCalled() + expect(lineageById[childId]).toBeTruthy() + expect(metaById[parentId].instanceId).toBe('parent-instance') + }) + + it('exposes valid parent and child lineage in CLI worktree records', async () => { + const parentPath = '/tmp/worktree-parent' + const childPath = '/tmp/worktree-child' + const parentId = `${TEST_REPO_ID}::${parentPath}` + const childId = `${TEST_REPO_ID}::${childPath}` + const metaById: Record = { + [parentId]: makeWorktreeMeta({ + instanceId: 'parent-instance', + displayName: 'parent' + }), + [childId]: makeWorktreeMeta({ + instanceId: 'child-instance', + displayName: 'child' + }) + } + const lineageById: Record = { + [childId]: { + worktreeId: childId, + worktreeInstanceId: 'child-instance', + parentWorktreeId: parentId, + parentWorktreeInstanceId: 'parent-instance', + origin: 'manual', + capture: { source: 'manual-action', confidence: 'explicit' }, + createdAt: 1 + } + } + const runtimeStore = { + ...store, + getAllWorktreeMeta: () => metaById, + getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], + setWorktreeMeta: (worktreeId: string, meta: Partial) => { + metaById[worktreeId] = { ...metaById[worktreeId], ...meta } + return metaById[worktreeId] + }, + getAllWorktreeLineage: () => lineageById + } + vi.mocked(listWorktrees).mockResolvedValue([ + { + path: parentPath, + head: 'abc', + branch: 'feature/parent', + isBare: false, + isMainWorktree: false + }, + { + path: childPath, + head: 'def', + branch: 'feature/child', + isBare: false, + isMainWorktree: false + } + ]) + const runtime = new OrcaRuntimeService(runtimeStore as never) + + const listed = await runtime.listManagedWorktrees('id:repo-1') + const parent = listed.worktrees.find((worktree) => worktree.id === parentId) + const child = listed.worktrees.find((worktree) => worktree.id === childId) + + expect(parent).toMatchObject({ + parentWorktreeId: null, + childWorktreeIds: [childId], + lineage: null + }) + expect(child).toMatchObject({ + parentWorktreeId: parentId, + childWorktreeIds: [], + lineage: lineageById[childId] + }) + await expect(runtime.showManagedWorktree(`id:${childId}`)).resolves.toMatchObject({ + id: childId, + parentWorktreeId: parentId, + childWorktreeIds: [], + lineage: lineageById[childId] + }) + }) + + it('keeps valid orchestration lineage when caller terminal context is stale', async () => { + const parentPath = '/tmp/worktree-parent' + const childPath = '/tmp/workspaces/worker-child' + const parentId = `${TEST_REPO_ID}::${parentPath}` + const childId = `${TEST_REPO_ID}::${childPath}` + const metaById: Record = { + [parentId]: makeWorktreeMeta({ + instanceId: 'parent-instance', + displayName: 'coordinator' + }) + } + const setWorktreeLineage = vi.fn((worktreeId: string, lineage) => { + metaById[worktreeId] = metaById[worktreeId] ?? makeWorktreeMeta() + return lineage + }) + const runtimeStore = { + ...store, + getAllWorktreeMeta: () => metaById, + getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], + setWorktreeMeta: (worktreeId: string, meta: Partial) => { + const existing = metaById[worktreeId] ?? makeWorktreeMeta({ instanceId: 'child-instance' }) + metaById[worktreeId] = { ...existing, ...meta } + return metaById[worktreeId] + }, + getWorktreeLineage: () => undefined, + setWorktreeLineage + } + const runtime = new OrcaRuntimeService(runtimeStore as never) + computeWorktreePathMock.mockReturnValue(childPath) + ensurePathWithinWorkspaceMock.mockReturnValue(childPath) + vi.mocked(listWorktrees) + .mockResolvedValueOnce([ + { + path: parentPath, + head: 'abc', + branch: 'feature/coordinator', + isBare: false, + isMainWorktree: false + } + ]) + .mockResolvedValueOnce([ + { + path: childPath, + head: 'def', + branch: 'worker-child', + isBare: false, + isMainWorktree: false + } + ]) + + const result = await runtime.createManagedWorktree({ + repoSelector: 'id:repo-1', + name: 'worker-child', + lineage: { + callerTerminalHandle: 'term_stale', + orchestrationContext: { + parentWorktreeId: parentId, + orchestrationRunId: 'run-1', + taskId: 'task-1', + coordinatorHandle: 'term_coord' + } + } + }) + + expect(result.lineage).toMatchObject({ + worktreeId: childId, + parentWorktreeId: parentId, + origin: 'orchestration', + capture: { source: 'orchestration-context', confidence: 'inferred' }, + orchestrationRunId: 'run-1', + taskId: 'task-1', + coordinatorHandle: 'term_coord' + }) + expect(result.lineage).not.toHaveProperty('createdByTerminalHandle') + expect(result.warnings).toEqual([]) + expect(setWorktreeLineage).toHaveBeenCalledWith(childId, expect.any(Object)) + }) + + it('enriches caller-terminal lineage with active orchestration dispatch context', async () => { + const workerPath = '/tmp/worktree-worker' + const childPath = '/tmp/workspaces/worker-child' + const childId = `${TEST_REPO_ID}::${childPath}` + const workerId = `${TEST_REPO_ID}::${workerPath}` + const metaById: Record = { + [TEST_WORKTREE_ID]: makeWorktreeMeta({ + instanceId: 'parent-instance', + displayName: 'coordinator' + }), + [workerId]: makeWorktreeMeta({ + instanceId: 'worker-instance', + displayName: 'worker' + }) + } + const setWorktreeLineage = vi.fn((_worktreeId: string, lineage) => lineage) + const runtimeStore = { + ...store, + getAllWorktreeMeta: () => metaById, + getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], + setWorktreeMeta: (worktreeId: string, meta: Partial) => { + const existing = metaById[worktreeId] ?? makeWorktreeMeta() + metaById[worktreeId] = { ...existing, ...meta } + return metaById[worktreeId] + }, + getWorktreeLineage: () => undefined, + setWorktreeLineage + } + const runtime = new OrcaRuntimeService(runtimeStore as never) + const workerHandle = runtime.preAllocateHandleForPty('pty-worker') + const coordinatorHandle = runtime.preAllocateHandleForPty('pty-coordinator') + runtime.setOrchestrationDb({ + getActiveDispatchForTerminal: vi.fn(() => ({ + task_id: 'task-1' + })), + getActiveCoordinatorRun: vi.fn(() => ({ + id: 'run-1', + coordinator_handle: coordinatorHandle + })) + } as never) + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab-worker', + worktreeId: workerId, + title: 'Worker', + activeLeafId: 'pane:1', + layout: null + }, + { + tabId: 'tab-coordinator', + worktreeId: TEST_WORKTREE_ID, + title: 'Coordinator', + activeLeafId: 'pane:1', + layout: null + } + ], + leaves: [ + { + tabId: 'tab-worker', + worktreeId: workerId, + leafId: 'pane:1', + paneRuntimeId: 1, + ptyId: 'pty-worker', + paneTitle: null + }, + { + tabId: 'tab-coordinator', + worktreeId: TEST_WORKTREE_ID, + leafId: 'pane:1', + paneRuntimeId: 2, + ptyId: 'pty-coordinator', + paneTitle: null + } + ] + }) + computeWorktreePathMock.mockReturnValue(childPath) + ensurePathWithinWorkspaceMock.mockReturnValue(childPath) + vi.mocked(listWorktrees) + .mockResolvedValueOnce([ + ...MOCK_GIT_WORKTREES, + { + path: workerPath, + head: 'fed', + branch: 'feature/worker', + isBare: false, + isMainWorktree: false + } + ]) + .mockResolvedValueOnce([ + { + path: childPath, + head: 'def', + branch: 'worker-child', + isBare: false, + isMainWorktree: false + } + ]) + + const result = await runtime.createManagedWorktree({ + repoSelector: 'id:repo-1', + name: 'worker-child', + lineage: { callerTerminalHandle: workerHandle } + }) + + expect(result.lineage).toMatchObject({ + worktreeId: childId, + parentWorktreeId: workerId, + origin: 'orchestration', + capture: { source: 'orchestration-context', confidence: 'inferred' }, + orchestrationRunId: 'run-1', + taskId: 'task-1', + coordinatorHandle, + createdByTerminalHandle: workerHandle + }) + expect(setWorktreeLineage).toHaveBeenCalledWith( + childId, + expect.objectContaining({ + worktreeInstanceId: expect.not.stringMatching(/^old-/), + parentWorktreeInstanceId: 'worker-instance' + }) + ) + }) + + it('falls back to cwd lineage when the caller terminal handle is stale', async () => { + const parentPath = '/tmp/worktree-parent' + const childPath = '/tmp/workspaces/cwd-child' + const parentId = `${TEST_REPO_ID}::${parentPath}` + const childId = `${TEST_REPO_ID}::${childPath}` + const metaById: Record = { + [parentId]: makeWorktreeMeta({ instanceId: 'parent-instance' }) + } + const setWorktreeLineage = vi.fn((_worktreeId: string, lineage) => lineage) + const runtimeStore = { + ...store, + getAllWorktreeMeta: () => metaById, + getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], + setWorktreeMeta: (worktreeId: string, meta: Partial) => { + const existing = metaById[worktreeId] ?? makeWorktreeMeta() + metaById[worktreeId] = { ...existing, ...meta } + return metaById[worktreeId] + }, + getWorktreeLineage: () => undefined, + setWorktreeLineage + } + const runtime = new OrcaRuntimeService(runtimeStore as never) + computeWorktreePathMock.mockReturnValue(childPath) + ensurePathWithinWorkspaceMock.mockReturnValue(childPath) + vi.mocked(listWorktrees) + .mockResolvedValueOnce([ + { + path: parentPath, + head: 'abc', + branch: 'feature/parent', + isBare: false, + isMainWorktree: false + } + ]) + .mockResolvedValueOnce([ + { + path: childPath, + head: 'def', + branch: 'cwd-child', + isBare: false, + isMainWorktree: false + } + ]) + + const result = await runtime.createManagedWorktree({ + repoSelector: 'id:repo-1', + name: 'cwd-child', + lineage: { + callerTerminalHandle: 'term_stale', + cwdParentWorktree: `id:${parentId}` + } + }) + + expect(result.lineage).toMatchObject({ + worktreeId: childId, + parentWorktreeId: parentId, + origin: 'cli', + capture: { source: 'cwd-context', confidence: 'inferred' } + }) + expect(result.worktree).toMatchObject({ + parentWorktreeId: parentId, + childWorktreeIds: [], + lineage: result.lineage + }) + expect(setWorktreeLineage).toHaveBeenCalledWith(childId, expect.any(Object)) + }) + + it('keeps cwd-inferred lineage best-effort when the cwd parent cannot be resolved', async () => { + const childPath = '/tmp/workspaces/no-cwd-parent' + computeWorktreePathMock.mockReturnValue(childPath) + ensurePathWithinWorkspaceMock.mockReturnValue(childPath) + vi.mocked(listWorktrees) + .mockResolvedValueOnce(MOCK_GIT_WORKTREES) + .mockResolvedValueOnce([ + { + path: childPath, + head: 'def', + branch: 'no-cwd-parent', + isBare: false, + isMainWorktree: false + } + ]) + const runtime = new OrcaRuntimeService(store) + + const result = await runtime.createManagedWorktree({ + repoSelector: 'id:repo-1', + name: 'no-cwd-parent', + lineage: { + cwdParentWorktree: 'id:repo-1::/tmp/missing-parent' + } + }) + + expect(result.lineage).toBeNull() + expect(result.worktree).toMatchObject({ + parentWorktreeId: null, + childWorktreeIds: [], + lineage: null + }) + expect(result.warnings).toEqual([ + expect.objectContaining({ + code: 'LINEAGE_PARENT_CONTEXT_MISSING', + message: + 'Worktree created, but Orca could not validate the current directory as a parent workspace.' + }) + ]) + }) + + it('infers orchestration lineage from task-id comments when dispatch is completed', async () => { + const workerPath = '/tmp/worktree-worker' + const childPath = '/tmp/workspaces/worker-child' + const childId = `${TEST_REPO_ID}::${childPath}` + const workerId = `${TEST_REPO_ID}::${workerPath}` + const metaById: Record = { + [workerId]: makeWorktreeMeta({ + instanceId: 'worker-instance', + displayName: 'worker' + }) + } + const setWorktreeLineage = vi.fn((_worktreeId: string, lineage) => lineage) + const runtimeStore = { + ...store, + getAllWorktreeMeta: () => metaById, + getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], + setWorktreeMeta: (worktreeId: string, meta: Partial) => { + const existing = metaById[worktreeId] ?? makeWorktreeMeta() + metaById[worktreeId] = { ...existing, ...meta } + return metaById[worktreeId] + }, + getWorktreeLineage: () => undefined, + setWorktreeLineage + } + const runtime = new OrcaRuntimeService(runtimeStore as never) + const workerHandle = runtime.preAllocateHandleForPty('pty-worker') + runtime.setOrchestrationDb({ + getDispatchContext: vi.fn(() => ({ + task_id: 'task_abc123', + assignee_handle: workerHandle, + status: 'completed' + })) + } as never) + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab-worker', + worktreeId: workerId, + title: 'Worker', + activeLeafId: 'pane:1', + layout: null + } + ], + leaves: [ + { + tabId: 'tab-worker', + worktreeId: workerId, + leafId: 'pane:1', + paneRuntimeId: 1, + ptyId: 'pty-worker', + paneTitle: null + } + ] + }) + computeWorktreePathMock.mockReturnValue(childPath) + ensurePathWithinWorkspaceMock.mockReturnValue(childPath) + vi.mocked(listWorktrees) + .mockResolvedValueOnce([ + { + path: workerPath, + head: 'fed', + branch: 'feature/worker', + isBare: false, + isMainWorktree: false + } + ]) + .mockResolvedValueOnce([ + { + path: childPath, + head: 'def', + branch: 'worker-child', + isBare: false, + isMainWorktree: false + } + ]) + + const result = await runtime.createManagedWorktree({ + repoSelector: 'id:repo-1', + name: 'worker-child', + comment: 'Created via orchestration task task_abc123' + }) + + expect(result.lineage).toMatchObject({ + worktreeId: childId, + parentWorktreeId: workerId, + origin: 'orchestration', + capture: { source: 'orchestration-context', confidence: 'inferred' }, + taskId: 'task_abc123' + }) + expect(setWorktreeLineage).toHaveBeenCalledWith( + childId, + expect.objectContaining({ + parentWorktreeInstanceId: 'worker-instance' + }) + ) + }) + + it('infers orchestration lineage from task creator when no dispatch context exists', async () => { + const parentPath = '/tmp/worktree-parent' + const childPath = '/tmp/workspaces/parent-child' + const childId = `${TEST_REPO_ID}::${childPath}` + const parentId = `${TEST_REPO_ID}::${parentPath}` + const metaById: Record = { + [parentId]: makeWorktreeMeta({ + instanceId: 'parent-instance', + displayName: 'parent' + }) + } + const setWorktreeLineage = vi.fn((_worktreeId: string, lineage) => lineage) + const runtimeStore = { + ...store, + getAllWorktreeMeta: () => metaById, + getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], + setWorktreeMeta: (worktreeId: string, meta: Partial) => { + const existing = metaById[worktreeId] ?? makeWorktreeMeta() + metaById[worktreeId] = { ...existing, ...meta } + return metaById[worktreeId] + }, + getWorktreeLineage: () => undefined, + setWorktreeLineage + } + const runtime = new OrcaRuntimeService(runtimeStore as never) + const parentHandle = runtime.preAllocateHandleForPty('pty-parent') + runtime.setOrchestrationDb({ + getDispatchContext: vi.fn(() => undefined), + getTask: vi.fn(() => ({ + id: 'task_creator123', + created_by_terminal_handle: parentHandle + })) + } as never) + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab-parent', + worktreeId: parentId, + title: 'Parent', + activeLeafId: 'pane:1', + layout: null + } + ], + leaves: [ + { + tabId: 'tab-parent', + worktreeId: parentId, + leafId: 'pane:1', + paneRuntimeId: 1, + ptyId: 'pty-parent', + paneTitle: null + } + ] + }) + computeWorktreePathMock.mockReturnValue(childPath) + ensurePathWithinWorkspaceMock.mockReturnValue(childPath) + vi.mocked(listWorktrees) + .mockResolvedValueOnce([ + { + path: parentPath, + head: 'fed', + branch: 'feature/parent', + isBare: false, + isMainWorktree: false + } + ]) + .mockResolvedValueOnce([ + { + path: childPath, + head: 'def', + branch: 'parent-child', + isBare: false, + isMainWorktree: false + } + ]) + + const result = await runtime.createManagedWorktree({ + repoSelector: 'id:repo-1', + name: 'parent-child', + comment: 'Created via orchestration task task_creator123' + }) + + expect(result.lineage).toMatchObject({ + worktreeId: childId, + parentWorktreeId: parentId, + origin: 'orchestration', + capture: { source: 'orchestration-context', confidence: 'inferred' }, + taskId: 'task_creator123' + }) + expect(setWorktreeLineage).toHaveBeenCalledWith( + childId, + expect.objectContaining({ + parentWorktreeInstanceId: 'parent-instance' + }) + ) + }) + it('returns a setup launch payload for CLI-created worktrees when hooks are explicitly enabled', async () => { const runtime = new OrcaRuntimeService(store) const activateWorktree = vi.fn() diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index f52bc0ebc..44ba0c649 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -22,6 +22,8 @@ import type { Repo, StatsSummary, Worktree, + WorktreeLineage, + WorktreeLineageWarning, WorktreeMeta, WorktreeBaseStatusEvent, WorktreeRemoteBranchConflictEvent, @@ -286,6 +288,10 @@ type RuntimeStore = { getWorktreeMeta: Store['getWorktreeMeta'] setWorktreeMeta: Store['setWorktreeMeta'] removeWorktreeMeta: Store['removeWorktreeMeta'] + getWorktreeLineage?: Store['getWorktreeLineage'] + getAllWorktreeLineage?: Store['getAllWorktreeLineage'] + setWorktreeLineage?: Store['setWorktreeLineage'] + removeWorktreeLineage?: Store['removeWorktreeLineage'] getGitHubCache: Store['getGitHubCache'] getWorkspaceSession?: Store['getWorkspaceSession'] getSettings(): { @@ -470,7 +476,69 @@ function omitUndefinedProperties>(value: T): P ) as Partial } -type ResolvedWorktree = Worktree & { git: GitWorktreeInfo } +type ResolvedWorktree = Worktree & { + parentWorktreeId: string | null + childWorktreeIds: string[] + lineage: WorktreeLineage | null + git: GitWorktreeInfo +} + +type WorktreeLineageInput = { + parentWorktree?: string + cwdParentWorktree?: string + noParent?: boolean + callerTerminalHandle?: string + comment?: string + orchestrationContext?: { + parentWorktreeId?: string + orchestrationRunId?: string + taskId?: string + coordinatorHandle?: string + } +} + +type WorktreeLineageResolution = + | { + kind: 'lineage' + parent: ResolvedWorktree + origin: WorktreeLineage['origin'] + capture: WorktreeLineage['capture'] + orchestrationRunId?: string + taskId?: string + coordinatorHandle?: string + createdByTerminalHandle?: string + } + | { + kind: 'none' + warnings: WorktreeLineageWarning[] + } + +type RuntimeWorktreeScanResult = + | { ok: true; worktrees: GitWorktreeInfo[] } + | { ok: false; worktrees: [] } + +type WorktreeLineageCandidate = { + source: 'cwd-context' | 'terminal-context' | 'orchestration-context' + parent: ResolvedWorktree + orchestrationRunId?: string + taskId?: string + coordinatorHandle?: string +} + +function extractOrchestrationTaskId(text?: string): string | undefined { + return text?.match(/\btask_[A-Za-z0-9]+\b/)?.[0] +} + +class RuntimeLineageError extends Error { + code: string + data?: unknown + + constructor(code: string, message: string, data?: unknown) { + super(message) + this.code = code + this.data = data + } +} type ResolvedWorktreeCache = { expiresAt: number @@ -3852,6 +3920,8 @@ export class OrcaRuntimeService { repo: repo?.displayName ?? worktree.repoId, path: worktree.path, branch: worktree.branch, + parentWorktreeId: worktree.parentWorktreeId, + childWorktreeIds: worktree.childWorktreeIds, displayName: worktree.displayName, linkedIssue: worktree.linkedIssue, linkedPR, @@ -5007,6 +5077,7 @@ export class OrcaRuntimeService { setupDecision?: 'run' | 'skip' | 'inherit' createdWithAgent?: TuiAgent startup?: WorktreeStartupLaunch + lineage?: WorktreeLineageInput }): Promise { if (!this.store) { throw new Error('runtime_unavailable') @@ -5022,6 +5093,9 @@ export class OrcaRuntimeService { // Runtime RPC must not fall through to local git against server paths. throw new Error('SSH-backed worktree creation is not supported through runtime RPC yet.') } + const lineageInput = + args.lineage || args.comment ? { ...args.lineage, comment: args.comment } : undefined + const lineageResolution = await this.resolveLineageForWorktreeCreate(lineageInput) const settings = this.store.getSettings() const requestedName = args.name const requestedDisplayName = args.displayName?.trim() || undefined @@ -5137,6 +5211,10 @@ export class OrcaRuntimeService { ? { displayName: requestedName } : {} const meta = this.store.setWorktreeMeta(worktreeId, { + // Why: worktree IDs are path-derived. If a path is deleted outside Orca + // and later recreated, creation must mint a fresh instance identity so + // stale lineage records tied to the old occupant fail validation. + instanceId: randomUUID(), lastActivityAt: now, // See createRemoteWorktree: createdAt grants the new worktree a grace // window in Recent sort so ambient PTY bumps in OTHER worktrees can't @@ -5162,6 +5240,44 @@ export class OrcaRuntimeService { ...(args.comment !== undefined ? { comment: args.comment } : {}) }) const worktree = mergeWorktree(repo.id, created, meta) + let lineage: WorktreeLineage | null = null + const lineageWarnings = lineageResolution.kind === 'none' ? [...lineageResolution.warnings] : [] + if (lineageResolution.kind === 'lineage') { + const childInstanceId = meta.instanceId + const parentInstanceId = lineageResolution.parent.instanceId + if (childInstanceId && parentInstanceId && this.store.setWorktreeLineage) { + lineage = this.store.setWorktreeLineage(worktreeId, { + worktreeId, + worktreeInstanceId: childInstanceId, + parentWorktreeId: lineageResolution.parent.id, + parentWorktreeInstanceId: parentInstanceId, + origin: lineageResolution.origin, + capture: lineageResolution.capture, + ...(lineageResolution.orchestrationRunId + ? { orchestrationRunId: lineageResolution.orchestrationRunId } + : {}), + ...(lineageResolution.taskId ? { taskId: lineageResolution.taskId } : {}), + ...(lineageResolution.coordinatorHandle + ? { coordinatorHandle: lineageResolution.coordinatorHandle } + : {}), + ...(lineageResolution.createdByTerminalHandle + ? { createdByTerminalHandle: lineageResolution.createdByTerminalHandle } + : {}), + createdAt: now + }) + } else { + lineageWarnings.push({ + code: 'LINEAGE_PARENT_CONTEXT_MISSING', + message: + 'Worktree created, but Orca could not record lineage because instance identity was unavailable.', + details: { + childHasInstanceId: Boolean(childInstanceId), + parentHasInstanceId: Boolean(parentInstanceId), + storeSupportsLineage: Boolean(this.store.setWorktreeLineage) + } + }) + } + } if ( settings.experimentalWorktreeSymlinks && @@ -5296,7 +5412,14 @@ export class OrcaRuntimeService { } } return { - worktree, + worktree: { + ...worktree, + parentWorktreeId: lineage?.parentWorktreeId ?? null, + childWorktreeIds: [], + lineage, + git: created + }, + ...(lineageInput ? { lineage, warnings: lineageWarnings } : {}), ...(setup ? { setup } : {}), ...(warning ? { warning } : {}) } @@ -5641,17 +5764,53 @@ export class OrcaRuntimeService { return { base, behind: drift.behind, recentSubjects } } - async updateManagedWorktreeMeta(worktreeSelector: string, updates: Partial) { + async updateManagedWorktreeMeta( + worktreeSelector: string, + updates: Partial & { + lineage?: { + parentWorktree?: string + noParent?: boolean + } + } + ) { if (!this.store) { throw new Error('runtime_unavailable') } const worktree = await this.resolveWorktreeSelector(worktreeSelector) - const meta = this.store.setWorktreeMeta(worktree.id, omitUndefinedProperties(updates)) + const { lineage, ...metaUpdates } = updates + if (lineage?.noParent === true) { + this.store.removeWorktreeLineage?.(worktree.id) + } else if (lineage?.parentWorktree) { + const parent = await this.resolveWorktreeSelector(lineage.parentWorktree) + this.validateLineageParent(worktree, parent) + if (!worktree.instanceId || !parent.instanceId) { + throw new RuntimeLineageError( + 'LINEAGE_PARENT_CONTEXT_MISSING', + 'Workspace instance identity was unavailable.' + ) + } + if (!this.store.setWorktreeLineage) { + throw new RuntimeLineageError( + 'LINEAGE_PARENT_CONTEXT_MISSING', + 'Workspace lineage storage was unavailable.' + ) + } + this.store.setWorktreeLineage(worktree.id, { + worktreeId: worktree.id, + worktreeInstanceId: worktree.instanceId, + parentWorktreeId: parent.id, + parentWorktreeInstanceId: parent.instanceId, + origin: 'manual', + capture: { source: 'manual-action', confidence: 'explicit' }, + createdAt: Date.now() + }) + } + this.store.setWorktreeMeta(worktree.id, omitUndefinedProperties(metaUpdates)) // Why: unlike renderer-initiated optimistic updates, CLI callers need an // explicit push so the editor refreshes metadata changed outside the UI. this.invalidateResolvedWorktreeCache() this.notifier?.worktreesChanged(worktree.repoId) - return mergeWorktree(worktree.repoId, worktree.git, meta) + return await this.showManagedWorktree(`id:${worktree.id}`) } persistManagedWorktreeSortOrder(orderedIds: string[]): { updated: number } { @@ -6594,6 +6753,305 @@ export class OrcaRuntimeService { throw new Error('selector_not_found') } + private validateLineageParent(child: ResolvedWorktree, parent: ResolvedWorktree): void { + const childWorktreeId = child.id + const parentWorktreeId = parent.id + if (childWorktreeId === parentWorktreeId) { + throw new RuntimeLineageError('LINEAGE_PARENT_CYCLE', 'A workspace cannot parent itself.') + } + const instanceByWorktreeId = new Map( + this.resolvedWorktreeCache?.worktrees.map((worktree) => [ + worktree.id, + worktree.instanceId + ]) ?? [ + [child.id, child.instanceId], + [parent.id, parent.instanceId] + ] + ) + let cursor: string | undefined = parentWorktreeId + const visited = new Set([childWorktreeId]) + while (cursor) { + if (visited.has(cursor)) { + throw new RuntimeLineageError( + 'LINEAGE_PARENT_CYCLE', + 'Parent workspace would create a lineage cycle.' + ) + } + visited.add(cursor) + const lineage = this.store?.getWorktreeLineage?.(cursor) + if (!lineage) { + break + } + const cursorInstanceId = instanceByWorktreeId.get(cursor) + const parentInstanceId = instanceByWorktreeId.get(lineage.parentWorktreeId) + if ( + cursorInstanceId !== lineage.worktreeInstanceId || + parentInstanceId !== lineage.parentWorktreeInstanceId + ) { + break + } + cursor = lineage.parentWorktreeId + } + } + + private async resolveLineageForWorktreeCreate( + input?: WorktreeLineageInput + ): Promise { + if (!input) { + return { kind: 'none', warnings: [] } + } + + if (input.noParent === true && input.parentWorktree) { + throw new RuntimeLineageError( + 'LINEAGE_PARENT_CONTEXT_CONFLICT', + 'Choose either --parent-worktree or --no-parent, not both.' + ) + } + + if (input.noParent === true) { + return { kind: 'none', warnings: [] } + } + + if (input.parentWorktree) { + try { + const parent = await this.resolveWorktreeSelector(input.parentWorktree) + return { + kind: 'lineage', + parent, + origin: 'cli', + capture: { source: 'explicit-cli-flag', confidence: 'explicit' } + } + } catch { + throw new RuntimeLineageError( + 'LINEAGE_PARENT_NOT_FOUND', + 'Parent workspace was not found.', + { + nextSteps: [ + 'Run `orca worktree list` and pass a valid --parent-worktree selector.', + 'Retry with --no-parent to create without lineage.' + ] + } + ) + } + } + + const warnings: WorktreeLineageWarning[] = [] + const candidates: WorktreeLineageCandidate[] = [] + let cwdCandidate: WorktreeLineageCandidate | null = null + let terminalContextResolved = false + + if (input.orchestrationContext?.parentWorktreeId) { + try { + candidates.push({ + source: 'orchestration-context', + parent: await this.resolveWorktreeSelector( + `id:${input.orchestrationContext.parentWorktreeId}` + ) + }) + } catch { + // Keep creation recoverable; the warning below covers missing inferred context. + } + } + + const commentTaskId = extractOrchestrationTaskId(input.comment) + if (commentTaskId) { + const candidate = await this.resolveLineageCandidateForTaskId(commentTaskId) + if (candidate) { + candidates.push(candidate) + } + } + + if (input.callerTerminalHandle) { + try { + const terminal = await this.showTerminal(input.callerTerminalHandle) + const terminalParent = await this.resolveWorktreeSelector(`id:${terminal.worktreeId}`) + const activeDispatch = this._orchestrationDb?.getActiveDispatchForTerminal( + input.callerTerminalHandle + ) + const activeRun = this._orchestrationDb?.getActiveCoordinatorRun() + if (activeDispatch) { + candidates.push({ + source: 'orchestration-context', + parent: terminalParent, + taskId: activeDispatch.task_id, + ...(activeRun + ? { + orchestrationRunId: activeRun.id, + coordinatorHandle: activeRun.coordinator_handle + } + : {}) + }) + } else { + candidates.push({ + source: 'terminal-context', + parent: terminalParent + }) + } + terminalContextResolved = true + } catch { + // Why: terminal handles can go stale during reloads or SSH reconnects. + // A valid orchestration parent is still authoritative, so keep resolving + // other inferred candidates instead of dropping lineage completely. + warnings.push({ + code: 'LINEAGE_PARENT_CONTEXT_MISSING', + message: + 'Worktree created, but Orca could not validate the caller terminal as a parent workspace.', + details: { callerTerminalHandle: input.callerTerminalHandle } + }) + } + } + + if (input.cwdParentWorktree) { + try { + cwdCandidate = { + source: 'cwd-context', + parent: await this.resolveWorktreeSelector(input.cwdParentWorktree) + } + } catch { + warnings.push({ + code: 'LINEAGE_PARENT_CONTEXT_MISSING', + message: + 'Worktree created, but Orca could not validate the current directory as a parent workspace.', + details: { cwdParentWorktree: input.cwdParentWorktree } + }) + } + } + + if (candidates.length === 0 && cwdCandidate) { + candidates.push(cwdCandidate) + } + + if (candidates.length === 0) { + return { kind: 'none', warnings } + } + + const [first] = candidates + const conflict = candidates.find((candidate) => candidate.parent.id !== first.parent.id) + if (conflict) { + return { + kind: 'none', + warnings: [ + { + code: 'LINEAGE_PARENT_CONTEXT_CONFLICT', + message: 'Worktree created, but Orca could not prove which parent workspace caused it.', + details: { + terminalParentWorktreeId: candidates.find((c) => c.source === 'terminal-context') + ?.parent.id, + orchestrationParentWorktreeId: candidates.find( + (c) => c.source === 'orchestration-context' + )?.parent.id + } + } + ] + } + } + + const preferred = + candidates.find((candidate) => candidate.source === 'orchestration-context') ?? first + return { + kind: 'lineage', + parent: preferred.parent, + origin: preferred.source === 'orchestration-context' ? 'orchestration' : 'cli', + capture: { source: preferred.source, confidence: 'inferred' }, + ...((preferred.orchestrationRunId ?? input.orchestrationContext?.orchestrationRunId) + ? { + orchestrationRunId: + preferred.orchestrationRunId ?? input.orchestrationContext?.orchestrationRunId + } + : {}), + ...((preferred.taskId ?? input.orchestrationContext?.taskId) + ? { taskId: preferred.taskId ?? input.orchestrationContext?.taskId } + : {}), + ...((preferred.coordinatorHandle ?? input.orchestrationContext?.coordinatorHandle) + ? { + coordinatorHandle: + preferred.coordinatorHandle ?? input.orchestrationContext?.coordinatorHandle + } + : {}), + ...(terminalContextResolved && input.callerTerminalHandle + ? { createdByTerminalHandle: input.callerTerminalHandle } + : {}) + } + } + + private async resolveLineageCandidateForTaskId( + taskId: string + ): Promise { + const db = this.getOrchestrationDbIfAvailable() + const dispatch = db?.getDispatchContext(taskId) + // Why: agent-created task records may never be dispatched, but the + // creating terminal still identifies the parent workspace for descendants. + const parentHandle = + dispatch?.assignee_handle ?? db?.getTask(taskId)?.created_by_terminal_handle + if (!parentHandle) { + return null + } + try { + const terminal = await this.showTerminal(parentHandle) + return { + source: 'orchestration-context', + parent: await this.resolveWorktreeSelector(`id:${terminal.worktreeId}`), + taskId + } + } catch { + return null + } + } + + private getOrchestrationDbIfAvailable(): OrchestrationDb | null { + try { + return this._orchestrationDb ?? this.getOrchestrationDb() + } catch { + return this._orchestrationDb + } + } + + async hydrateInferredWorktreeLineage(): Promise { + const store = this.store + if ( + !store || + typeof store.getWorktreeLineage !== 'function' || + typeof store.setWorktreeLineage !== 'function' + ) { + return + } + + const worktrees = await this.listResolvedWorktrees() + for (const worktree of worktrees) { + if (store.getWorktreeLineage(worktree.id) || !worktree.instanceId) { + continue + } + const taskId = extractOrchestrationTaskId(worktree.comment) + if (!taskId) { + continue + } + const candidate = await this.resolveLineageCandidateForTaskId(taskId) + if (!candidate?.parent.instanceId || candidate.parent.id === worktree.id) { + continue + } + try { + this.validateLineageParent(worktree, candidate.parent) + } catch { + continue + } + store.setWorktreeLineage(worktree.id, { + worktreeId: worktree.id, + worktreeInstanceId: worktree.instanceId, + parentWorktreeId: candidate.parent.id, + parentWorktreeInstanceId: candidate.parent.instanceId, + origin: 'orchestration', + capture: { source: 'orchestration-context', confidence: 'inferred' }, + taskId, + createdAt: Date.now() + }) + } + } + + async listWorktreeLineage(): Promise> { + await this.hydrateInferredWorktreeLineage() + return this.store?.getAllWorktreeLineage?.() ?? {} + } + private async resolveRepoSelector(selector: string): Promise { if (!this.store) { throw new Error('repo_not_found') @@ -6661,21 +7119,35 @@ export class OrcaRuntimeService { return [] } const now = Date.now() - const metaById = this.store.getAllWorktreeMeta() const perRepoWorktrees = await Promise.all( this.store.getRepos().map(async (repo) => { // Why: mobile startup RPCs share this path. A slow repo scan should // degrade one repo's metadata, not block all terminal/session loading. - const gitWorktrees = await withTimeout( - listRepoWorktrees(repo), + const scan = await withTimeout( + this.listRepoWorktreesForResolution(repo), RESOLVED_WORKTREE_REPO_TIMEOUT_MS, - [] + { ok: false, worktrees: [] } ) + const gitWorktrees = scan.worktrees + if (scan.ok) { + this.pruneLineageForMissingRepoWorktrees(repo, gitWorktrees) + } + const metaById = this.store?.getAllWorktreeMeta() ?? {} return gitWorktrees.map((gitWorktree) => { const worktreeId = `${repo.id}::${gitWorktree.path}` - const merged = mergeWorktree(repo.id, gitWorktree, metaById[worktreeId], repo.displayName) + // Why: lineage validation needs a durable instance ID even when the + // runtime sees a workspace before the renderer's discovery-stamp path. + const existingMeta = metaById[worktreeId] + const meta = + existingMeta && existingMeta.instanceId + ? existingMeta + : this.store?.setWorktreeMeta(worktreeId, {}) + const merged = mergeWorktree(repo.id, gitWorktree, meta, repo.displayName) return { ...merged, + parentWorktreeId: null, + childWorktreeIds: [], + lineage: null, git: { path: gitWorktree.path, head: gitWorktree.head, @@ -6689,7 +7161,7 @@ export class OrcaRuntimeService { }) }) ) - const worktrees = perRepoWorktrees.flat() + const worktrees = this.attachLineageToResolvedWorktrees(perRepoWorktrees.flat()) // Why: terminal polling can be frequent, but git worktree state is still // allowed to change outside Orca. A short TTL avoids shelling out on every // read without pretending the cache is authoritative for long. @@ -6702,6 +7174,86 @@ export class OrcaRuntimeService { return worktrees } + private attachLineageToResolvedWorktrees(worktrees: ResolvedWorktree[]): ResolvedWorktree[] { + const lineageById = this.store?.getAllWorktreeLineage?.() ?? {} + const worktreeById = new Map(worktrees.map((worktree) => [worktree.id, worktree])) + const validLineageByChildId = new Map() + const childIdsByParentId = new Map() + + for (const [childId, lineage] of Object.entries(lineageById)) { + const child = worktreeById.get(childId) + const parent = worktreeById.get(lineage.parentWorktreeId) + if ( + !child || + !parent || + child.instanceId !== lineage.worktreeInstanceId || + parent.instanceId !== lineage.parentWorktreeInstanceId + ) { + // Why: worktree IDs are path-derived. Instance checks keep replacement + // checkouts from appearing as children of stale same-path lineage. + continue + } + validLineageByChildId.set(childId, lineage) + const children = childIdsByParentId.get(lineage.parentWorktreeId) ?? [] + children.push(childId) + childIdsByParentId.set(lineage.parentWorktreeId, children) + } + + return worktrees.map((worktree) => { + const lineage = validLineageByChildId.get(worktree.id) ?? null + return { + ...worktree, + parentWorktreeId: lineage?.parentWorktreeId ?? null, + childWorktreeIds: childIdsByParentId.get(worktree.id) ?? [], + lineage + } + }) + } + + private pruneLineageForMissingRepoWorktrees(repo: Repo, gitWorktrees: GitWorktreeInfo[]): void { + const store = this.store + if ( + !store || + typeof store.getAllWorktreeLineage !== 'function' || + typeof store.removeWorktreeLineage !== 'function' + ) { + return + } + const liveIds = new Set(gitWorktrees.map((worktree) => `${repo.id}::${worktree.path}`)) + const repoPrefix = `${repo.id}::` + for (const [childId, lineage] of Object.entries(store.getAllWorktreeLineage())) { + if (childId.startsWith(repoPrefix) && !liveIds.has(childId)) { + // Why: runtime selector scans can be the only scan before a path is + // reused. Once a successful scan proves the child is gone, stale + // lineage must not survive into the replacement checkout. + store.removeWorktreeLineage(childId) + } + if ( + lineage.parentWorktreeId.startsWith(repoPrefix) && + !liveIds.has(lineage.parentWorktreeId) + ) { + const parentMeta = store.getWorktreeMeta(lineage.parentWorktreeId) + if (!parentMeta || parentMeta.instanceId === lineage.parentWorktreeInstanceId) { + // Why: preserving child lineage powers the repair UI, but a missing + // parent path only needs one fresh identity to keep same-path + // replacement checkouts from validating old lineage. + store.setWorktreeMeta(lineage.parentWorktreeId, { instanceId: randomUUID() }) + } + } + } + } + + private async listRepoWorktreesForResolution(repo: Repo): Promise { + if (!repo.connectionId) { + return { ok: true, worktrees: await listRepoWorktrees(repo) } + } + const provider = getSshGitProvider(repo.connectionId) + if (!provider) { + return { ok: false, worktrees: [] } + } + return { ok: true, worktrees: await provider.listWorktrees(repo.path) } + } + private async getResolvedWorktreeMap(): Promise> { return new Map((await this.listResolvedWorktrees()).map((worktree) => [worktree.id, worktree])) } diff --git a/src/main/runtime/orchestration/db.test.ts b/src/main/runtime/orchestration/db.test.ts index 9e9d5d941..2f6b7f089 100644 --- a/src/main/runtime/orchestration/db.test.ts +++ b/src/main/runtime/orchestration/db.test.ts @@ -132,6 +132,17 @@ describe('OrchestrationDb', () => { expect(task.deps).toBe('[]') }) + it('persists the creating terminal handle for task-created worktrees', () => { + const d = createDb() + const task = d.createTask({ + spec: 'spawn related workspace', + createdByTerminalHandle: 'term_creator' + }) + + expect(task.created_by_terminal_handle).toBe('term_creator') + expect(d.getTask(task.id)?.created_by_terminal_handle).toBe('term_creator') + }) + it('creates a task with deps as pending', () => { const d = createDb() const parent = d.createTask({ spec: 'parent' }) diff --git a/src/main/runtime/orchestration/db.ts b/src/main/runtime/orchestration/db.ts index e8daa9f17..8bfe15991 100644 --- a/src/main/runtime/orchestration/db.ts +++ b/src/main/runtime/orchestration/db.ts @@ -36,10 +36,10 @@ function generateId(prefix: string): string { // Why: v1 → v2 added `'heartbeat'` to messages.type CHECK + `last_heartbeat_at` // column (preamble-hardening PR). v2 → v3 adds `delivered_at` column so // push-on-idle can distinguish queued-but-undelivered from user-acknowledged -// messages without touching the `read` bit (check-wait PR). Bumping together -// since both PRs ship in the same release — existing on-disk DBs must clear -// both gaps in one atomic migration. -const SCHEMA_VERSION = 3 +// messages without touching the `read` bit (check-wait PR). v3 → v4 records +// the terminal that created a task so task-record worktree creation can infer +// the parent workspace even when no dispatch context exists. +const SCHEMA_VERSION = 4 export class OrchestrationDb { private db: Database.Database @@ -83,6 +83,7 @@ export class OrchestrationDb { CREATE TABLE IF NOT EXISTS tasks ( id TEXT PRIMARY KEY, parent_id TEXT, + created_by_terminal_handle TEXT, spec TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ( @@ -227,6 +228,11 @@ export class OrchestrationDb { this.db.exec(`ALTER TABLE messages ADD COLUMN delivered_at TEXT`) } } + if (current < 4) { + if (!this.hasColumn('tasks', 'created_by_terminal_handle')) { + this.db.exec(`ALTER TABLE tasks ADD COLUMN created_by_terminal_handle TEXT`) + } + } this.db.pragma(`user_version = ${SCHEMA_VERSION}`) this.db.exec('COMMIT') @@ -367,14 +373,28 @@ export class OrchestrationDb { // ── Tasks ── - createTask(task: { spec: string; deps?: string[]; parentId?: string }): TaskRow { + createTask(task: { + spec: string + deps?: string[] + parentId?: string + createdByTerminalHandle?: string + }): TaskRow { const id = generateId('task') const depsJson = JSON.stringify(task.deps ?? []) const hasDeps = (task.deps ?? []).length > 0 const status: TaskStatus = hasDeps ? 'pending' : 'ready' this.db - .prepare('INSERT INTO tasks (id, parent_id, spec, status, deps) VALUES (?, ?, ?, ?, ?)') - .run(id, task.parentId ?? null, task.spec, status, depsJson) + .prepare( + 'INSERT INTO tasks (id, parent_id, created_by_terminal_handle, spec, status, deps) VALUES (?, ?, ?, ?, ?, ?)' + ) + .run( + id, + task.parentId ?? null, + task.createdByTerminalHandle ?? null, + task.spec, + status, + depsJson + ) return this.db.prepare('SELECT * FROM tasks WHERE id = ?').get(id) as TaskRow } diff --git a/src/main/runtime/orchestration/types.ts b/src/main/runtime/orchestration/types.ts index 03a31391c..f966368b9 100644 --- a/src/main/runtime/orchestration/types.ts +++ b/src/main/runtime/orchestration/types.ts @@ -37,6 +37,7 @@ export type MessageRow = { export type TaskRow = { id: string parent_id: string | null + created_by_terminal_handle: string | null spec: string status: TaskStatus deps: string diff --git a/src/main/runtime/rpc/errors.test.ts b/src/main/runtime/rpc/errors.test.ts new file mode 100644 index 000000000..bf11965bf --- /dev/null +++ b/src/main/runtime/rpc/errors.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest' +import { mapRuntimeError } from './errors' + +class LineageError extends Error { + code = 'LINEAGE_PARENT_NOT_FOUND' + data = { + nextSteps: ['Run `orca worktree list`.', 'Retry with --no-parent.'] + } +} + +describe('mapRuntimeError', () => { + it('preserves structured lineage error codes and data for CLI recovery hints', () => { + const response = mapRuntimeError( + 'req_1', + { runtimeId: 'runtime-1' }, + new LineageError('Parent workspace was not found.') + ) + + expect(response).toEqual({ + id: 'req_1', + ok: false, + error: { + code: 'LINEAGE_PARENT_NOT_FOUND', + message: 'Parent workspace was not found.', + data: { + nextSteps: ['Run `orca worktree list`.', 'Retry with --no-parent.'] + } + }, + _meta: { runtimeId: 'runtime-1' } + }) + }) +}) diff --git a/src/main/runtime/rpc/errors.ts b/src/main/runtime/rpc/errors.ts index da19f1cba..98937e6a1 100644 --- a/src/main/runtime/rpc/errors.ts +++ b/src/main/runtime/rpc/errors.ts @@ -59,6 +59,20 @@ export function mapRuntimeError(id: string, meta: RpcEnvelopeMeta, error: unknow ) { return errorResponse(id, meta, (error as { code: string }).code, message) } + if ( + error instanceof Error && + 'code' in error && + typeof (error as { code: unknown }).code === 'string' && + (error as { code: string }).code.startsWith('LINEAGE_') + ) { + return errorResponse( + id, + meta, + (error as { code: string }).code, + message, + (error as { data?: unknown }).data + ) + } if (RUNTIME_PASSTHROUGH_CODES.has(message)) { return errorResponse(id, meta, message, message) } diff --git a/src/main/runtime/rpc/methods/orchestration.test.ts b/src/main/runtime/rpc/methods/orchestration.test.ts index 93856e98a..27cc27cff 100644 --- a/src/main/runtime/rpc/methods/orchestration.test.ts +++ b/src/main/runtime/rpc/methods/orchestration.test.ts @@ -477,6 +477,16 @@ describe('orchestration RPC methods', () => { expect(result.task.status).toBe('pending') }) + it('records the caller terminal handle when creating a task', async () => { + setup() + const result = (await call('orchestration.taskCreate', { + spec: 'spawn related workspace', + callerTerminalHandle: 'term_creator' + })) as { task: { id: string } } + + expect(db.getTask(result.task.id)?.created_by_terminal_handle).toBe('term_creator') + }) + it('rejects invalid deps JSON', async () => { setup() await expect( diff --git a/src/main/runtime/rpc/methods/orchestration.ts b/src/main/runtime/rpc/methods/orchestration.ts index 0fb5a6f86..b2d31e989 100644 --- a/src/main/runtime/rpc/methods/orchestration.ts +++ b/src/main/runtime/rpc/methods/orchestration.ts @@ -81,7 +81,8 @@ const InboxParams = z.object({ const TaskCreateParams = z.object({ spec: requiredString('Missing --spec'), deps: OptionalString, - parent: OptionalString + parent: OptionalString, + callerTerminalHandle: OptionalString }) const TaskListParams = z.object({ @@ -328,7 +329,8 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [ const task = db.createTask({ spec: params.spec, deps, - parentId: params.parent + parentId: params.parent, + createdByTerminalHandle: params.callerTerminalHandle }) return { task } } diff --git a/src/main/runtime/rpc/methods/worktree.test.ts b/src/main/runtime/rpc/methods/worktree.test.ts index e0da750b5..d9a9d4ddd 100644 --- a/src/main/runtime/rpc/methods/worktree.test.ts +++ b/src/main/runtime/rpc/methods/worktree.test.ts @@ -26,7 +26,8 @@ describe('worktree RPC methods', () => { linkedIssue: 123, linkedPR: 456, sparseCheckout: { directories: ['src'], presetId: 'preset-1' }, - pushTarget: { remoteName: 'fork', branchName: 'feature' } + pushTarget: { remoteName: 'fork', branchName: 'feature' }, + parentWorktree: 'id:parent' }) ) @@ -36,6 +37,7 @@ describe('worktree RPC methods', () => { baseBranch: 'origin/main', linkedIssue: 123, linkedPR: 456, + linkedLinearIssue: undefined, comment: undefined, displayName: 'Feature title', sparseCheckout: { directories: ['src'], presetId: 'preset-1' }, @@ -43,10 +45,82 @@ describe('worktree RPC methods', () => { runHooks: false, activate: false, setupDecision: 'skip', - startup: undefined + createdWithAgent: undefined, + startup: undefined, + lineage: { + parentWorktree: 'id:parent', + noParent: false, + callerTerminalHandle: undefined, + orchestrationContext: undefined + } }) }) + it('rejects worktree.create when both parent and no-parent are supplied', async () => { + const runtime = { + getRuntimeId: () => 'test-runtime', + createManagedWorktree: vi.fn() + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: WORKTREE_METHODS }) + + const response = await dispatcher.dispatch( + makeRequest('worktree.create', { + repo: 'repo-1', + name: 'child', + parentWorktree: 'id:parent', + noParent: true + }) + ) + + expect(response).toMatchObject({ ok: false }) + expect(JSON.stringify(response)).toContain('Choose either --parent-worktree or --no-parent') + expect(runtime.createManagedWorktree).not.toHaveBeenCalled() + }) + + it('rejects worktree.set when both parent and no-parent are supplied', async () => { + const runtime = { + getRuntimeId: () => 'test-runtime', + updateManagedWorktreeMeta: vi.fn() + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: WORKTREE_METHODS }) + + const response = await dispatcher.dispatch( + makeRequest('worktree.set', { + worktree: 'id:child', + parentWorktree: 'id:parent', + noParent: true + }) + ) + + expect(response).toMatchObject({ ok: false }) + expect(JSON.stringify(response)).toContain('Choose either --parent-worktree or --no-parent') + expect(runtime.updateManagedWorktreeMeta).not.toHaveBeenCalled() + }) + + it('lists raw worktree lineage through the runtime server', async () => { + const lineage = { + 'repo::/child': { + worktreeId: 'repo::/child', + worktreeInstanceId: 'child-instance', + parentWorktreeId: 'repo::/missing-parent', + parentWorktreeInstanceId: 'parent-instance', + origin: 'manual', + capture: { source: 'manual-action', confidence: 'explicit' }, + createdAt: 1 + } + } + const runtime = { + getRuntimeId: () => 'test-runtime', + listWorktreeLineage: vi.fn().mockResolvedValue(lineage) + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: WORKTREE_METHODS }) + + const response = await dispatcher.dispatch(makeRequest('worktree.lineageList')) + + expect(runtime.listWorktreeLineage).toHaveBeenCalled() + expect(response).toMatchObject({ ok: true, result: { lineage } }) + }) + it('persists smart sort order on the runtime server', async () => { const runtime = { getRuntimeId: () => 'test-runtime', diff --git a/src/main/runtime/rpc/methods/worktree.ts b/src/main/runtime/rpc/methods/worktree.ts index ee3de8f36..17922acb7 100644 --- a/src/main/runtime/rpc/methods/worktree.ts +++ b/src/main/runtime/rpc/methods/worktree.ts @@ -29,48 +29,69 @@ const WorktreeSelector = z.object({ .pipe(z.string().min(1, 'Missing worktree selector')) }) -const WorktreeCreate = z.object({ - repo: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing repo selector')), - name: OptionalString, - baseBranch: OptionalString, - linkedIssue: TriStateLinkedIssue, - linkedPR: TriStateLinkedIssue, - linkedLinearIssue: z.string().optional(), - comment: OptionalString, - displayName: OptionalString, - sparseCheckout: z - .object({ - directories: z.array(z.string()), - presetId: OptionalString - }) - .optional(), - pushTarget: z - .object({ - remoteName: z.string(), - branchName: z.string(), - remoteUrl: OptionalString - }) - .optional(), - runHooks: OptionalBoolean, - activate: OptionalBoolean, - setupDecision: z - .unknown() - .transform((v) => - typeof v === 'string' && (v === 'run' || v === 'skip' || v === 'inherit') ? v : undefined - ) - .pipe(z.union([z.enum(['run', 'skip', 'inherit']), z.undefined()])) - .optional(), - // Why: mobile clients pass a startup command (e.g. 'claude') so the first - // terminal pane launches the selected agent instead of an idle shell. - startupCommand: OptionalString, - createdWithAgent: z - .unknown() - .transform((value) => (isTuiAgent(value) ? value : undefined)) - .optional() -}) +const WorktreeCreate = z + .object({ + repo: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing repo selector')), + name: OptionalString, + baseBranch: OptionalString, + linkedIssue: TriStateLinkedIssue, + linkedPR: TriStateLinkedIssue, + linkedLinearIssue: z.string().optional(), + comment: OptionalString, + displayName: OptionalString, + sparseCheckout: z + .object({ + directories: z.array(z.string()), + presetId: OptionalString + }) + .optional(), + pushTarget: z + .object({ + remoteName: z.string(), + branchName: z.string(), + remoteUrl: OptionalString + }) + .optional(), + runHooks: OptionalBoolean, + activate: OptionalBoolean, + parentWorktree: OptionalString, + cwdParentWorktree: OptionalString, + noParent: OptionalBoolean, + callerTerminalHandle: OptionalString, + orchestrationContext: z + .object({ + parentWorktreeId: OptionalString, + orchestrationRunId: OptionalString, + taskId: OptionalString, + coordinatorHandle: OptionalString + }) + .optional(), + setupDecision: z + .unknown() + .transform((v) => + typeof v === 'string' && (v === 'run' || v === 'skip' || v === 'inherit') ? v : undefined + ) + .pipe(z.union([z.enum(['run', 'skip', 'inherit']), z.undefined()])) + .optional(), + // Why: mobile clients pass a startup command (e.g. 'claude') so the first + // terminal pane launches the selected agent instead of an idle shell. + startupCommand: OptionalString, + createdWithAgent: z + .unknown() + .transform((value) => (isTuiAgent(value) ? value : undefined)) + .optional() + }) + .superRefine((params, ctx) => { + if (params.parentWorktree && params.noParent === true) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'Choose either --parent-worktree or --no-parent, not both.' + }) + } + }) const WorktreeSet = WorktreeSelector.extend({ displayName: OptionalString, @@ -97,7 +118,16 @@ const WorktreeSet = WorktreeSelector.extend({ remoteUrl: OptionalString }) .optional(), - diffComments: z.array(z.unknown()).optional() + diffComments: z.array(z.unknown()).optional(), + parentWorktree: OptionalString, + noParent: OptionalBoolean +}).superRefine((params, ctx) => { + if (params.parentWorktree && params.noParent === true) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'Choose either --parent-worktree or --no-parent, not both.' + }) + } }) const WorktreeRemove = WorktreeSelector.extend({ @@ -129,6 +159,11 @@ export const WORKTREE_METHODS: RpcMethod[] = [ params: WorktreeListParams, handler: async (params, { runtime }) => runtime.listManagedWorktrees(params.repo, params.limit) }), + defineMethod({ + name: 'worktree.lineageList', + params: null, + handler: async (_params, { runtime }) => ({ lineage: await runtime.listWorktreeLineage() }) + }), defineMethod({ name: 'worktree.show', params: WorktreeSelector, @@ -165,7 +200,14 @@ export const WORKTREE_METHODS: RpcMethod[] = [ activate: params.activate === true, setupDecision: params.setupDecision, createdWithAgent: params.createdWithAgent, - startup: params.startupCommand ? { command: params.startupCommand } : undefined + startup: params.startupCommand ? { command: params.startupCommand } : undefined, + lineage: { + parentWorktree: params.parentWorktree, + ...(params.cwdParentWorktree ? { cwdParentWorktree: params.cwdParentWorktree } : {}), + noParent: params.noParent === true, + callerTerminalHandle: params.callerTerminalHandle, + orchestrationContext: params.orchestrationContext + } }) }), defineMethod({ @@ -189,7 +231,14 @@ export const WORKTREE_METHODS: RpcMethod[] = [ sparsePresetId: params.sparsePresetId, baseRef: params.baseRef, pushTarget: params.pushTarget, - diffComments: params.diffComments + diffComments: params.diffComments, + lineage: + params.parentWorktree || params.noParent === true + ? { + parentWorktree: params.parentWorktree, + noParent: params.noParent === true + } + : undefined } as Parameters[1]) }) }), diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 0fdce54eb..576a56ab9 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -87,6 +87,7 @@ import type { UpdateStatus, Worktree, WorktreeBaseStatusEvent, + WorktreeLineage, WorktreeMeta, WorktreeRemoteBranchConflictEvent, WorktreeSetupLaunch, @@ -586,6 +587,12 @@ export type PreloadApi = { }) => Promise<{ baseBranch: string } | { error: string }> remove: (args: { worktreeId: string; force?: boolean; skipArchive?: boolean }) => Promise updateMeta: (args: { worktreeId: string; updates: Partial }) => Promise + listLineage: () => Promise> + updateLineage: (args: { + worktreeId: string + parentWorktreeId?: string + noParent?: boolean + }) => Promise persistSortOrder: (args: { orderedIds: string[] }) => Promise onChanged: (callback: (data: { repoId: string }) => void) => () => void onBaseStatus: (callback: (data: WorktreeBaseStatusEvent) => void) => () => void diff --git a/src/preload/index.ts b/src/preload/index.ts index f6348d1b7..4ecf67c7b 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -465,6 +465,15 @@ const api = { updates: Record }): Promise => ipcRenderer.invoke('worktrees:updateMeta', args), + listLineage: (): Promise> => + ipcRenderer.invoke('worktrees:listLineage'), + + updateLineage: (args: { + worktreeId: string + parentWorktreeId?: string + noParent?: boolean + }): Promise => ipcRenderer.invoke('worktrees:updateLineage', args), + persistSortOrder: (args: { orderedIds: string[] }): Promise => ipcRenderer.invoke('worktrees:persistSortOrder', args), diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 6a7a0e960..a1352071a 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -220,6 +220,7 @@ function App(): React.JSX.Element { toggleSidebar: s.toggleSidebar, fetchRepos: s.fetchRepos, fetchAllWorktrees: s.fetchAllWorktrees, + fetchWorktreeLineage: s.fetchWorktreeLineage, fetchSettings: s.fetchSettings, initGitHubCache: s.initGitHubCache, refreshAllGitHub: s.refreshAllGitHub, @@ -320,6 +321,7 @@ function App(): React.JSX.Element { const sidebarWidth = useAppStore((s) => s.sidebarWidth) const sidebarOpen = useAppStore((s) => s.sidebarOpen) const groupBy = useAppStore((s) => s.groupBy) + const showWorkspaceLineage = useAppStore((s) => s.showWorkspaceLineage) const sortBy = useAppStore((s) => s.sortBy) const showActiveOnly = useAppStore((s) => s.showActiveOnly) const hideDefaultBranchWorkspace = useAppStore((s) => s.hideDefaultBranchWorkspace) @@ -408,6 +410,7 @@ function App(): React.JSX.Element { await actions.fetchSettings() await actions.fetchRepos() await actions.fetchAllWorktrees() + await actions.fetchWorktreeLineage() const persistedUI = await window.api.ui.get() uiHydrated = hydratePersistedUIAfterStartupRead({ persistedUI, @@ -782,6 +785,7 @@ function App(): React.JSX.Element { sidebarWidth, rightSidebarWidth, groupBy, + showWorkspaceLineage, sortBy, showActiveOnly, hideDefaultBranchWorkspace, @@ -801,6 +805,7 @@ function App(): React.JSX.Element { sidebarWidth, rightSidebarWidth, groupBy, + showWorkspaceLineage, sortBy, showActiveOnly, hideDefaultBranchWorkspace, diff --git a/src/renderer/src/components/sidebar/SidebarHeader.tsx b/src/renderer/src/components/sidebar/SidebarHeader.tsx index 57ff07b79..1cd6b264c 100644 --- a/src/renderer/src/components/sidebar/SidebarHeader.tsx +++ b/src/renderer/src/components/sidebar/SidebarHeader.tsx @@ -73,6 +73,8 @@ const SidebarHeader = React.memo(function SidebarHeader() { const setSortBy = useAppStore((s) => s.setSortBy) const groupBy = useAppStore((s) => s.groupBy) const setGroupBy = useAppStore((s) => s.setGroupBy) + const showWorkspaceLineage = useAppStore((s) => s.showWorkspaceLineage) + const setShowWorkspaceLineage = useAppStore((s) => s.setShowWorkspaceLineage) const clearWorkspaceBoardHoverClose = useCallback(() => { if (workspaceBoardHoverCloseTimerRef.current === null) { @@ -222,6 +224,15 @@ const SidebarHeader = React.memo(function SidebarHeader() { + + setShowWorkspaceLineage(Boolean(checked))} + onSelect={(e) => e.preventDefault()} + > + Nest child workspaces + + Sort by ) => void onActivate?: () => void onSelectionGesture?: (event: React.MouseEvent, worktreeId: string) => boolean onContextMenuSelect?: (event: React.MouseEvent) => readonly Worktree[] @@ -61,7 +70,13 @@ const WorktreeCard = React.memo(function WorktreeCard({ onActivate, onSelectionGesture, onContextMenuSelect, - hideRepoBadge + hideRepoBadge, + parentLabel, + lineageState, + lineageChildCount = 0, + lineageCollapsed = false, + lineageChildren, + onLineageToggle }: WorktreeCardProps) { const openModal = useAppStore((s) => s.openModal) const updateWorktreeMeta = useAppStore((s) => s.updateWorktreeMeta) @@ -291,6 +306,13 @@ const WorktreeCard = React.memo(function WorktreeCard({ ) const unreadTooltip = worktree.isUnread ? 'Mark read' : 'Mark unread' + const childWorkspaceLabel = `${lineageChildCount} child ${ + lineageChildCount === 1 ? 'workspace' : 'workspaces' + }` + const childWorkspaceShortLabel = `${lineageChildCount} ${ + lineageChildCount === 1 ? 'child' : 'children' + }` + const showLineageChildChip = lineageChildCount > 0 && onLineageToggle !== undefined const handleDragStart = useCallback( (event: React.DragEvent) => { @@ -523,6 +545,23 @@ const WorktreeCard = React.memo(function WorktreeCard({ )} + + {parentLabel && ( + + + + {lineageState === 'missing' ? 'Missing parent' : `from ${parentLabel}`} + + + )} {/* Meta section: Issue / hosted review / Comment @@ -563,6 +602,41 @@ const WorktreeCard = React.memo(function WorktreeCard({ measureElement on each row, so the virtualizer re-measures naturally when agents appear/disappear. */} {cardProps.includes('inline-agents') && } + + {showLineageChildChip && ( +
+ + + + + + {lineageCollapsed ? 'Show child workspaces' : 'Hide child workspaces'} + + +
+ )} + + {lineageChildren &&
{lineageChildren}
} ) diff --git a/src/renderer/src/components/sidebar/WorktreeContextMenu.test.ts b/src/renderer/src/components/sidebar/WorktreeContextMenu.test.ts new file mode 100644 index 000000000..e909eea3d --- /dev/null +++ b/src/renderer/src/components/sidebar/WorktreeContextMenu.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest' +import { + shouldIgnoreNestedWorktreeContextMenuScope, + shouldSuppressContextMenuFollowUpClick +} from './WorktreeContextMenu' + +describe('shouldIgnoreNestedWorktreeContextMenuScope', () => { + it('allows the context menu scope that owns the event target', () => { + const currentScope = {} as EventTarget + const target = { + closest: () => currentScope + } as unknown as EventTarget + + expect(shouldIgnoreNestedWorktreeContextMenuScope(currentScope, target)).toBe(false) + }) + + it('ignores context menu events owned by a nested scope', () => { + const currentScope = {} as EventTarget + const nestedScope = {} as Element + const target = { + closest: () => nestedScope + } as unknown as EventTarget + + expect(shouldIgnoreNestedWorktreeContextMenuScope(currentScope, target)).toBe(true) + }) + + it('ignores context menu events from text nodes inside a nested scope', () => { + const currentScope = {} as EventTarget + const nestedScope = {} as Element + const target = { + parentElement: { + closest: () => nestedScope + } + } as unknown as EventTarget + + expect(shouldIgnoreNestedWorktreeContextMenuScope(currentScope, target)).toBe(true) + }) + + it('allows events from unscoped targets', () => { + const currentScope = {} as EventTarget + const target = { + closest: () => null + } as unknown as EventTarget + + expect(shouldIgnoreNestedWorktreeContextMenuScope(currentScope, target)).toBe(false) + }) +}) + +describe('shouldSuppressContextMenuFollowUpClick', () => { + it('suppresses the click emitted immediately after opening a context menu', () => { + expect(shouldSuppressContextMenuFollowUpClick(1_000, 1_050)).toBe(true) + }) + + it('does not suppress later unrelated clicks', () => { + expect(shouldSuppressContextMenuFollowUpClick(1_000, 1_700)).toBe(false) + }) + + it('does not suppress clicks that predate the context menu timestamp', () => { + expect(shouldSuppressContextMenuFollowUpClick(1_000, 999)).toBe(false) + }) +}) diff --git a/src/renderer/src/components/sidebar/WorktreeContextMenu.tsx b/src/renderer/src/components/sidebar/WorktreeContextMenu.tsx index d8eccb5c8..9a4f4c4f7 100644 --- a/src/renderer/src/components/sidebar/WorktreeContextMenu.tsx +++ b/src/renderer/src/components/sidebar/WorktreeContextMenu.tsx @@ -1,4 +1,5 @@ -import React, { useCallback, useEffect, useMemo, useState } from 'react' +/* eslint-disable max-lines -- Why: this menu keeps row targeting, batch actions, and ctrl-click event guards together so nested worktree menus share one event policy. */ +import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { DropdownMenu, DropdownMenuContent, @@ -23,15 +24,19 @@ import { Pin, PinOff, Kanban, - Trash2 + Trash2, + Unlink, + Workflow } from 'lucide-react' import { useAppStore } from '@/store' -import { useRepoById, useRepoMap } from '@/store/selectors' +import { useRepoById, useRepoMap, useWorktreeMap } from '@/store/selectors' import { cn } from '@/lib/utils' import type { Worktree } from '../../../../shared/types' import { isFolderRepo } from '../../../../shared/repo-kind' import { runWorktreeBatchDelete, runWorktreeDelete } from './delete-worktree-flow' import { runSleepWorktrees } from './sleep-worktree-flow' +import { activateAndRevealWorktree } from '@/lib/worktree-activation' +import { getLineageRenderInfo } from './worktree-list-groups' import { getWorkspaceStatus, getWorkspaceStatusVisualMeta } from './workspace-status' import { WorktreeOpenInSubMenu } from './WorktreeOpenInMenu' @@ -45,6 +50,30 @@ type Props = { const CLOSE_ALL_CONTEXT_MENUS_EVENT = 'orca-close-all-context-menus' const WORKTREE_CONTEXT_MENU_SCOPE_ATTR = 'data-worktree-context-menu-scope' +const CONTEXT_MENU_CLICK_SUPPRESSION_MS = 500 + +function shouldIgnoreNestedWorktreeContextMenuScope( + currentTarget: EventTarget, + target: EventTarget | null +): boolean { + const maybeScopedTarget = target as { + closest?: (selector: string) => Element | null + parentElement?: { closest?: (selector: string) => Element | null } + } | null + const scopeSelector = `[${WORKTREE_CONTEXT_MENU_SCOPE_ATTR}]` + const closestScope = + maybeScopedTarget?.closest?.(scopeSelector) ?? + maybeScopedTarget?.parentElement?.closest?.(scopeSelector) + // Why: lineage child previews live inside the parent card DOM but own their + // context menu target. The parent must ignore only those nested scopes. + return closestScope != null && closestScope !== currentTarget +} + +function shouldSuppressContextMenuFollowUpClick(contextMenuOpenedAt: number, now: number): boolean { + return ( + now - contextMenuOpenedAt >= 0 && now - contextMenuOpenedAt <= CONTEXT_MENU_CLICK_SUPPRESSION_MS + ) +} const WorktreeContextMenu = React.memo(function WorktreeContextMenu({ worktree, @@ -64,10 +93,14 @@ const WorktreeContextMenu = React.memo(function WorktreeContextMenu({ const isDeleting = deleteState?.isDeleting ?? false const isFolder = repo ? isFolderRepo(repo) : false const repoMap = useRepoMap() + const worktreeMap = useWorktreeMap() + const worktreeLineageById = useAppStore((s) => s.worktreeLineageById) + const updateWorktreeLineage = useAppStore((s) => s.updateWorktreeLineage) const tabsByWorktree = useAppStore((s) => s.tabsByWorktree) const ptyIdsByTabId = useAppStore((s) => s.ptyIdsByTabId) const browserTabsByWorktree = useAppStore((s) => s.browserTabsByWorktree) const deleteStateByWorktreeId = useAppStore((s) => s.deleteStateByWorktreeId) + const contextMenuOpenedAtRef = useRef(null) const activeContextWorktrees = menuOpen ? contextWorktrees : selectedWorktrees const isMultiContext = activeContextWorktrees.length > 1 const sleepableWorktrees = useMemo( @@ -110,6 +143,15 @@ const WorktreeContextMenu = React.memo(function WorktreeContextMenu({ isMultiContext && batchDeleteWorktrees.length > 0 ? `Delete ${batchDeleteWorktrees.length} Workspace${batchDeleteWorktrees.length === 1 ? '' : 's'}` : 'Delete Selected' + const lineage = worktreeLineageById[worktree.id] + // Why: path-derived worktree IDs can be reused. The menu must honor the same + // instance check as grouped rows before offering navigation to a parent. + const lineageInfo = useMemo( + () => getLineageRenderInfo(worktree, worktreeLineageById, worktreeMap), + [worktree, worktreeLineageById, worktreeMap] + ) + const validParentWorktreeId = lineageInfo.state === 'valid' ? lineageInfo.parent.id : null + const hasAnyContextLineage = activeContextWorktrees.some((item) => worktreeLineageById[item.id]) useEffect(() => { const closeMenu = (): void => setMenuOpen(false) @@ -234,29 +276,59 @@ const WorktreeContextMenu = React.memo(function WorktreeContextMenu({ worktree.repoId ]) - return ( - <> -
{ - const target = event.target - if ( - target instanceof Element && - target.closest(`[${WORKTREE_CONTEXT_MENU_SCOPE_ATTR}]`) - ) { - return - } - event.preventDefault() - window.dispatchEvent(new Event(CLOSE_ALL_CONTEXT_MENUS_EVENT)) - setContextWorktrees(onContextMenuSelect?.(event) ?? selectedWorktrees) - const bounds = event.currentTarget.getBoundingClientRect() - setMenuPoint({ x: event.clientX - bounds.left, y: event.clientY - bounds.top }) - setMenuOpen(true) - }} - > - {children} -
+ const handleOpenParent = useCallback(() => { + if (validParentWorktreeId) { + activateAndRevealWorktree(validParentWorktreeId) + } + }, [validParentWorktreeId]) + const handleRemoveParentLink = useCallback(() => { + void Promise.all( + activeContextWorktrees.map((item) => updateWorktreeLineage(item.id, { noParent: true })) + ) + }, [activeContextWorktrees, updateWorktreeLineage]) + + const suppressOpeningPointerEvent = useCallback((event: React.SyntheticEvent) => { + const contextMenuOpenedAt = contextMenuOpenedAtRef.current + if ( + contextMenuOpenedAt == null || + !shouldSuppressContextMenuFollowUpClick(contextMenuOpenedAt, Date.now()) + ) { + if (contextMenuOpenedAt != null) { + contextMenuOpenedAtRef.current = null + } + return + } + // Why: macOS ctrl-click can release over the just-opened menu, selecting + // the item under the cursor unless the opening pointer sequence is ignored. + event.preventDefault() + event.stopPropagation() + if (event.type === 'click') { + contextMenuOpenedAtRef.current = null + } + }, []) + + return ( +
{ + if (shouldIgnoreNestedWorktreeContextMenuScope(event.currentTarget, event.target)) { + return + } + event.preventDefault() + contextMenuOpenedAtRef.current = Date.now() + window.dispatchEvent(new Event(CLOSE_ALL_CONTEXT_MENUS_EVENT)) + setContextWorktrees(onContextMenuSelect?.(event) ?? selectedWorktrees) + const bounds = event.currentTarget.getBoundingClientRect() + setMenuPoint({ x: event.clientX - bounds.left, y: event.clientY - bounds.top }) + setMenuOpen(true) + }} + onClickCapture={(event) => { + suppressOpeningPointerEvent(event) + }} + > + {children}
) }) export default WorktreeContextMenu -export { CLOSE_ALL_CONTEXT_MENUS_EVENT, WORKTREE_CONTEXT_MENU_SCOPE_ATTR } +export { + CLOSE_ALL_CONTEXT_MENUS_EVENT, + WORKTREE_CONTEXT_MENU_SCOPE_ATTR, + shouldSuppressContextMenuFollowUpClick, + shouldIgnoreNestedWorktreeContextMenuScope +} diff --git a/src/renderer/src/components/sidebar/WorktreeList.tsx b/src/renderer/src/components/sidebar/WorktreeList.tsx index e44df6924..c9afa1915 100644 --- a/src/renderer/src/components/sidebar/WorktreeList.tsx +++ b/src/renderer/src/components/sidebar/WorktreeList.tsx @@ -1,7 +1,7 @@ /* eslint-disable max-lines */ import React, { useMemo, useCallback, useRef, useState, useEffect, useLayoutEffect } from 'react' import { useVirtualizer } from '@tanstack/react-virtual' -import { ChevronDown, CircleX, Plus } from 'lucide-react' +import { ChevronDown, CircleX, Plus, Workflow } from 'lucide-react' import { useAppStore } from '@/store' import { getAllWorktreesFromState, @@ -16,6 +16,7 @@ import { cn } from '@/lib/utils' import type { Worktree, Repo, + WorktreeLineage, WorkspaceStatus, WorkspaceStatusDefinition } from '../../../../shared/types' @@ -35,8 +36,9 @@ import { type WorktreeGroupBy, PINNED_GROUP_KEY, buildRows, + getGroupKeyForWorktree, getRepoGroupOrdering, - getGroupKeyForWorktree + getLineageGroupKey } from './worktree-list-groups' import { getWorkspaceStatus, @@ -53,12 +55,14 @@ import { } from './visible-worktrees' import { activateAndRevealWorktree } from '@/lib/worktree-activation' import { useRepoHeaderDrag } from './repo-header-drag' +import WorktreeContextMenu from './WorktreeContextMenu' import { areWorktreeSelectionsEqual, getWorktreeSelectionIntent, pruneWorktreeSelection, updateWorktreeSelection } from './worktree-multi-selection' +import { branchDisplayName } from './WorktreeCardHelpers' import { callRuntimeRpc, getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client' // How long to wait after a sortEpoch bump before actually re-sorting. @@ -91,10 +95,13 @@ function getWorktreeOptionId(worktreeId: string): string { return `worktree-list-option-${encodeURIComponent(worktreeId)}` } +const LINEAGE_INDENT = 24 + type VirtualizedWorktreeViewportProps = { rows: Row[] activeWorktreeId: string | null groupBy: WorktreeGroupBy + showWorkspaceLineage: boolean repoGroupOrdering: RepoGroupOrdering toggleGroup: (key: string) => void collapsedGroups: Set @@ -111,6 +118,8 @@ type VirtualizedWorktreeViewportProps = { worktree: Worktree ) => readonly Worktree[] repoMap: Map + worktreeMap: Map + worktreeLineageById: Record repoOrder: Map // The full canonical state.repos id ordering — the drag controller commits // permutations of this list, even when some repos aren't currently visible @@ -131,10 +140,77 @@ type VirtualizedWorktreeViewportProps = { scrollOffsetRef: React.MutableRefObject } +type WorktreeItemRow = Extract +type RenderRow = Row | { type: 'lineage-group'; key: string; rows: WorktreeItemRow[] } + +function isWorktreeItemRow(row: Row): row is WorktreeItemRow { + return row.type === 'item' +} + +function renderRowContainsWorktree(row: RenderRow, worktreeId: string | null): boolean { + if (worktreeId === null) { + return false + } + if (row.type === 'lineage-group') { + return row.rows.some((item) => item.worktree.id === worktreeId) + } + return row.type === 'item' && row.worktree.id === worktreeId +} + +function buildRenderableRows(rows: Row[], showWorkspaceLineage: boolean): RenderRow[] { + if (!showWorkspaceLineage) { + return rows + } + + const renderRows: RenderRow[] = [] + for (let index = 0; index < rows.length; index++) { + const row = rows[index] + if ( + !isWorktreeItemRow(row) || + row.lineageChildCount === 0 || + row.lineageCollapsed || + rows[index + 1]?.type !== 'item' || + (rows[index + 1] as WorktreeItemRow).depth <= row.depth + ) { + renderRows.push(row) + continue + } + + const groupRows: WorktreeItemRow[] = [row] + let cursor = index + 1 + while (cursor < rows.length) { + const child = rows[cursor] + if (!isWorktreeItemRow(child) || child.depth <= row.depth) { + break + } + groupRows.push(child) + cursor++ + } + renderRows.push({ + type: 'lineage-group', + key: getLineageGroupKey(row.worktree.id), + rows: groupRows + }) + index = cursor - 1 + } + return renderRows +} + +function getRenderRowKey(row: RenderRow): string { + if (row.type === 'header') { + return `hdr:${row.key}` + } + if (row.type === 'lineage-group') { + return `lineage-group:${row.key}` + } + return `wt:${row.worktree.id}` +} + const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewport({ rows, activeWorktreeId, groupBy, + showWorkspaceLineage, repoGroupOrdering, toggleGroup, collapsedGroups, @@ -148,6 +224,8 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp onSelectionGesture, onContextMenuSelect, repoMap, + worktreeMap, + worktreeLineageById, repoOrder, allRepoIds, reorderRepos, @@ -169,15 +247,25 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp onCommit: reorderRepos, getScrollContainer: () => scrollRef.current }) + const renderRows = useMemo( + () => buildRenderableRows(rows, showWorkspaceLineage), + [rows, showWorkspaceLineage] + ) const activeWorktreeRowIndex = useMemo( - () => rows.findIndex((row) => row.type === 'item' && row.worktree.id === activeWorktreeId), - [rows, activeWorktreeId] + () => renderRows.findIndex((row) => renderRowContainsWorktree(row, activeWorktreeId)), + [renderRows, activeWorktreeId] ) const virtualizer = useVirtualizer({ - count: rows.length, + count: renderRows.length, getScrollElement: () => scrollRef.current, - estimateSize: () => 120, + estimateSize: (index) => { + const row = renderRows[index] + if (row?.type === 'lineage-group') { + return 104 + Math.max(0, row.rows.length - 1) * 96 + } + return 120 + }, overscan: 10, gap: 6, // Why: tells the virtualizer to start its internal scrollOffset at the @@ -187,11 +275,11 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp // virtualizer stay aligned across remounts. initialOffset: () => scrollOffsetRef.current, getItemKey: (index) => { - const row = rows[index] + const row = renderRows[index] if (!row) { return `__stale_${index}` } - return row.type === 'header' ? `hdr:${row.key}` : `wt:${row.worktree.id}` + return getRenderRowKey(row) } }) @@ -247,6 +335,29 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp { const targetWorktree = worktrees.find((w) => w.id === pendingRevealWorktreeId) + if (targetWorktree && showWorkspaceLineage && !targetWorktree.isPinned) { + const seen = new Set() + let current: Worktree | undefined = targetWorktree + while (current && !seen.has(current.id)) { + seen.add(current.id) + const lineage = worktreeLineageById[current.id] + const parent = lineage ? worktreeMap.get(lineage.parentWorktreeId) : undefined + if ( + !lineage || + !parent || + current.instanceId !== lineage.worktreeInstanceId || + parent.instanceId !== lineage.parentWorktreeInstanceId + ) { + break + } + const lineageGroupKey = getLineageGroupKey(parent.id) + if (collapsedGroups.has(lineageGroupKey)) { + toggleGroup(lineageGroupKey) + } + current = parent + } + } + if (targetWorktree?.isPinned) { // Why: pinned worktrees live in the dedicated "Pinned" section regardless // of their PR-status / repo group. Only uncollapse the Pinned header @@ -270,8 +381,8 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp } requestAnimationFrame(() => { - const targetIndex = rows.findIndex( - (row) => row.type === 'item' && row.worktree.id === pendingRevealWorktreeId + const targetIndex = renderRows.findIndex((row) => + renderRowContainsWorktree(row, pendingRevealWorktreeId) ) if (targetIndex !== -1) { // Why: `align: 'auto'` is a no-op when the card is already visible and @@ -290,7 +401,10 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp worktrees, repoMap, prCache, - rows, + worktreeLineageById, + worktreeMap, + showWorkspaceLineage, + renderRows, virtualizer, clearPendingRevealWorktreeId, toggleGroup, @@ -304,12 +418,12 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp useLayoutEffect(() => { virtualizer.elementsCache.forEach((element) => { const idx = parseInt(element.getAttribute('data-index') ?? '', 10) - if (Number.isNaN(idx) || idx >= rows.length) { + if (Number.isNaN(idx) || idx >= renderRows.length) { return } virtualizer.measureElement(element) }) - }, [prCacheLen, issueCacheLen, virtualizer, rows.length]) + }, [prCacheLen, issueCacheLen, virtualizer, renderRows.length]) const navigateWorktree = useCallback( (direction: 'up' | 'down') => { @@ -326,7 +440,10 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp new Set(), repoOrder, workspaceStatuses, - repoGroupOrdering + repoGroupOrdering, + worktreeLineageById, + worktreeMap, + showWorkspaceLineage ).filter((r): r is Extract => r.type === 'item') if (worktreeRows.length === 0) { return @@ -354,13 +471,13 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp // it must flow through the same activation helper that records history. activateAndRevealWorktree(nextWorktreeId) - const rowIndex = rows.findIndex((r) => r.type === 'item' && r.worktree.id === nextWorktreeId) + const rowIndex = renderRows.findIndex((row) => renderRowContainsWorktree(row, nextWorktreeId)) if (rowIndex !== -1) { virtualizer.scrollToIndex(rowIndex, { align: 'auto' }) } }, [ - rows, + renderRows, activeWorktreeId, virtualizer, groupBy, @@ -369,7 +486,10 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp repoMap, prCache, repoOrder, - workspaceStatuses + workspaceStatuses, + worktreeLineageById, + worktreeMap, + showWorkspaceLineage ] ) @@ -419,7 +539,10 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp [navigateWorktree] ) - const firstHeaderIndex = useMemo(() => rows.findIndex((r) => r.type === 'header'), [rows]) + const firstHeaderIndex = useMemo( + () => renderRows.findIndex((row) => row.type === 'header'), + [renderRows] + ) const virtualItems = virtualizer.getVirtualItems() const activeDescendantId = @@ -527,7 +650,10 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp /> ) : null} {virtualItems.map((vItem) => { - const row = rows[vItem.index] + const row = renderRows[vItem.index] + if (!row) { + return null + } if (row.type === 'header') { const isRepoHeader = groupBy === 'repo' && row.repo !== undefined @@ -634,7 +760,7 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp /> - {row.repo ? ( + {row.repo && groupBy === 'repo' ? ( + + + {child.lineageCollapsed + ? 'Show child workspaces' + : 'Hide child workspaces'} + + + + ) : null} + + + + + ) + } + + const renderWorktreeRow = ( + itemRow: WorktreeItemRow, + nested: boolean, + lineageChildren?: React.ReactNode, + forceActiveSurface = false + ) => { + const lineageToggleGroupKey = itemRow.lineageGroupKey + return ( +
0 + ? `${Math.max(0, itemRow.depth - 1) * LINEAGE_INDENT}px` + : itemRow.depth > 0 + ? `${itemRow.depth * LINEAGE_INDENT}px` + : undefined + }} + > + onContextMenuSelect(event, itemRow.worktree)} + hideRepoBadge={groupBy === 'repo'} + parentLabel={ + itemRow.depth > 0 && itemRow.lineageState === 'valid' + ? undefined + : itemRow.parentLabel + } + lineageState={itemRow.lineageState} + lineageChildCount={itemRow.lineageChildCount} + lineageCollapsed={itemRow.lineageCollapsed} + lineageChildren={lineageChildren} + onLineageToggle={ + lineageToggleGroupKey + ? (event) => { + event.preventDefault() + event.stopPropagation() + toggleGroup(lineageToggleGroupKey) + } + : undefined + } + /> +
+ ) + } + + if (row.type === 'lineage-group') { + const [parent, ...children] = row.rows + const childIsActive = children.some((child) => child.worktree.id === activeWorktreeId) + return ( +
+
+ {parent + ? renderWorktreeRow( + parent, + false, + children.length > 0 ? children.map(renderLineageChildPreview) : undefined, + childIsActive + ) + : null} +
+
+ ) + } + const itemWorkspaceStatus = groupBy === 'none' ? getWorkspaceStatus(row.worktree, workspaceStatuses) : null return (
- onContextMenuSelect(event, row.worktree)} - hideRepoBadge={groupBy === 'repo'} - /> + {renderWorktreeRow(row, false)}
) })} @@ -721,9 +1034,11 @@ const WorktreeList = React.memo(function WorktreeList() { const allWorktrees = useAllWorktrees() const repoMap = useRepoMap() const worktreeMap = useWorktreeMap() + const worktreeLineageById = useAppStore((s) => s.worktreeLineageById) const worktreesByRepo = useAppStore((s) => s.worktreesByRepo) const activeWorktreeId = useAppStore((s) => s.activeWorktreeId) const groupBy = useAppStore((s) => s.groupBy) + const showWorkspaceLineage = useAppStore((s) => s.showWorkspaceLineage) const workspaceStatuses = useAppStore((s) => s.workspaceStatuses) const sortBy = useAppStore((s) => s.sortBy) const showActiveOnly = useAppStore((s) => s.showActiveOnly) @@ -1045,7 +1360,10 @@ const WorktreeList = React.memo(function WorktreeList() { collapsedGroups, repoOrder, workspaceStatuses, - repoGroupOrdering + repoGroupOrdering, + worktreeLineageById, + worktreeMap, + showWorkspaceLineage ), [ groupBy, @@ -1055,7 +1373,10 @@ const WorktreeList = React.memo(function WorktreeList() { collapsedGroups, repoOrder, workspaceStatuses, - repoGroupOrdering + repoGroupOrdering, + worktreeLineageById, + worktreeMap, + showWorkspaceLineage ] ) // Why: rows.length alone can stay the same when items migrate between @@ -1259,6 +1580,7 @@ const WorktreeList = React.memo(function WorktreeList() { rows={rows} activeWorktreeId={selectedSidebarWorktreeId} groupBy={groupBy} + showWorkspaceLineage={showWorkspaceLineage} repoGroupOrdering={repoGroupOrdering} toggleGroup={toggleGroup} collapsedGroups={collapsedGroups} @@ -1272,6 +1594,8 @@ const WorktreeList = React.memo(function WorktreeList() { onSelectionGesture={updateSelectionForGesture} onContextMenuSelect={selectForContextMenu} repoMap={repoMap} + worktreeMap={worktreeMap} + worktreeLineageById={worktreeLineageById} repoOrder={repoOrder} allRepoIds={allRepoIds} reorderRepos={(orderedIds) => { diff --git a/src/renderer/src/components/sidebar/worktree-list-groups.test.ts b/src/renderer/src/components/sidebar/worktree-list-groups.test.ts index 1dd46e3b4..861e874ab 100644 --- a/src/renderer/src/components/sidebar/worktree-list-groups.test.ts +++ b/src/renderer/src/components/sidebar/worktree-list-groups.test.ts @@ -1,8 +1,15 @@ +/* eslint-disable max-lines -- Why: row-builder tests keep grouping, pinning, and lineage ordering cases together so expected row contracts stay comparable. */ import { readFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' -import { buildRows, getPRGroupKey, getRepoGroupOrdering } from './worktree-list-groups' -import type { Repo, Worktree } from '../../../../shared/types' +import { + buildRows, + getLineageGroupKey, + getLineageRenderInfo, + getPRGroupKey, + getRepoGroupOrdering +} from './worktree-list-groups' +import type { Repo, Worktree, WorktreeLineage } from '../../../../shared/types' const repo: Repo = { id: 'repo-1', @@ -310,6 +317,237 @@ describe('getRepoGroupOrdering', () => { }) }) +describe('buildRows workspace lineage nesting', () => { + const parent: Worktree = { + ...worktree, + id: 'wt-parent', + instanceId: 'parent-instance', + displayName: 'coordinator' + } + const child: Worktree = { + ...worktree, + id: 'wt-child', + instanceId: 'child-instance', + displayName: 'worker' + } + const grandchild: Worktree = { + ...worktree, + id: 'wt-grandchild', + instanceId: 'grandchild-instance', + displayName: 'nested-worker' + } + const lineage: WorktreeLineage = { + worktreeId: child.id, + worktreeInstanceId: 'child-instance', + parentWorktreeId: parent.id, + parentWorktreeInstanceId: 'parent-instance', + origin: 'cli', + capture: { source: 'terminal-context', confidence: 'inferred' }, + createdAt: 1 + } + const grandchildLineage: WorktreeLineage = { + worktreeId: grandchild.id, + worktreeInstanceId: 'grandchild-instance', + parentWorktreeId: child.id, + parentWorktreeInstanceId: 'child-instance', + origin: 'cli', + capture: { source: 'terminal-context', confidence: 'inferred' }, + createdAt: 1 + } + + it('keeps lineage flat when nesting is off', () => { + const rows = buildRows( + 'none', + [child, parent], + repoMap, + null, + new Set(), + undefined, + undefined, + undefined, + { [child.id]: lineage }, + new Map([ + [parent.id, parent], + [child.id, child] + ]) + ) + + const items = rows.filter((row) => row.type === 'item') + expect(items[0]).toMatchObject({ type: 'item', worktree: { id: child.id } }) + expect(items[0]).not.toHaveProperty('parentLabel') + expect(items[1]).toMatchObject({ + type: 'item', + worktree: { id: parent.id } + }) + }) + + it('places children directly under their parent when nesting is on', () => { + const rows = buildRows( + 'none', + [child, parent], + repoMap, + null, + new Set(), + undefined, + undefined, + undefined, + { [child.id]: lineage }, + new Map([ + [parent.id, parent], + [child.id, child] + ]), + true + ) + + const items = rows.filter((row) => row.type === 'item') + expect(items[0]).toMatchObject({ type: 'item', worktree: { id: parent.id } }) + expect(items[1]).toMatchObject({ + type: 'item', + worktree: { id: child.id }, + depth: 1, + parentLabel: 'coordinator' + }) + }) + + it('supports nested lineage chains beyond one level', () => { + const rows = buildRows( + 'none', + [grandchild, child, parent], + repoMap, + null, + new Set(), + undefined, + undefined, + undefined, + { [child.id]: lineage, [grandchild.id]: grandchildLineage }, + new Map([ + [parent.id, parent], + [child.id, child], + [grandchild.id, grandchild] + ]), + true + ) + + const items = rows.filter((row) => row.type === 'item') + expect(items.map((row) => row.worktree.id)).toEqual([parent.id, child.id, grandchild.id]) + expect(items[0]).toMatchObject({ + type: 'item', + depth: 0, + lineageChildCount: 1, + lineageCollapsed: false + }) + expect(items[1]).toMatchObject({ + type: 'item', + worktree: { id: child.id }, + depth: 1, + lineageChildCount: 1 + }) + expect(items[2]).toMatchObject({ + type: 'item', + worktree: { id: grandchild.id }, + depth: 2, + lineageChildCount: 0 + }) + }) + + it('collapses descendants under lineage parents', () => { + const rows = buildRows( + 'none', + [grandchild, child, parent], + repoMap, + null, + new Set([getLineageGroupKey(parent.id)]), + undefined, + undefined, + undefined, + { [child.id]: lineage, [grandchild.id]: grandchildLineage }, + new Map([ + [parent.id, parent], + [child.id, child], + [grandchild.id, grandchild] + ]), + true + ) + + const items = rows.filter((row) => row.type === 'item') + expect(items).toHaveLength(1) + expect(items[0]).toMatchObject({ + type: 'item', + worktree: { id: parent.id }, + lineageChildCount: 1, + lineageCollapsed: true + }) + }) + + it('marks stale instance links as missing without creating a parent group', () => { + const staleLineage = { ...lineage, parentWorktreeInstanceId: 'old-parent-instance' } + const rows = buildRows( + 'none', + [child], + repoMap, + null, + new Set(), + undefined, + undefined, + undefined, + { [child.id]: staleLineage }, + new Map([ + [parent.id, parent], + [child.id, child] + ]), + true + ) + + const items = rows.filter((row) => row.type === 'item') + expect(items[0]).toMatchObject({ + type: 'item', + worktree: { id: child.id }, + lineageState: 'missing' + }) + }) + + it('marks stale instance links as missing for shared context-menu validation', () => { + const staleLineage = { ...lineage, parentWorktreeInstanceId: 'old-parent-instance' } + const info = getLineageRenderInfo( + child, + { [child.id]: staleLineage }, + new Map([ + [parent.id, parent], + [child.id, child] + ]) + ) + + expect(info).toMatchObject({ state: 'missing' }) + }) + + it('keeps pinned children in Pinned with parent context', () => { + const pinnedChild = { ...child, isPinned: true } + const rows = buildRows( + 'none', + [parent, pinnedChild], + repoMap, + null, + new Set(), + undefined, + undefined, + undefined, + { [child.id]: lineage }, + new Map([ + [parent.id, parent], + [child.id, pinnedChild] + ]), + true + ) + + expect(rows[0]).toMatchObject({ type: 'header', key: 'pinned' }) + expect(rows[1]).toMatchObject({ + type: 'item', + worktree: { id: child.id }, + parentLabel: 'coordinator' + }) + }) +}) + describe('WorktreeList header styles', () => { it('does not title-case workspace group labels', () => { const source = readFileSync( diff --git a/src/renderer/src/components/sidebar/worktree-list-groups.ts b/src/renderer/src/components/sidebar/worktree-list-groups.ts index fd292eadf..0bbb191ba 100644 --- a/src/renderer/src/components/sidebar/worktree-list-groups.ts +++ b/src/renderer/src/components/sidebar/worktree-list-groups.ts @@ -1,6 +1,12 @@ +/* eslint-disable max-lines -- Why: sidebar row construction keeps every grouping mode in one pure module so reveal, virtualized rendering, and tests share the same flat row contract. */ import { CircleCheckBig, CircleDot, CircleX, Folder, GitPullRequest, Pin } from 'lucide-react' import type React from 'react' -import type { Repo, Worktree, WorkspaceStatusDefinition } from '../../../../shared/types' +import type { + Repo, + Worktree, + WorktreeLineage, + WorkspaceStatusDefinition +} from '../../../../shared/types' import { branchName } from '@/lib/git-utils' import { getWorkspaceStatus, @@ -32,7 +38,19 @@ export type GroupHeaderRow = { repo?: Repo } -export type WorktreeRow = { type: 'item'; worktree: Worktree; repo: Repo | undefined } +export type WorktreeRow = { + type: 'item' + worktree: Worktree + repo: Repo | undefined + depth: number + lineageTrail: boolean[] + isLastLineageChild: boolean + lineageChildCount: number + lineageGroupKey?: string + lineageCollapsed?: boolean + parentLabel?: string + lineageState?: 'valid' | 'missing' +} export type Row = GroupHeaderRow | WorktreeRow export type PRGroupKey = 'done' | 'in-review' | 'in-progress' | 'closed' @@ -82,6 +100,40 @@ export const PINNED_GROUP_META = { icon: Pin } as const +export const MISSING_PARENT_GROUP_META = { + label: 'Missing parent' +} as const + +export const LINEAGE_GROUP_PREFIX = 'lineage:' + +export function getLineageGroupKey(worktreeId: string): string { + return `${LINEAGE_GROUP_PREFIX}${worktreeId}` +} + +export type LineageRenderInfo = + | { state: 'none' } + | { state: 'valid'; lineage: WorktreeLineage; parent: Worktree } + | { state: 'missing'; lineage: WorktreeLineage } + +export function getLineageRenderInfo( + worktree: Worktree, + lineageById: Record, + worktreeMap: Map +): LineageRenderInfo { + const lineage = lineageById[worktree.id] + if (!lineage) { + return { state: 'none' } + } + const parent = worktreeMap.get(lineage.parentWorktreeId) + if ( + !parent || + worktree.instanceId !== lineage.worktreeInstanceId || + parent.instanceId !== lineage.parentWorktreeInstanceId + ) { + return { state: 'missing', lineage } + } + return { state: 'valid', lineage, parent } +} export function getPRGroupKey( worktree: Worktree, repoMap: Map, @@ -118,8 +170,11 @@ export function getPRGroupKey( function emitPinnedGroup( worktrees: Worktree[], repoMap: Map, + lineageById: Record, + worktreeMap: Map, collapsedGroups: Set, result: Row[], + showLineageContext: boolean, force = false ): Set { const pinned = worktrees.filter((w) => w.isPinned) @@ -136,13 +191,151 @@ function emitPinnedGroup( icon: PINNED_GROUP_META.icon }) if (!collapsedGroups.has(PINNED_GROUP_KEY)) { - for (const w of pinned) { - result.push({ type: 'item', worktree: w, repo: repoMap.get(w.repoId) }) - } + appendWorktreeRows(result, pinned, repoMap, lineageById, worktreeMap, { + nestLineage: false, + showLineageContext, + collapsedGroups + }) } return new Set(pinned.map((w) => w.id)) } +function buildWorktreeRow( + worktree: Worktree, + repoMap: Map, + lineageById: Record, + worktreeMap: Map, + showLineageContext: boolean, + depth: number, + lineageTrail: boolean[], + isLastLineageChild: boolean, + lineageChildCount: number, + lineageCollapsed: boolean +): WorktreeRow { + const lineage = showLineageContext + ? getLineageRenderInfo(worktree, lineageById, worktreeMap) + : { state: 'none' as const } + return { + type: 'item', + worktree, + repo: repoMap.get(worktree.repoId), + depth, + lineageTrail, + isLastLineageChild, + lineageChildCount, + ...(lineageChildCount > 0 ? { lineageGroupKey: getLineageGroupKey(worktree.id) } : {}), + ...(lineageChildCount > 0 ? { lineageCollapsed } : {}), + ...(lineage.state === 'valid' + ? { parentLabel: lineage.parent.displayName, lineageState: 'valid' as const } + : lineage.state === 'missing' + ? { parentLabel: MISSING_PARENT_GROUP_META.label, lineageState: 'missing' as const } + : {}) + } +} + +function appendWorktreeRows( + result: Row[], + worktrees: Worktree[], + repoMap: Map, + lineageById: Record, + worktreeMap: Map, + options: { + nestLineage: boolean + showLineageContext: boolean + collapsedGroups: Set + } +): void { + const { nestLineage, showLineageContext, collapsedGroups } = options + if (!nestLineage) { + for (const worktree of worktrees) { + result.push( + buildWorktreeRow( + worktree, + repoMap, + lineageById, + worktreeMap, + showLineageContext, + 0, + [], + false, + 0, + false + ) + ) + } + return + } + + const visibleIds = new Set(worktrees.map((worktree) => worktree.id)) + const childrenByParentId = new Map() + const childIds = new Set() + for (const worktree of worktrees) { + const lineage = getLineageRenderInfo(worktree, lineageById, worktreeMap) + if (lineage.state !== 'valid' || !visibleIds.has(lineage.parent.id)) { + continue + } + childIds.add(worktree.id) + const children = childrenByParentId.get(lineage.parent.id) ?? [] + children.push(worktree) + childrenByParentId.set(lineage.parent.id, children) + } + + const emitted = new Set() + const emit = ( + worktree: Worktree, + depth: number, + lineageTrail: boolean[], + isLastChild: boolean + ): void => { + if (emitted.has(worktree.id)) { + return + } + const children = childrenByParentId.get(worktree.id) ?? [] + const lineageGroupKey = getLineageGroupKey(worktree.id) + const lineageCollapsed = collapsedGroups.has(lineageGroupKey) + emitted.add(worktree.id) + result.push( + buildWorktreeRow( + worktree, + repoMap, + lineageById, + worktreeMap, + showLineageContext, + depth, + lineageTrail, + isLastChild, + children.length, + lineageCollapsed + ) + ) + if (lineageCollapsed) { + return + } + children.forEach((child, index) => { + emit( + child, + depth + 1, + [...lineageTrail, index < children.length - 1], + index === children.length - 1 + ) + }) + } + + const roots = worktrees.filter((worktree) => !childIds.has(worktree.id)) + for (const [index, worktree] of roots.entries()) { + emit(worktree, 0, [], index === roots.length - 1) + } + if (roots.length === 0) { + for (const worktree of worktrees) { + if (!emitted.has(worktree.id)) { + // Why: malformed cyclic lineage should not hide every participant. + // Render any leftovers as roots rather than recursing forever. + emit(worktree, 0, [], true) + } + } + } +} + /** * Build the flat row list consumed by the virtualizer. * Extracted here to keep WorktreeList.tsx under the line-count lint limit. @@ -155,11 +348,25 @@ export function buildRows( collapsedGroups: Set, repoOrder?: Map, workspaceStatuses: readonly WorkspaceStatusDefinition[] = cloneDefaultWorkspaceStatuses(), - repoGroupOrdering: RepoGroupOrdering = 'manual' + repoGroupOrdering: RepoGroupOrdering = 'manual', + lineageById: Record = {}, + worktreeMap: Map = new Map( + worktrees.map((worktree) => [worktree.id, worktree]) + ), + nestLineage = false ): Row[] { const result: Row[] = [] - const pinnedIds = emitPinnedGroup(worktrees, repoMap, collapsedGroups, result, groupBy === 'none') + const pinnedIds = emitPinnedGroup( + worktrees, + repoMap, + lineageById, + worktreeMap, + collapsedGroups, + result, + nestLineage, + groupBy === 'none' + ) const unpinned = pinnedIds.size > 0 ? worktrees.filter((w) => !pinnedIds.has(w.id)) : worktrees const grouped = new Map() @@ -276,9 +483,11 @@ export function buildRows( result.push(header) if (!isCollapsed) { - for (const w of group.items) { - result.push({ type: 'item', worktree: w, repo: repoMap.get(w.repoId) }) - } + appendWorktreeRows(result, group.items, repoMap, lineageById, worktreeMap, { + nestLineage, + showLineageContext: nestLineage, + collapsedGroups + }) } } diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index 6f1d69bc9..172094ce5 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -79,6 +79,7 @@ async function prepareRemoteWorkspaceTarget(targetId: string): Promise repos = useAppStore.getState().repos.filter((repo) => repo.connectionId === targetId) } await Promise.all(repos.map((repo) => useAppStore.getState().fetchWorktrees(repo.id))) + await useAppStore.getState().fetchWorktreeLineage() return true } @@ -352,6 +353,7 @@ export function useIpcEvents(): void { const state = useAppStore.getState() const before = new Set((state.worktreesByRepo[data.repoId] ?? []).map((w) => w.id)) await state.fetchWorktrees(data.repoId) + await useAppStore.getState().fetchWorktreeLineage() const afterState = useAppStore.getState() const after = new Set((afterState.worktreesByRepo[data.repoId] ?? []).map((w) => w.id)) const removed: string[] = [] @@ -1297,7 +1299,8 @@ export function useIpcEvents(): void { // lets it detect that providers are now available and retry. store.bumpSshConnectedGeneration() - void Promise.all(remoteRepos.map((r) => store.fetchWorktrees(r.id))).then(() => { + void Promise.all(remoteRepos.map((r) => store.fetchWorktrees(r.id))).then(async () => { + await useAppStore.getState().fetchWorktreeLineage() // Why: terminal panes that failed to spawn (no PTY provider on cold // start) sit inert. Bumping generation forces TerminalPane to remount // and retry pty:spawn. Only bump tabs with no live ptyId. diff --git a/src/renderer/src/lib/pane-manager/pane-manager.ts b/src/renderer/src/lib/pane-manager/pane-manager.ts index 6923fa333..c5d5e8c08 100644 --- a/src/renderer/src/lib/pane-manager/pane-manager.ts +++ b/src/renderer/src/lib/pane-manager/pane-manager.ts @@ -14,7 +14,12 @@ import { import { createDragReorderState, hideDropOverlay, handlePaneDrop } from './pane-drag-reorder' import { createPaneDOM, openTerminal, setLigaturesEnabled, disposePane } from './pane-lifecycle' import { shouldFollowMouseFocus } from './focus-follows-mouse' -import { equalizePaneSplitSizes, safeFit, fitAllPanesInternal, refitPanesUnder } from './pane-tree-ops' +import { + equalizePaneSplitSizes, + safeFit, + fitAllPanesInternal, + refitPanesUnder +} from './pane-tree-ops' import { toPublicPane } from './pane-public-view' import { applyTerminalGpuAcceleration } from './pane-terminal-gpu-acceleration' import { diff --git a/src/renderer/src/lib/startup-ui-hydration.ts b/src/renderer/src/lib/startup-ui-hydration.ts index 28fb39334..5d276491a 100644 --- a/src/renderer/src/lib/startup-ui-hydration.ts +++ b/src/renderer/src/lib/startup-ui-hydration.ts @@ -35,6 +35,7 @@ export function getStartupErrorFallbackUI(uiHydrated: boolean): PersistedUIState sidebarWidth: 280, rightSidebarWidth: 350, groupBy: 'none', + showWorkspaceLineage: false, sortBy: 'name', showActiveOnly: false, hideDefaultBranchWorkspace: false, diff --git a/src/renderer/src/store/slices/settings.test.ts b/src/renderer/src/store/slices/settings.test.ts index 9d0bc5e54..0b762ef5e 100644 --- a/src/renderer/src/store/slices/settings.test.ts +++ b/src/renderer/src/store/slices/settings.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi, beforeEach } from 'vitest' import { createTestStore, makeWorktree } from './store-test-helpers' import type { AppState } from '../types' +import type { WorktreeLineage } from '../../../../shared/types' import { toast } from 'sonner' import { MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, @@ -20,6 +21,16 @@ vi.mock('@/lib/agent-status', async (importOriginal) => { const runtimeEnvironmentCall = vi.fn() const settingsSet = vi.fn().mockResolvedValue(undefined) +const env2Lineage: WorktreeLineage = { + worktreeId: 'repo-env-2::/env-2/repo', + worktreeInstanceId: 'env-2-instance', + parentWorktreeId: 'repo-env-2::/env-2/parent', + parentWorktreeInstanceId: 'env-2-parent-instance', + origin: 'manual', + capture: { source: 'manual-action', confidence: 'explicit' }, + createdAt: 1 +} + beforeEach(() => { clearRuntimeCompatibilityCacheForTests() vi.clearAllMocks() @@ -58,7 +69,9 @@ beforeEach(() => { } : method === 'browser.profile.list' ? { profiles: [] } - : {} + : method === 'worktree.lineageList' + ? { lineage: { [env2Lineage.worktreeId]: env2Lineage } } + : {} return Promise.resolve({ id: 'rpc-1', ok: true, result, _meta: { runtimeId: 'runtime-2' } }) }) vi.stubGlobal('window', { @@ -78,6 +91,13 @@ describe('createSettingsSlice runtime switching', () => { worktreesByRepo: { 'repo-env-1': [makeWorktree({ id: 'repo-env-1::/env-1/repo', repoId: 'repo-env-1' })] }, + worktreeLineageById: { + 'repo-env-1::/env-1/repo': { + ...env2Lineage, + worktreeId: 'repo-env-1::/env-1/repo', + parentWorktreeId: 'repo-env-1::/env-1/parent' + } + }, activeWorktreeId: 'repo-env-1::/env-1/repo', openFiles: [{ id: '/env-1/repo/a.md', worktreeId: 'repo-env-1::/env-1/repo' } as never], ptyIdsByTabId: { tab1: ['remote:env-1@@terminal-a'] }, @@ -113,6 +133,9 @@ describe('createSettingsSlice runtime switching', () => { expect(runtimeEnvironmentCall).toHaveBeenCalledWith( expect.objectContaining({ selector: 'env-2', method: 'repo.list' }) ) + expect(runtimeEnvironmentCall).toHaveBeenCalledWith( + expect.objectContaining({ selector: 'env-2', method: 'worktree.lineageList' }) + ) expect(runtimeEnvironmentCall).toHaveBeenCalledWith( expect.objectContaining({ selector: 'env-1', @@ -138,6 +161,9 @@ describe('createSettingsSlice runtime switching', () => { expect(store.getState().worktreesByRepo['repo-env-2']?.map((worktree) => worktree.id)).toEqual([ 'repo-env-2::/env-2/repo' ]) + expect(store.getState().worktreeLineageById).toEqual({ + [env2Lineage.worktreeId]: env2Lineage + }) expect(store.getState().activeWorktreeId).toBeNull() expect(store.getState().openFiles).toEqual([]) expect(store.getState().editorDrafts).toEqual({}) diff --git a/src/renderer/src/store/slices/settings.ts b/src/renderer/src/store/slices/settings.ts index 4a30c09f9..629b76db5 100644 --- a/src/renderer/src/store/slices/settings.ts +++ b/src/renderer/src/store/slices/settings.ts @@ -33,6 +33,7 @@ function runtimeScopedStateReset(): Partial { sparsePresetsLoadStatusByRepo: {}, sparsePresetsErrorByRepo: {}, worktreesByRepo: {}, + worktreeLineageById: {}, activeWorktreeId: null, deleteStateByWorktreeId: {}, baseStatusByWorktreeId: {}, @@ -303,6 +304,7 @@ export const createSettingsSlice: StateCreator // while the new environment is loading. await get().fetchRepos() await get().fetchAllWorktrees() + await get().fetchWorktreeLineage() await get().fetchBrowserSessionProfiles() return true } catch (err) { diff --git a/src/renderer/src/store/slices/ui.ts b/src/renderer/src/store/slices/ui.ts index a24fe6aa5..bf4fdd0b0 100644 --- a/src/renderer/src/store/slices/ui.ts +++ b/src/renderer/src/store/slices/ui.ts @@ -348,6 +348,8 @@ export type UISlice = { clearOrcaHookTrustForRepo: (repoId: string) => void groupBy: 'none' | 'repo' | 'pr-status' setGroupBy: (g: UISlice['groupBy']) => void + showWorkspaceLineage: boolean + setShowWorkspaceLineage: (v: boolean) => void sortBy: 'name' | 'smart' | 'recent' | 'repo' setSortBy: (s: UISlice['sortBy']) => void showActiveOnly: boolean @@ -702,6 +704,9 @@ export const createUISlice: StateCreator = (set, get) set({ groupBy: g, collapsedGroups: new Set() }) }, + showWorkspaceLineage: false, + setShowWorkspaceLineage: (v) => set({ showWorkspaceLineage: v }), + sortBy: 'recent', setSortBy: (s) => set({ sortBy: s }), @@ -886,7 +891,8 @@ export const createUISlice: StateCreator = (set, get) s.rightSidebarWidth, MAX_RIGHT_SIDEBAR_WIDTH ), - groupBy: ui.groupBy, + groupBy: (ui.groupBy as UISlice['groupBy'] | 'parent') === 'parent' ? 'repo' : ui.groupBy, + showWorkspaceLineage: ui.showWorkspaceLineage ?? false, sortBy, // Why: "Active only" is part of the user's sidebar working set, not a // transient render detail. Restoring it on launch keeps the filtered diff --git a/src/renderer/src/store/slices/worktree-helpers.ts b/src/renderer/src/store/slices/worktree-helpers.ts index 508daa7e6..0b4e2baff 100644 --- a/src/renderer/src/store/slices/worktree-helpers.ts +++ b/src/renderer/src/store/slices/worktree-helpers.ts @@ -7,6 +7,7 @@ import type { WorkspaceCreateTelemetrySource, Worktree, WorktreeBaseStatusEvent, + WorktreeLineage, WorktreeRemoteBranchConflictEvent, WorktreeMeta } from '../../../../shared/types' @@ -20,6 +21,7 @@ export type WorktreeDeleteState = { export type WorktreeSlice = { worktreesByRepo: Record + worktreeLineageById: Record activeWorktreeId: string | null deleteStateByWorktreeId: Record baseStatusByWorktreeId: Record @@ -62,6 +64,11 @@ export type WorktreeSlice = { hasHydratedWorktreePurge: boolean fetchWorktrees: (repoId: string) => Promise fetchAllWorktrees: () => Promise + fetchWorktreeLineage: () => Promise + updateWorktreeLineage: ( + worktreeId: string, + args: { parentWorktreeId?: string; noParent?: boolean } + ) => Promise createWorktree: ( repoId: string, name: string, diff --git a/src/renderer/src/store/slices/worktrees.test.ts b/src/renderer/src/store/slices/worktrees.test.ts index d89031ac1..e06d23c68 100644 --- a/src/renderer/src/store/slices/worktrees.test.ts +++ b/src/renderer/src/store/slices/worktrees.test.ts @@ -5,7 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { create } from 'zustand' import type { AppState } from '../types' -import type { Worktree } from '../../../../shared/types' +import type { Worktree, WorktreeLineage } from '../../../../shared/types' import { createCompatibleRuntimeStatusResponseIfNeeded, type RuntimeEnvironmentCallRequest @@ -19,8 +19,10 @@ const mockApi = { worktrees: { create: vi.fn(), list: vi.fn().mockResolvedValue([]), + listLineage: vi.fn().mockResolvedValue({}), remove: vi.fn().mockResolvedValue(undefined), - updateMeta: vi.fn().mockResolvedValue(undefined) + updateMeta: vi.fn().mockResolvedValue(undefined), + updateLineage: vi.fn().mockResolvedValue(null) }, pty: { kill: vi.fn().mockResolvedValue(undefined) @@ -115,6 +117,19 @@ function makeWorktree(overrides: Partial & { id: string; repoId: strin } } +function makeLineage(overrides: Partial = {}): WorktreeLineage { + return { + worktreeId: 'repo1::/path/child', + worktreeInstanceId: 'child-instance', + parentWorktreeId: 'repo1::/path/parent', + parentWorktreeInstanceId: 'parent-instance', + origin: 'manual', + capture: { source: 'manual-action', confidence: 'explicit' }, + createdAt: 1, + ...overrides + } +} + describe('fetchWorktrees', () => { beforeEach(() => { vi.clearAllMocks() @@ -241,6 +256,289 @@ describe('fetchWorktrees', () => { }) expect(mockApi.worktrees.list).not.toHaveBeenCalled() }) + + it('updates remote worktree records when only lineage changes', async () => { + const store = createTestStore() + const initial = makeWorktree({ + id: 'repo1::/remote/wt1', + repoId: 'repo1', + path: '/remote/wt1', + branch: 'refs/heads/remote' + }) + const lineage = makeLineage({ worktreeId: initial.id }) + const refreshed = { ...initial, lineage } + store.setState({ + settings: { activeRuntimeEnvironmentId: 'env-1' } as never, + worktreesByRepo: { repo1: [initial] }, + sortEpoch: 7 + } as Partial) + runtimeEnvironmentCall.mockImplementation(({ method }: RuntimeEnvironmentCallRequest) => { + const result = + method === 'worktree.lineageList' + ? { lineage: { [lineage.worktreeId]: lineage } } + : { worktrees: [refreshed], totalCount: 1, truncated: false } + return Promise.resolve({ + id: 'rpc-1', + ok: true, + result, + _meta: { runtimeId: 'runtime-remote' } + }) + }) + + await store.getState().fetchWorktrees('repo1') + + expect(store.getState().worktreesByRepo.repo1).toEqual([refreshed]) + expect(store.getState().worktreeLineageById).toEqual({ [lineage.worktreeId]: lineage }) + expect(store.getState().sortEpoch).toBe(8) + }) + + it('refreshes remote lineage when the worktree payload is otherwise unchanged', async () => { + const store = createTestStore() + const worktree = makeWorktree({ + id: 'repo1::/remote/wt1', + repoId: 'repo1', + path: '/remote/wt1', + branch: 'refs/heads/remote' + }) + const staleLineage = makeLineage({ + worktreeId: worktree.id, + parentWorktreeId: 'repo1::/remote/old-parent' + }) + const freshLineage = makeLineage({ + worktreeId: worktree.id, + parentWorktreeId: 'repo1::/remote/new-parent' + }) + store.setState({ + settings: { activeRuntimeEnvironmentId: 'env-1' } as never, + worktreesByRepo: { repo1: [worktree] }, + worktreeLineageById: { [worktree.id]: staleLineage }, + sortEpoch: 7 + } as Partial) + runtimeEnvironmentCall.mockImplementation(({ method }: RuntimeEnvironmentCallRequest) => { + const result = + method === 'worktree.lineageList' + ? { lineage: { [freshLineage.worktreeId]: freshLineage } } + : { worktrees: [worktree], totalCount: 1, truncated: false } + return Promise.resolve({ + id: 'rpc-1', + ok: true, + result, + _meta: { runtimeId: 'runtime-remote' } + }) + }) + + await store.getState().fetchWorktrees('repo1') + + expect(store.getState().worktreesByRepo.repo1).toEqual([worktree]) + expect(store.getState().worktreeLineageById).toEqual({ + [freshLineage.worktreeId]: freshLineage + }) + expect(store.getState().sortEpoch).toBe(7) + }) + + it('keeps a successful remote worktree refresh when lineage refresh fails', async () => { + const store = createTestStore() + const refreshed = makeWorktree({ + id: 'repo1::/remote/wt1', + repoId: 'repo1', + path: '/remote/wt1', + branch: 'refs/heads/remote' + }) + const staleLineage = makeLineage({ worktreeId: refreshed.id }) + store.setState({ + settings: { activeRuntimeEnvironmentId: 'env-1' } as never, + worktreesByRepo: {}, + worktreeLineageById: { [staleLineage.worktreeId]: staleLineage }, + sortEpoch: 7 + } as Partial) + runtimeEnvironmentCall.mockImplementation(({ method }: RuntimeEnvironmentCallRequest) => { + if (method === 'worktree.lineageList') { + return Promise.reject(new Error('lineage timeout')) + } + return Promise.resolve({ + id: 'rpc-1', + ok: true, + result: { worktrees: [refreshed], totalCount: 1, truncated: false }, + _meta: { runtimeId: 'runtime-remote' } + }) + }) + vi.spyOn(console, 'error').mockImplementation(() => {}) + + await store.getState().fetchWorktrees('repo1') + + expect(store.getState().worktreesByRepo.repo1).toEqual([refreshed]) + expect(store.getState().worktreeLineageById).toEqual({ + [staleLineage.worktreeId]: staleLineage + }) + expect(store.getState().sortEpoch).toBe(8) + }) +}) + +describe('worktree lineage state', () => { + beforeEach(() => { + vi.clearAllMocks() + resetRemoteRuntimeMocks() + }) + + it('fetches persisted lineage into the renderer store', async () => { + const store = createTestStore() + const lineage = makeLineage() + mockApi.worktrees.listLineage.mockResolvedValue({ [lineage.worktreeId]: lineage }) + + await store.getState().fetchWorktreeLineage() + + expect(mockApi.worktrees.listLineage).toHaveBeenCalled() + expect(store.getState().worktreeLineageById).toEqual({ [lineage.worktreeId]: lineage }) + }) + + it('updates a child lineage entry and bumps sortEpoch', async () => { + const store = createTestStore() + const lineage = makeLineage() + mockApi.worktrees.updateLineage.mockResolvedValue(lineage) + store.setState({ sortEpoch: 3 } as Partial) + + await store.getState().updateWorktreeLineage(lineage.worktreeId, { + parentWorktreeId: lineage.parentWorktreeId + }) + + expect(mockApi.worktrees.updateLineage).toHaveBeenCalledWith({ + worktreeId: lineage.worktreeId, + parentWorktreeId: lineage.parentWorktreeId + }) + expect(store.getState().worktreeLineageById).toEqual({ [lineage.worktreeId]: lineage }) + expect(store.getState().sortEpoch).toBe(4) + }) + + it('removes a child lineage entry when the backend clears the parent link', async () => { + const store = createTestStore() + const lineage = makeLineage() + mockApi.worktrees.updateLineage.mockResolvedValue(null) + store.setState({ + worktreeLineageById: { [lineage.worktreeId]: lineage }, + sortEpoch: 3 + } as Partial) + + await store.getState().updateWorktreeLineage(lineage.worktreeId, { noParent: true }) + + expect(store.getState().worktreeLineageById).toEqual({}) + expect(store.getState().sortEpoch).toBe(4) + }) + + it('refetches lineage after an update failure', async () => { + const store = createTestStore() + const lineage = makeLineage() + mockApi.worktrees.updateLineage.mockRejectedValueOnce(new Error('stale parent')) + mockApi.worktrees.listLineage.mockResolvedValue({ [lineage.worktreeId]: lineage }) + vi.spyOn(console, 'error').mockImplementation(() => {}) + + await store.getState().updateWorktreeLineage(lineage.worktreeId, { + parentWorktreeId: lineage.parentWorktreeId + }) + + expect(mockApi.worktrees.listLineage).toHaveBeenCalled() + expect(store.getState().worktreeLineageById).toEqual({ [lineage.worktreeId]: lineage }) + }) + + it('fetches raw lineage from the active remote runtime environment', async () => { + const store = createTestStore() + const lineage = makeLineage() + runtimeEnvironmentCall.mockResolvedValue({ + id: 'rpc-lineage-list', + ok: true, + result: { lineage: { [lineage.worktreeId]: lineage } }, + _meta: { runtimeId: 'runtime-remote' } + }) + store.setState({ + settings: { activeRuntimeEnvironmentId: 'env-1' } as never, + worktreesByRepo: {} + } as Partial) + + await store.getState().fetchWorktreeLineage() + + expect(runtimeEnvironmentCall).toHaveBeenCalledWith({ + selector: 'env-1', + method: 'worktree.lineageList', + params: undefined, + timeoutMs: 15_000 + }) + expect(mockApi.worktrees.listLineage).not.toHaveBeenCalled() + expect(store.getState().worktreeLineageById).toEqual({ [lineage.worktreeId]: lineage }) + }) + + it('updates lineage through the active remote runtime environment', async () => { + const store = createTestStore() + const lineage = makeLineage() + const child = makeWorktree({ + id: lineage.worktreeId, + repoId: 'repo1', + path: '/remote/child' + }) + const updatedChild = { ...child, lineage } + runtimeEnvironmentCall.mockResolvedValue({ + id: 'rpc-set-lineage', + ok: true, + result: { worktree: updatedChild }, + _meta: { runtimeId: 'runtime-remote' } + }) + store.setState({ + settings: { activeRuntimeEnvironmentId: 'env-1' } as never, + worktreesByRepo: { repo1: [child] }, + sortEpoch: 3 + } as Partial) + + await store.getState().updateWorktreeLineage(lineage.worktreeId, { + parentWorktreeId: lineage.parentWorktreeId + }) + + expect(runtimeEnvironmentCall).toHaveBeenCalledWith({ + selector: 'env-1', + method: 'worktree.set', + params: { + worktree: lineage.worktreeId, + parentWorktree: `id:${lineage.parentWorktreeId}` + }, + timeoutMs: 15_000 + }) + expect(mockApi.worktrees.updateLineage).not.toHaveBeenCalled() + expect(store.getState().worktreeLineageById).toEqual({ [lineage.worktreeId]: lineage }) + expect(store.getState().worktreesByRepo.repo1?.[0]).toEqual(updatedChild) + expect(store.getState().sortEpoch).toBe(4) + }) + + it('clears lineage through the active remote runtime environment', async () => { + const store = createTestStore() + const lineage = makeLineage() + const child = makeWorktree({ + id: lineage.worktreeId, + repoId: 'repo1', + path: '/remote/child', + lineage + } as Partial & { id: string; repoId: string }) + const updatedChild = { ...child, lineage: null } + runtimeEnvironmentCall.mockResolvedValue({ + id: 'rpc-clear-lineage', + ok: true, + result: { worktree: updatedChild }, + _meta: { runtimeId: 'runtime-remote' } + }) + store.setState({ + settings: { activeRuntimeEnvironmentId: 'env-1' } as never, + worktreesByRepo: { repo1: [child] }, + worktreeLineageById: { [lineage.worktreeId]: lineage }, + sortEpoch: 3 + } as Partial) + + await store.getState().updateWorktreeLineage(lineage.worktreeId, { noParent: true }) + + expect(runtimeEnvironmentCall).toHaveBeenCalledWith({ + selector: 'env-1', + method: 'worktree.set', + params: { worktree: lineage.worktreeId, noParent: true }, + timeoutMs: 15_000 + }) + expect(store.getState().worktreeLineageById).toEqual({}) + expect(store.getState().worktreesByRepo.repo1?.[0]).toEqual(updatedChild) + }) }) describe('updateWorktreeGitIdentity', () => { @@ -402,6 +700,30 @@ describe('removeWorktree state cleanup', () => { }) }) + it('cleans up the removed worktree lineage entry', async () => { + const store = createTestStore() + const wt = makeWorktree({ id: 'repo1::/path/wt1', repoId: 'repo1', path: '/path/wt1' }) + const childLineage = makeLineage({ worktreeId: wt.id }) + const siblingLineage = makeLineage({ + worktreeId: 'repo1::/path/wt2', + worktreeInstanceId: 'sibling-instance' + }) + + store.setState({ + worktreesByRepo: { repo1: [wt] }, + worktreeLineageById: { + [wt.id]: childLineage, + 'repo1::/path/wt2': siblingLineage + } + } as Partial) + + await store.getState().removeWorktree(wt.id) + + expect(store.getState().worktreeLineageById).toEqual({ + 'repo1::/path/wt2': siblingLineage + }) + }) + it('cleans up markdownViewMode for files in the removed worktree', async () => { const store = createTestStore() const wt = makeWorktree({ id: 'repo1::/path/wt1', repoId: 'repo1', path: '/path/wt1' }) @@ -1030,6 +1352,10 @@ describe('purgeWorktreeTerminalState direct (design §4.4)', () => { ], editorDrafts: { 'file-1': 'draft', 'file-99': 'other' }, activeWorktreeId: 'repoA::/a/wt1', + worktreeLineageById: { + 'repoA::/a/wt1': makeLineage({ worktreeId: 'repoA::/a/wt1' }), + 'repoA::/a/wt2': makeLineage({ worktreeId: 'repoA::/a/wt2' }) + }, activeFileId: 'file-1', activeTabId: 'tab-1', activeTabType: 'editor' as const @@ -1041,6 +1367,9 @@ describe('purgeWorktreeTerminalState direct (design §4.4)', () => { expect(s.tabsByWorktree).toEqual({ 'repoA::/a/wt2': [{ id: 'tab-3', worktreeId: 'repoA::/a/wt2' }] }) + expect(s.worktreeLineageById).toEqual({ + 'repoA::/a/wt2': makeLineage({ worktreeId: 'repoA::/a/wt2' }) + }) expect(s.terminalLayoutsByTabId).toEqual({ 'tab-3': { panes: [] } }) expect(s.ptyIdsByTabId).toEqual({ 'tab-3': ['pty-3'] }) expect(s.runtimePaneTitlesByTabId).toEqual({ 'tab-3': 'bash' }) diff --git a/src/renderer/src/store/slices/worktrees.ts b/src/renderer/src/store/slices/worktrees.ts index 53ae531c8..7912964c2 100644 --- a/src/renderer/src/store/slices/worktrees.ts +++ b/src/renderer/src/store/slices/worktrees.ts @@ -1,7 +1,12 @@ /* eslint-disable max-lines */ import type { StateCreator } from 'zustand' import type { AppState } from '../types' -import type { Worktree, WorkspaceVisibleTabType, WorktreeMeta } from '../../../../shared/types' +import type { + Worktree, + WorkspaceVisibleTabType, + WorktreeLineage, + WorktreeMeta +} from '../../../../shared/types' import { findWorktreeById, applyWorktreeUpdates, @@ -23,6 +28,29 @@ function arraysShallowEqual(a: string[] | undefined, b: string[] | undefined): b return a.every((v, i) => v === b[i]) } +function areLineageRecordsEqual( + a: WorktreeLineage | null | undefined, + b: WorktreeLineage | null | undefined +): boolean { + if (!a || !b) { + return !a && !b + } + return ( + a.worktreeId === b.worktreeId && + a.worktreeInstanceId === b.worktreeInstanceId && + a.parentWorktreeId === b.parentWorktreeId && + a.parentWorktreeInstanceId === b.parentWorktreeInstanceId && + a.origin === b.origin && + a.capture.source === b.capture.source && + a.capture.confidence === b.capture.confidence && + a.orchestrationRunId === b.orchestrationRunId && + a.taskId === b.taskId && + a.coordinatorHandle === b.coordinatorHandle && + a.createdByTerminalHandle === b.createdByTerminalHandle && + a.createdAt === b.createdAt + ) +} + function areWorktreesEqual(current: Worktree[] | undefined, next: Worktree[]): boolean { if (!current || current.length !== next.length) { return false @@ -32,6 +60,7 @@ function areWorktreesEqual(current: Worktree[] | undefined, next: Worktree[]): b const candidate = next[index] return ( worktree.id === candidate.id && + worktree.instanceId === candidate.instanceId && worktree.repoId === candidate.repoId && worktree.path === candidate.path && worktree.head === candidate.head && @@ -55,7 +84,17 @@ function areWorktreesEqual(current: Worktree[] | undefined, next: Worktree[]): b worktree.pushTarget?.branchName === candidate.pushTarget?.branchName && worktree.pushTarget?.remoteUrl === candidate.pushTarget?.remoteUrl && worktree.sparseBaseRef === candidate.sparseBaseRef && - arraysShallowEqual(worktree.sparseDirectories, candidate.sparseDirectories) + arraysShallowEqual(worktree.sparseDirectories, candidate.sparseDirectories) && + (worktree as WorktreeWithLineage).parentWorktreeId === + (candidate as WorktreeWithLineage).parentWorktreeId && + arraysShallowEqual( + (worktree as WorktreeWithLineage).childWorktreeIds, + (candidate as WorktreeWithLineage).childWorktreeIds + ) && + areLineageRecordsEqual( + (worktree as WorktreeWithLineage).lineage, + (candidate as WorktreeWithLineage).lineage + ) ) }) } @@ -64,6 +103,29 @@ function toVisibleTabType(contentType: string): WorkspaceVisibleTabType { return contentType === 'browser' ? 'browser' : contentType === 'terminal' ? 'terminal' : 'editor' } +type WorktreeWithLineage = Worktree & { + parentWorktreeId?: string | null + childWorktreeIds?: string[] + lineage?: WorktreeLineage | null +} + +function replaceWorktreeInRepoLists( + worktreesByRepo: Record, + updatedWorktree: Worktree +): Record { + const repoId = getRepoIdFromWorktreeId(updatedWorktree.id) + const current = worktreesByRepo[repoId] + if (!current) { + return worktreesByRepo + } + return { + ...worktreesByRepo, + [repoId]: current.map((worktree) => + worktree.id === updatedWorktree.id ? updatedWorktree : worktree + ) + } +} + async function listWorktreesForRepo( settings: AppState['settings'], repoId: string @@ -83,6 +145,39 @@ async function listWorktreesForRepo( return result.worktrees } +async function listWorktreeLineageForRuntime( + settings: AppState['settings'] +): Promise> { + const target = getActiveRuntimeTarget(settings) + if (target.kind === 'local') { + return window.api.worktrees.listLineage() + } + return ( + await callRuntimeRpc<{ lineage: Record }>( + target, + 'worktree.lineageList', + undefined, + { timeoutMs: 15_000 } + ) + ).lineage +} + +async function refreshRemoteWorktreeLineageBestEffort( + settings: AppState['settings'], + set: (partial: Partial) => void +): Promise { + if (getActiveRuntimeTarget(settings).kind === 'local') { + return + } + try { + set({ worktreeLineageById: await listWorktreeLineageForRuntime(settings) }) + } catch (err) { + // Why: lineage is supplemental to the worktree list. A remote timeout here + // must not discard a successful worktree refresh. + console.error('Failed to fetch worktree lineage:', err) + } +} + async function persistWorktreeMeta( settings: AppState['settings'], worktreeId: string, @@ -103,6 +198,7 @@ async function persistWorktreeMeta( export const createWorktreeSlice: StateCreator = (set, get) => ({ worktreesByRepo: {}, + worktreeLineageById: {}, activeWorktreeId: null, deleteStateByWorktreeId: {}, baseStatusByWorktreeId: {}, @@ -114,9 +210,11 @@ export const createWorktreeSlice: StateCreator fetchWorktrees: async (repoId) => { try { - const worktrees = await listWorktreesForRepo(get().settings, repoId) + const settings = get().settings + const worktrees = await listWorktreesForRepo(settings, repoId) const current = get().worktreesByRepo[repoId] if (areWorktreesEqual(current, worktrees)) { + await refreshRemoteWorktreeLineageBestEffort(settings, set) return } @@ -138,6 +236,7 @@ export const createWorktreeSlice: StateCreator worktreesByRepo: { ...s.worktreesByRepo, [repoId]: worktrees }, sortEpoch: s.sortEpoch + 1 })) + await refreshRemoteWorktreeLineageBestEffort(settings, set) } catch (err) { console.error(`Failed to fetch worktrees for repo ${repoId}:`, err) } @@ -209,6 +308,56 @@ export const createWorktreeSlice: StateCreator set({ hasHydratedWorktreePurge: true }) }, + fetchWorktreeLineage: async () => { + try { + set({ worktreeLineageById: await listWorktreeLineageForRuntime(get().settings) }) + } catch (err) { + console.error('Failed to fetch worktree lineage:', err) + } + }, + + updateWorktreeLineage: async (worktreeId, args) => { + try { + const target = getActiveRuntimeTarget(get().settings) + let updatedRemoteWorktree: WorktreeWithLineage | undefined + const lineage = + target.kind === 'local' + ? await window.api.worktrees.updateLineage({ worktreeId, ...args }) + : await callRuntimeRpc<{ worktree: WorktreeWithLineage }>( + target, + 'worktree.set', + { + worktree: worktreeId, + ...(args.parentWorktreeId ? { parentWorktree: `id:${args.parentWorktreeId}` } : {}), + ...(args.noParent === true ? { noParent: true } : {}) + }, + { timeoutMs: 15_000 } + ).then((result) => { + updatedRemoteWorktree = result.worktree + return result.worktree.lineage ?? null + }) + set((s) => { + const next = { ...s.worktreeLineageById } + if (lineage) { + next[worktreeId] = lineage + } else { + delete next[worktreeId] + } + return { + worktreeLineageById: next, + worktreesByRepo: + target.kind === 'local' || !updatedRemoteWorktree + ? s.worktreesByRepo + : replaceWorktreeInRepoLists(s.worktreesByRepo, updatedRemoteWorktree), + sortEpoch: s.sortEpoch + 1 + } + }) + } catch (err) { + console.error('Failed to update worktree lineage:', err) + await get().fetchWorktreeLineage() + } + }, + updateWorktreeGitIdentity: (worktreeId, identity) => { set((s) => { const repoId = getRepoIdFromWorktreeId(worktreeId) @@ -424,6 +573,8 @@ export const createWorktreeSlice: StateCreator } const nextDeleteState = { ...s.deleteStateByWorktreeId } delete nextDeleteState[worktreeId] + const nextLineage = { ...s.worktreeLineageById } + delete nextLineage[worktreeId] // Clean up editor files belonging to this worktree const newOpenFiles = s.openFiles.filter((f) => f.worktreeId !== worktreeId) const nextBrowserTabsByWorktree = { ...s.browserTabsByWorktree } @@ -521,6 +672,7 @@ export const createWorktreeSlice: StateCreator : s.lastVisitedAtByWorktreeId return { worktreesByRepo: next, + worktreeLineageById: nextLineage, tabsByWorktree: nextTabs, ptyIdsByTabId: nextPtyIdsByTabId, runtimePaneTitlesByTabId: nextRuntimePaneTitlesByTabId, @@ -1108,6 +1260,7 @@ export const createWorktreeSlice: StateCreator return { // Worktree-scoped terminal/tab state + worktreeLineageById: omitByWorktree(s.worktreeLineageById), tabsByWorktree: omitByWorktree(s.tabsByWorktree), terminalLayoutsByTabId: omitByTabId(s.terminalLayoutsByTabId), ptyIdsByTabId: omitByTabId(s.ptyIdsByTabId), diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts index 172742c0b..5e98aa3e6 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -11,7 +11,8 @@ import type { Repo, SearchResult, StatsSummary, - Worktree + Worktree, + WorktreeLineage } from '../../../shared/types' import { getDefaultOnboardingState, @@ -323,6 +324,23 @@ function createWorktreesApi(): NonNullable['worktrees']> { ...updates }) ).worktree, + listLineage: async () => + ( + await callRuntimeResult<{ lineage: Record }>( + 'worktree.lineageList' + ) + ).lineage, + updateLineage: async ({ worktreeId, parentWorktreeId, noParent }) => { + cachedWorktrees = null + const result = await callRuntimeResult<{ + worktree: Worktree & { lineage?: WorktreeLineage | null } + }>('worktree.set', { + worktree: worktreeId, + parentWorktree: parentWorktreeId, + noParent + }) + return result.worktree.lineage ?? null + }, persistSortOrder: async ({ orderedIds }) => { await callRuntimeResult('worktree.persistSortOrder', { orderedIds }) }, diff --git a/src/shared/constants.ts b/src/shared/constants.ts index d451336ec..f007b726f 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -315,6 +315,7 @@ export function getDefaultPersistedState(homedir: string): PersistedState { repos: [], sparsePresetsByRepo: {}, worktreeMeta: {}, + worktreeLineageById: {}, settings: getDefaultSettings(homedir), ui: getDefaultUIState(), githubCache: { pr: {}, issue: {} }, @@ -336,6 +337,7 @@ export function getDefaultUIState(): PersistedUIState { sidebarWidth: 280, rightSidebarWidth: 350, groupBy: 'repo', + showWorkspaceLineage: false, sortBy: 'recent', showActiveOnly: false, hideDefaultBranchWorkspace: false, diff --git a/src/shared/runtime-types.ts b/src/shared/runtime-types.ts index 6d89e8d79..9afa5e142 100644 --- a/src/shared/runtime-types.ts +++ b/src/shared/runtime-types.ts @@ -1,13 +1,15 @@ /* eslint-disable max-lines -- Why: shared type definitions for all runtime RPC methods live in one file for discoverability and import simplicity. */ -import type { TerminalPaneLayoutNode } from './types' import type { BrowserCookieImportResult, BrowserSessionProfile, BrowserSessionProfileSource, GitWorktreeInfo, Repo, - Worktree + Worktree, + WorktreeLineage, + WorktreeLineageWarning } from './types' +import type { TerminalPaneLayoutNode } from './types' import type { RuntimeMarkdownReadTabResult, RuntimeMarkdownSaveTabResult @@ -304,6 +306,8 @@ export type RuntimeWorktreePsSummary = { repo: string path: string branch: string + parentWorktreeId: string | null + childWorktreeIds: string[] displayName: string linkedIssue: number | null linkedPR: { number: number; state: string } | null @@ -319,9 +323,19 @@ export type RuntimeWorktreePsSummary = { export type RuntimeWorktreeStatus = 'active' | 'working' | 'permission' | 'done' | 'inactive' export type RuntimeWorktreeRecord = Worktree & { + parentWorktreeId: string | null + childWorktreeIds: string[] + lineage: WorktreeLineage | null git: GitWorktreeInfo } +export type RuntimeWorktreeCreateResult = { + worktree: RuntimeWorktreeRecord + lineage: WorktreeLineage | null + warnings: WorktreeLineageWarning[] + warning?: string +} + export type RuntimeWorktreePsResult = { worktrees: RuntimeWorktreePsSummary[] totalCount: number diff --git a/src/shared/types.ts b/src/shared/types.ts index b85faf388..00e72770b 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -121,6 +121,7 @@ export type WorkspaceStatusDefinition = { export type Worktree = { id: string // `${repoId}::${path}` + instanceId?: string repoId: string displayName: string comment: string @@ -172,6 +173,8 @@ export type GitPushTarget = { // ─── Worktree metadata (persisted user-authored fields only) ───────── export type WorktreeMeta = { + /** Immutable per-workspace-instance ID used to reject stale lineage after path reuse. */ + instanceId?: string displayName: string comment: string linkedIssue: number | null @@ -202,6 +205,45 @@ export type WorktreeMeta = { diffComments?: DiffComment[] } +export type WorktreeLineageOrigin = 'orchestration' | 'cli' | 'manual' +export type WorktreeLineageCaptureConfidence = 'explicit' | 'inferred' +export type WorktreeLineageCaptureSource = + | 'explicit-cli-flag' + | 'cwd-context' + | 'terminal-context' + | 'orchestration-context' + | 'manual-action' + +export type WorktreeLineageCapture = { + source: WorktreeLineageCaptureSource + confidence: WorktreeLineageCaptureConfidence +} + +export type WorktreeLineage = { + worktreeId: string + worktreeInstanceId: string + parentWorktreeId: string + parentWorktreeInstanceId: string + origin: WorktreeLineageOrigin + capture: WorktreeLineageCapture + orchestrationRunId?: string + taskId?: string + coordinatorHandle?: string + createdByTerminalHandle?: string + createdAt: number +} + +export type WorktreeLineageWarningCode = + | 'LINEAGE_PARENT_CONTEXT_MISSING' + | 'LINEAGE_PARENT_CONTEXT_CONFLICT' + | 'LINEAGE_PARENT_INSTANCE_STALE' + +export type WorktreeLineageWarning = { + code: WorktreeLineageWarningCode + message: string + details?: Record +} + // ─── Diff line comments ────────────────────────────────────────────── // Why: users leave review notes on specific lines of the modified side of // a diff so they can be handed back to an AI agent (pasted into a terminal @@ -988,7 +1030,14 @@ export type CreateWorktreeArgs = { } export type CreateWorktreeResult = { - worktree: Worktree + worktree: Worktree & { + parentWorktreeId?: string | null + childWorktreeIds?: string[] + lineage?: WorktreeLineage | null + git?: GitWorktreeInfo + } + lineage?: WorktreeLineage | null + warnings?: WorktreeLineageWarning[] setup?: WorktreeSetupLaunch warning?: string initialBaseStatus?: WorktreeBaseStatusEvent @@ -1621,6 +1670,7 @@ export type PersistedUIState = { sidebarWidth: number rightSidebarWidth: number groupBy: 'none' | 'repo' | 'pr-status' + showWorkspaceLineage?: boolean sortBy: 'name' | 'smart' | 'recent' | 'repo' showActiveOnly: boolean /** Hide the repo's original checked-out branch from workspace navigation @@ -1819,6 +1869,7 @@ export type PersistedState = { * presets are managed from the new-workspace composer and repo settings. */ sparsePresetsByRepo: Record worktreeMeta: Record + worktreeLineageById: Record settings: GlobalSettings ui: PersistedUIState githubCache: { diff --git a/tests/e2e/worktree-lineage.spec.ts b/tests/e2e/worktree-lineage.spec.ts new file mode 100644 index 000000000..201965723 --- /dev/null +++ b/tests/e2e/worktree-lineage.spec.ts @@ -0,0 +1,127 @@ +import type { Page } from '@stablyai/playwright-test' +import { test, expect } from './helpers/orca-app' +import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' + +type LineageScenario = { + parentId: string + childId: string +} + +function worktreeOption(page: Page, worktreeId: string) { + return page.locator(`[id="worktree-list-option-${encodeURIComponent(worktreeId)}"]`) +} + +async function seedLineageScenario(page: Page): Promise { + return page.evaluate(() => { + const store = window.__store + if (!store) { + throw new Error('window.__store is not available') + } + + const state = store.getState() + state.setActiveView('terminal') + state.setSidebarOpen(true) + state.setGroupBy('none') + state.setSortBy('recent') + state.setShowWorkspaceLineage(true) + + const worktrees = Object.values(state.worktreesByRepo) + .flat() + .filter((worktree) => !worktree.isArchived) + if (worktrees.length < 2) { + throw new Error('Worktree lineage E2E needs at least two worktrees') + } + + const [parent, child] = worktrees + if (!parent.instanceId || !child.instanceId) { + throw new Error('Worktree lineage E2E needs instance-stamped worktrees') + } + store.setState((current) => ({ + worktreesByRepo: Object.fromEntries( + Object.entries(current.worktreesByRepo).map(([repoId, repoWorktrees]) => [ + repoId, + repoWorktrees.map((worktree) => { + if (worktree.id === parent.id) { + return { ...worktree, displayName: 'E2E lineage parent', sortOrder: 0 } + } + if (worktree.id === child.id) { + return { ...worktree, displayName: 'E2E lineage child', sortOrder: 1 } + } + return worktree + }) + ]) + ), + worktreeLineageById: { + ...current.worktreeLineageById, + [child.id]: { + worktreeId: child.id, + worktreeInstanceId: child.instanceId, + parentWorktreeId: parent.id, + parentWorktreeInstanceId: parent.instanceId, + origin: 'manual', + capture: { source: 'manual-action', confidence: 'explicit' }, + createdAt: Date.now() + } + } + })) + + store.getState().setActiveWorktree(parent.id) + return { parentId: parent.id, childId: child.id } + }) +} + +test.describe('Worktree Lineage', () => { + test.beforeEach(async ({ orcaPage }) => { + await waitForSessionReady(orcaPage) + await waitForActiveWorktree(orcaPage) + }) + + test('renders existing child lineage in the sidebar', async ({ orcaPage }) => { + const { parentId, childId } = await seedLineageScenario(orcaPage) + const parentRow = worktreeOption(orcaPage, parentId) + const childRow = worktreeOption(orcaPage, childId) + + await expect(parentRow).toContainText('E2E lineage parent') + await parentRow.click() + await expect(parentRow).toHaveAttribute('aria-current', 'page') + + await expect(childRow).toContainText('E2E lineage child') + const childToggle = parentRow.getByRole('button', { name: 'Hide 1 child workspace' }) + await expect(childToggle).toBeVisible({ timeout: 10_000 }) + await expect(childRow).toBeVisible() + + const positions = await orcaPage.evaluate( + ({ parentId, childId }) => { + const parent = document.getElementById( + `worktree-list-option-${encodeURIComponent(parentId)}` + ) + const child = document.getElementById(`worktree-list-option-${encodeURIComponent(childId)}`) + if (!parent || !child) { + return null + } + return { + parentTop: parent.getBoundingClientRect().top, + childTop: child.getBoundingClientRect().top + } + }, + { parentId, childId } + ) + expect(positions).not.toBeNull() + expect(positions!.childTop).toBeGreaterThan(positions!.parentTop) + + await childToggle.click() + await expect(parentRow.getByRole('button', { name: 'Show 1 child workspace' })).toBeVisible() + await expect(childRow).toBeHidden() + + await parentRow.getByRole('button', { name: 'Show 1 child workspace' }).click() + await childRow.click({ button: 'right' }) + await orcaPage.getByRole('menuitem', { name: 'Remove from Parent' }).click() + await expect(parentRow.getByRole('button', { name: /child workspace/ })).toHaveCount(0) + await expect(childRow).toBeVisible() + + await parentRow.click({ button: 'right' }) + await expect( + orcaPage.getByRole('menuitem', { name: 'Group under Active Workspace' }) + ).toHaveCount(0) + }) +})