Add workspace lineage grouping (#1885)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Brennan Benson
2026-05-15 17:21:00 -07:00
committed by GitHub
co-authored by Orca
parent 82f99ee6ef
commit bf85d51bc1
49 changed files with 4725 additions and 207 deletions
+91
View File
@@ -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> = {}): 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: []')
})
})
+16 -4
View File
@@ -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}`
+7 -1
View File
@@ -207,12 +207,18 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
},
'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}]`)
+91 -15
View File
@@ -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<string, string | boolean>): 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<string, CommandHandler> = {
'worktree ps': async ({ flags, client, json }) => {
const result = await client.call<RuntimeWorktreePsResult>('worktree.ps', {
@@ -50,28 +98,56 @@ export const WORKTREE_HANDLERS: Record<string, CommandHandler> = {
})
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<RuntimeWorktreeCreateResult>('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)
},
+7 -2
View File
@@ -152,10 +152,10 @@ Common Commands:
orca environment show --environment <selector> [--json]
orca environment rm --environment <selector> [--json]
orca worktree list [--repo <selector>] [--limit <n>] [--json]
orca worktree create --repo <selector> --name <name> [--base-branch <ref>] [--issue <number>] [--comment <text>] [--run-hooks] [--activate] [--json]
orca worktree create --repo <selector> --name <name> [--base-branch <ref>] [--issue <number>] [--comment <text>] [--parent-worktree <selector>] [--no-parent] [--run-hooks] [--activate] [--json]
orca worktree show --worktree <selector> [--json]
orca worktree current [--json]
orca worktree set --worktree <selector> [--display-name <name>] [--issue <number|null>] [--comment <text>] [--json]
orca worktree set --worktree <selector> [--display-name <name>] [--issue <number|null>] [--comment <text>] [--parent-worktree <selector>|--no-parent] [--json]
orca worktree rm --worktree <selector> [--force] [--run-hooks] [--json]
orca worktree ps [--limit <n>] [--json]
orca terminal list [--worktree <selector>] [--limit <n>] [--json]
@@ -178,6 +178,8 @@ Selectors:
--repo <selector> Registered repo selector such as id:<id>, name:<name>, or path:<path>
--worktree <selector> Worktree selector such as id:<id>, branch:<branch>, issue:<number>, path:<path>, or active/current
--terminal <handle> Runtime-issued terminal handle returned by \`orca terminal list --json\`
--parent-worktree <selector> 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> Text to send to the terminal
@@ -344,8 +346,11 @@ export function formatFlagHelp(flag: string): string {
limit: '--limit <n> Maximum number of rows to return',
'mouse-button': '--mouse-button <btn> Mouse button: left, right, or middle',
name: '--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 <n> Number of scroll pages',
'parent-worktree':
'--parent-worktree <selector> Parent worktree selector; create infers one by default',
path: '--path <path> Filesystem path to the repo',
query: '--query <text> Search text for matching refs',
ref: '--ref <ref> Base ref to persist for the repo',
+430 -5
View File
@@ -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'
+15 -3
View File
@@ -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 <selector> --name <name> [--base-branch <ref>] [--issue <number>] [--comment <text>] [--run-hooks] [--activate] [--json]',
'orca worktree create --repo <selector> --name <name> [--base-branch <ref>] [--issue <number>] [--comment <text>] [--parent-worktree <selector>] [--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 <selector> [--display-name <name>] [--issue <number|null>] [--comment <text>] [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'worktree', 'display-name', 'issue', 'comment']
'orca worktree set --worktree <selector> [--display-name <name>] [--issue <number|null>] [--comment <text>] [--parent-worktree <selector>|--no-parent] [--json]',
allowedFlags: [
...GLOBAL_FLAGS,
'worktree',
'display-name',
'issue',
'comment',
'parent-worktree',
'no-parent'
]
},
{
path: ['worktree', 'rm'],
+6
View File
@@ -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: '',
+1
View File
@@ -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,
+9
View File
@@ -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<WorktreeMeta> = {
// 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<WorktreeMeta> = {
// 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.
+143 -1
View File
@@ -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<typeof vi.fn>
@@ -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
+66
View File
@@ -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
+75 -1
View File
@@ -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> = {}): TerminalTab => (
...overrides
})
const makeWorktreeLineage = (overrides: Partial<WorktreeLineage> = {}): 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', () => {
+31
View File
@@ -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>): 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<string, WorktreeLineage> {
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,
File diff suppressed because it is too large Load Diff
+563 -11
View File
@@ -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<T extends Record<string, unknown>>(value: T): P
) as Partial<T>
}
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<CreateWorktreeResult> {
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<WorktreeMeta>) {
async updateManagedWorktreeMeta(
worktreeSelector: string,
updates: Partial<WorktreeMeta> & {
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<string>([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<WorktreeLineageResolution> {
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<WorktreeLineageCandidate | null> {
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<void> {
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<Record<string, WorktreeLineage>> {
await this.hydrateInferredWorktreeLineage()
return this.store?.getAllWorktreeLineage?.() ?? {}
}
private async resolveRepoSelector(selector: string): Promise<Repo> {
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<string, WorktreeLineage>()
const childIdsByParentId = new Map<string, string[]>()
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<RuntimeWorktreeScanResult> {
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<Map<string, ResolvedWorktree>> {
return new Map((await this.listResolvedWorktrees()).map((worktree) => [worktree.id, worktree]))
}
+11
View File
@@ -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' })
+27 -7
View File
@@ -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
}
+1
View File
@@ -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
+32
View File
@@ -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' }
})
})
})
+14
View File
@@ -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)
}
@@ -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(
@@ -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 }
}
+76 -2
View File
@@ -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',
+94 -45
View File
@@ -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<typeof runtime.updateManagedWorktreeMeta>[1])
})
}),
+7
View File
@@ -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<void>
updateMeta: (args: { worktreeId: string; updates: Partial<WorktreeMeta> }) => Promise<Worktree>
listLineage: () => Promise<Record<string, WorktreeLineage>>
updateLineage: (args: {
worktreeId: string
parentWorktreeId?: string
noParent?: boolean
}) => Promise<WorktreeLineage | null>
persistSortOrder: (args: { orderedIds: string[] }) => Promise<void>
onChanged: (callback: (data: { repoId: string }) => void) => () => void
onBaseStatus: (callback: (data: WorktreeBaseStatusEvent) => void) => () => void
+9
View File
@@ -465,6 +465,15 @@ const api = {
updates: Record<string, unknown>
}): Promise<unknown> => ipcRenderer.invoke('worktrees:updateMeta', args),
listLineage: (): Promise<Record<string, unknown>> =>
ipcRenderer.invoke('worktrees:listLineage'),
updateLineage: (args: {
worktreeId: string
parentWorktreeId?: string
noParent?: boolean
}): Promise<unknown> => ipcRenderer.invoke('worktrees:updateLineage', args),
persistSortOrder: (args: { orderedIds: string[] }): Promise<void> =>
ipcRenderer.invoke('worktrees:persistSortOrder', args),
+5
View File
@@ -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,
@@ -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() {
</ToggleGroup>
</div>
<DropdownMenuSeparator />
<DropdownMenuCheckboxItem
checked={showWorkspaceLineage}
onCheckedChange={(checked) => setShowWorkspaceLineage(Boolean(checked))}
onSelect={(e) => e.preventDefault()}
>
Nest child workspaces
</DropdownMenuCheckboxItem>
<DropdownMenuSeparator />
<DropdownMenuLabel>Sort by</DropdownMenuLabel>
<DropdownMenuRadioGroup
@@ -3,16 +3,19 @@ import React, { useEffect, useCallback, useState } from 'react'
import { useAppStore } from '@/store'
import { getHostedReviewCacheKey } from '@/store/slices/hosted-review'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip'
import {
AlertTriangle,
Bell,
ChevronDown,
GitMerge,
LoaderCircle,
CircleCheck,
CircleX,
Server,
ServerOff
ServerOff,
Workflow
} from 'lucide-react'
import StatusIndicator from './StatusIndicator'
import CacheTimer from './CacheTimer'
@@ -42,6 +45,12 @@ type WorktreeCardProps = {
isMultiSelected?: boolean
selectedWorktrees?: readonly Worktree[]
hideRepoBadge?: boolean
parentLabel?: string
lineageState?: 'valid' | 'missing'
lineageChildCount?: number
lineageCollapsed?: boolean
lineageChildren?: React.ReactNode
onLineageToggle?: (event: React.MouseEvent<HTMLButtonElement>) => void
onActivate?: () => void
onSelectionGesture?: (event: React.MouseEvent<HTMLDivElement>, worktreeId: string) => boolean
onContextMenuSelect?: (event: React.MouseEvent<HTMLDivElement>) => 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<HTMLDivElement>) => {
@@ -523,6 +545,23 @@ const WorktreeCard = React.memo(function WorktreeCard({
)}
<CacheTimer worktreeId={worktree.id} />
{parentLabel && (
<Badge
variant="outline"
className={cn(
'h-[16px] px-1.5 text-[10px] font-medium rounded shrink-0 gap-1 leading-none',
lineageState === 'missing'
? 'text-muted-foreground border-border bg-muted/40'
: 'text-muted-foreground border-border bg-accent/50'
)}
>
<Workflow className="size-2.5" />
<span className="max-w-[7rem] truncate">
{lineageState === 'missing' ? 'Missing parent' : `from ${parentLabel}`}
</span>
</Badge>
)}
</div>
{/* 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') && <WorktreeCardAgents worktreeId={worktree.id} />}
{showLineageChildChip && (
<div
className="relative mt-1 flex min-w-0 justify-start"
style={{ color: 'color-mix(in srgb, var(--muted-foreground) 42%, var(--sidebar))' }}
>
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="ghost"
size="xs"
className="relative z-10 h-[18px] max-w-[8rem] gap-1 rounded-md border border-sidebar-border bg-sidebar px-1.5 text-[10px] font-medium leading-none text-muted-foreground shadow-none hover:bg-sidebar-accent hover:text-foreground focus-visible:ring-1 focus-visible:ring-sidebar-ring"
aria-label={`${lineageCollapsed ? 'Show' : 'Hide'} ${childWorkspaceLabel}`}
aria-expanded={!lineageCollapsed}
onClick={onLineageToggle}
>
<Workflow className="size-2.5" />
<span className="truncate">{childWorkspaceShortLabel}</span>
<ChevronDown
className={cn(
'size-2.5 transition-transform',
lineageCollapsed && '-rotate-90'
)}
/>
</Button>
</TooltipTrigger>
<TooltipContent side="right" sideOffset={8}>
{lineageCollapsed ? 'Show child workspaces' : 'Hide child workspaces'}
</TooltipContent>
</Tooltip>
</div>
)}
{lineageChildren && <div className="-ml-4 mt-1.5 space-y-1">{lineageChildren}</div>}
</div>
</div>
)
@@ -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)
})
})
@@ -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<number | null>(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 (
<>
<div
className="relative"
onContextMenuCapture={(event) => {
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}
</div>
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 (
<div
className="relative"
{...{ [WORKTREE_CONTEXT_MENU_SCOPE_ATTR]: 'worktree' }}
onContextMenuCapture={(event) => {
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}
<DropdownMenu open={menuOpen} onOpenChange={setMenuOpen} modal={false}>
<DropdownMenuTrigger asChild>
<button
@@ -266,7 +338,14 @@ const WorktreeContextMenu = React.memo(function WorktreeContextMenu({
style={{ left: menuPoint.x, top: menuPoint.y }}
/>
</DropdownMenuTrigger>
<DropdownMenuContent className={cn('w-52', contentClassName)} sideOffset={0} align="start">
<DropdownMenuContent
className={cn('w-52', contentClassName)}
sideOffset={0}
align="start"
onPointerUpCapture={suppressOpeningPointerEvent}
onMouseUpCapture={suppressOpeningPointerEvent}
onClickCapture={suppressOpeningPointerEvent}
>
{!isMultiContext && (
<>
<WorktreeOpenInSubMenu
@@ -304,6 +383,31 @@ const WorktreeContextMenu = React.memo(function WorktreeContextMenu({
{worktree.comment ? 'Edit Comment' : 'Add Comment'}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onSelect={handleOpenParent}
disabled={isDeleting || !validParentWorktreeId}
>
<Workflow className="size-3.5" />
Open Parent Workspace
</DropdownMenuItem>
{lineage && (
<DropdownMenuItem onSelect={handleRemoveParentLink} disabled={isDeleting}>
<Unlink className="size-3.5" />
Remove from Parent
</DropdownMenuItem>
)}
<DropdownMenuSeparator />
</>
)}
{isMultiContext && (
<>
{hasAnyContextLineage && (
<DropdownMenuItem onSelect={handleRemoveParentLink} disabled={deletingContext}>
<Unlink className="size-3.5" />
Remove from Parent
</DropdownMenuItem>
)}
<DropdownMenuSeparator />
</>
)}
<DropdownMenuSub>
@@ -375,9 +479,14 @@ const WorktreeContextMenu = React.memo(function WorktreeContextMenu({
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</>
</div>
)
})
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
}
@@ -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<string>
@@ -111,6 +118,8 @@ type VirtualizedWorktreeViewportProps = {
worktree: Worktree
) => readonly Worktree[]
repoMap: Map<string, Repo>
worktreeMap: Map<string, Worktree>
worktreeLineageById: Record<string, WorktreeLineage>
repoOrder: Map<string, number>
// 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<number>
}
type WorktreeItemRow = Extract<Row, { type: 'item' }>
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<string>()
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<string>(),
repoOrder,
workspaceStatuses,
repoGroupOrdering
repoGroupOrdering,
worktreeLineageById,
worktreeMap,
showWorkspaceLineage
).filter((r): r is Extract<Row, { type: 'item' }> => 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
/>
</div>
{row.repo ? (
{row.repo && groupBy === 'repo' ? (
<Tooltip>
<TooltipTrigger asChild>
<Button
@@ -667,16 +793,212 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
)
}
const renderLineageChildPreview = (child: WorktreeItemRow) => {
const isActive = activeWorktreeId === child.worktree.id
const handleClick = (event: React.MouseEvent<HTMLDivElement>) => {
event.preventDefault()
event.stopPropagation()
const selectionOnly = onSelectionGesture(event, child.worktree.id)
if (!selectionOnly) {
activateAndRevealWorktree(child.worktree.id)
}
}
return (
<div
key={child.worktree.id}
style={{ paddingLeft: `${Math.max(0, child.depth - 1) * LINEAGE_INDENT}px` }}
>
<WorktreeContextMenu
worktree={child.worktree}
selectedWorktrees={selectedWorktrees}
onContextMenuSelect={(event) => onContextMenuSelect(event, child.worktree)}
>
<div
id={getWorktreeOptionId(child.worktree.id)}
role="option"
aria-selected={selectedWorktreeIds.has(child.worktree.id)}
aria-current={isActive ? 'page' : undefined}
className={cn(
'flex cursor-pointer items-start gap-1.5 rounded-md border border-transparent px-2 py-1.5 transition-colors',
isActive
? 'border-black/[0.015] bg-black/[0.08] shadow-[0_1px_2px_rgba(0,0,0,0.04)] dark:border-border/40 dark:bg-white/[0.10] dark:shadow-[0_1px_2px_rgba(0,0,0,0.03)]'
: 'hover:bg-sidebar-accent/40'
)}
onClick={handleClick}
onDoubleClick={(event) => event.stopPropagation()}
>
<span className="mt-[2px] flex w-4 shrink-0 justify-center pt-[2px]">
<span className="size-2 rounded-full bg-emerald-500" />
</span>
<div className="min-w-0 flex-1">
<div className="truncate text-[12px] leading-tight text-foreground">
{child.worktree.displayName}
</div>
<div className="mt-1 flex min-w-0 items-center gap-1.5">
{child.repo && groupBy !== 'repo' ? (
<span className="flex h-[16px] shrink-0 items-center gap-1.5 rounded-[4px] border border-border bg-accent px-1.5 text-[10px] font-semibold leading-none text-foreground dark:bg-accent/50 dark:border-border/60">
<span
className="size-1.5 rounded-full"
style={{ backgroundColor: child.repo.badgeColor }}
/>
<span className="max-w-[6rem] truncate lowercase">
{child.repo.displayName}
</span>
</span>
) : null}
<span className="truncate text-[10.5px] leading-none text-muted-foreground">
{branchDisplayName(child.worktree.branch)}
</span>
</div>
{child.worktree.linkedIssue || child.worktree.comment ? (
<div className="mt-1.5 truncate text-[10.5px] leading-tight text-muted-foreground">
{child.worktree.linkedIssue ? (
<span className="font-medium text-foreground/80">
#{child.worktree.linkedIssue}
</span>
) : null}
{child.worktree.linkedIssue && child.worktree.comment ? ' ' : null}
{child.worktree.comment}
</div>
) : null}
{child.lineageChildCount > 0 && child.lineageGroupKey ? (
<div className="mt-1.5 flex min-w-0 justify-start">
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="ghost"
size="xs"
className="h-[18px] max-w-[8rem] gap-1 rounded-md border border-sidebar-border bg-sidebar px-1.5 text-[10px] font-medium leading-none text-muted-foreground shadow-none hover:bg-sidebar-accent hover:text-foreground focus-visible:ring-1 focus-visible:ring-sidebar-ring"
aria-label={`${child.lineageCollapsed ? 'Show' : 'Hide'} ${
child.lineageChildCount
} child ${
child.lineageChildCount === 1 ? 'workspace' : 'workspaces'
}`}
aria-expanded={!child.lineageCollapsed}
onClick={(event) => {
event.preventDefault()
event.stopPropagation()
toggleGroup(child.lineageGroupKey!)
}}
>
<Workflow className="size-2.5" />
<span className="truncate">
{child.lineageChildCount}{' '}
{child.lineageChildCount === 1 ? 'child' : 'children'}
</span>
<ChevronDown
className={cn(
'size-2.5 transition-transform',
child.lineageCollapsed && '-rotate-90'
)}
/>
</Button>
</TooltipTrigger>
<TooltipContent side="right" sideOffset={8}>
{child.lineageCollapsed
? 'Show child workspaces'
: 'Hide child workspaces'}
</TooltipContent>
</Tooltip>
</div>
) : null}
</div>
</div>
</WorktreeContextMenu>
</div>
)
}
const renderWorktreeRow = (
itemRow: WorktreeItemRow,
nested: boolean,
lineageChildren?: React.ReactNode,
forceActiveSurface = false
) => {
const lineageToggleGroupKey = itemRow.lineageGroupKey
return (
<div
key={itemRow.worktree.id}
id={getWorktreeOptionId(itemRow.worktree.id)}
role="option"
aria-selected={selectedWorktreeIds.has(itemRow.worktree.id)}
aria-current={activeWorktreeId === itemRow.worktree.id ? 'page' : undefined}
className="relative"
style={{
paddingLeft:
nested && itemRow.depth > 0
? `${Math.max(0, itemRow.depth - 1) * LINEAGE_INDENT}px`
: itemRow.depth > 0
? `${itemRow.depth * LINEAGE_INDENT}px`
: undefined
}}
>
<WorktreeCard
worktree={itemRow.worktree}
repo={itemRow.repo}
isActive={forceActiveSurface || activeWorktreeId === itemRow.worktree.id}
isMultiSelected={selectedWorktreeIds.has(itemRow.worktree.id)}
selectedWorktrees={selectedWorktrees}
onSelectionGesture={onSelectionGesture}
onContextMenuSelect={(event) => 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
}
/>
</div>
)
}
if (row.type === 'lineage-group') {
const [parent, ...children] = row.rows
const childIsActive = children.some((child) => child.worktree.id === activeWorktreeId)
return (
<div
key={vItem.key}
role="presentation"
data-index={vItem.index}
ref={virtualizer.measureElement}
className="absolute left-0 right-0"
style={{ transform: `translateY(${vItem.start}px)` }}
>
<div className="overflow-visible">
{parent
? renderWorktreeRow(
parent,
false,
children.length > 0 ? children.map(renderLineageChildPreview) : undefined,
childIsActive
)
: null}
</div>
</div>
)
}
const itemWorkspaceStatus =
groupBy === 'none' ? getWorkspaceStatus(row.worktree, workspaceStatuses) : null
return (
<div
key={vItem.key}
id={getWorktreeOptionId(row.worktree.id)}
role="option"
aria-selected={selectedWorktreeIds.has(row.worktree.id)}
aria-current={activeWorktreeId === row.worktree.id ? 'page' : undefined}
role="presentation"
data-index={vItem.index}
ref={virtualizer.measureElement}
data-workspace-status-drop-target={itemWorkspaceStatus ? '' : undefined}
@@ -695,16 +1017,7 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
: undefined
}
>
<WorktreeCard
worktree={row.worktree}
repo={row.repo}
isActive={activeWorktreeId === row.worktree.id}
isMultiSelected={selectedWorktreeIds.has(row.worktree.id)}
selectedWorktrees={selectedWorktrees}
onSelectionGesture={onSelectionGesture}
onContextMenuSelect={(event) => onContextMenuSelect(event, row.worktree)}
hideRepoBadge={groupBy === 'repo'}
/>
{renderWorktreeRow(row, false)}
</div>
)
})}
@@ -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) => {
@@ -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(
@@ -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<string, WorktreeLineage>,
worktreeMap: Map<string, Worktree>
): 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<string, Repo>,
@@ -118,8 +170,11 @@ export function getPRGroupKey(
function emitPinnedGroup(
worktrees: Worktree[],
repoMap: Map<string, Repo>,
lineageById: Record<string, WorktreeLineage>,
worktreeMap: Map<string, Worktree>,
collapsedGroups: Set<string>,
result: Row[],
showLineageContext: boolean,
force = false
): Set<string> {
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<string, Repo>,
lineageById: Record<string, WorktreeLineage>,
worktreeMap: Map<string, Worktree>,
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<string, Repo>,
lineageById: Record<string, WorktreeLineage>,
worktreeMap: Map<string, Worktree>,
options: {
nestLineage: boolean
showLineageContext: boolean
collapsedGroups: Set<string>
}
): 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<string, Worktree[]>()
const childIds = new Set<string>()
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<string>()
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<string>,
repoOrder?: Map<string, number>,
workspaceStatuses: readonly WorkspaceStatusDefinition[] = cloneDefaultWorkspaceStatuses(),
repoGroupOrdering: RepoGroupOrdering = 'manual'
repoGroupOrdering: RepoGroupOrdering = 'manual',
lineageById: Record<string, WorktreeLineage> = {},
worktreeMap: Map<string, Worktree> = 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<string, { label: string; items: Worktree[]; repo?: Repo }>()
@@ -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
})
}
}
+4 -1
View File
@@ -79,6 +79,7 @@ async function prepareRemoteWorkspaceTarget(targetId: string): Promise<boolean>
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.
@@ -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 {
@@ -35,6 +35,7 @@ export function getStartupErrorFallbackUI(uiHydrated: boolean): PersistedUIState
sidebarWidth: 280,
rightSidebarWidth: 350,
groupBy: 'none',
showWorkspaceLineage: false,
sortBy: 'name',
showActiveOnly: false,
hideDefaultBranchWorkspace: false,
+27 -1
View File
@@ -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({})
@@ -33,6 +33,7 @@ function runtimeScopedStateReset(): Partial<AppState> {
sparsePresetsLoadStatusByRepo: {},
sparsePresetsErrorByRepo: {},
worktreesByRepo: {},
worktreeLineageById: {},
activeWorktreeId: null,
deleteStateByWorktreeId: {},
baseStatusByWorktreeId: {},
@@ -303,6 +304,7 @@ export const createSettingsSlice: StateCreator<AppState, [], [], SettingsSlice>
// while the new environment is loading.
await get().fetchRepos()
await get().fetchAllWorktrees()
await get().fetchWorktreeLineage()
await get().fetchBrowserSessionProfiles()
return true
} catch (err) {
+7 -1
View File
@@ -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<AppState, [], [], UISlice> = (set, get)
set({ groupBy: g, collapsedGroups: new Set<string>() })
},
showWorkspaceLineage: false,
setShowWorkspaceLineage: (v) => set({ showWorkspaceLineage: v }),
sortBy: 'recent',
setSortBy: (s) => set({ sortBy: s }),
@@ -886,7 +891,8 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (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
@@ -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<string, Worktree[]>
worktreeLineageById: Record<string, WorktreeLineage>
activeWorktreeId: string | null
deleteStateByWorktreeId: Record<string, WorktreeDeleteState>
baseStatusByWorktreeId: Record<string, WorktreeBaseStatusEvent>
@@ -62,6 +64,11 @@ export type WorktreeSlice = {
hasHydratedWorktreePurge: boolean
fetchWorktrees: (repoId: string) => Promise<void>
fetchAllWorktrees: () => Promise<void>
fetchWorktreeLineage: () => Promise<void>
updateWorktreeLineage: (
worktreeId: string,
args: { parentWorktreeId?: string; noParent?: boolean }
) => Promise<void>
createWorktree: (
repoId: string,
name: string,
+331 -2
View File
@@ -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<Worktree> & { id: string; repoId: strin
}
}
function makeLineage(overrides: Partial<WorktreeLineage> = {}): 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<AppState>)
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<AppState>)
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<AppState>)
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<AppState>)
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<AppState>)
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<AppState>)
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<AppState>)
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<Worktree> & { 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<AppState>)
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<AppState>)
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' })
+156 -3
View File
@@ -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<string, Worktree[]>,
updatedWorktree: Worktree
): Record<string, Worktree[]> {
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<Record<string, WorktreeLineage>> {
const target = getActiveRuntimeTarget(settings)
if (target.kind === 'local') {
return window.api.worktrees.listLineage()
}
return (
await callRuntimeRpc<{ lineage: Record<string, WorktreeLineage> }>(
target,
'worktree.lineageList',
undefined,
{ timeoutMs: 15_000 }
)
).lineage
}
async function refreshRemoteWorktreeLineageBestEffort(
settings: AppState['settings'],
set: (partial: Partial<AppState>) => void
): Promise<void> {
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<AppState, [], [], WorktreeSlice> = (set, get) => ({
worktreesByRepo: {},
worktreeLineageById: {},
activeWorktreeId: null,
deleteStateByWorktreeId: {},
baseStatusByWorktreeId: {},
@@ -114,9 +210,11 @@ export const createWorktreeSlice: StateCreator<AppState, [], [], WorktreeSlice>
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<AppState, [], [], WorktreeSlice>
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<AppState, [], [], WorktreeSlice>
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<AppState, [], [], WorktreeSlice>
}
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<AppState, [], [], WorktreeSlice>
: s.lastVisitedAtByWorktreeId
return {
worktreesByRepo: next,
worktreeLineageById: nextLineage,
tabsByWorktree: nextTabs,
ptyIdsByTabId: nextPtyIdsByTabId,
runtimePaneTitlesByTabId: nextRuntimePaneTitlesByTabId,
@@ -1108,6 +1260,7 @@ export const createWorktreeSlice: StateCreator<AppState, [], [], WorktreeSlice>
return {
// Worktree-scoped terminal/tab state
worktreeLineageById: omitByWorktree(s.worktreeLineageById),
tabsByWorktree: omitByWorktree(s.tabsByWorktree),
terminalLayoutsByTabId: omitByTabId(s.terminalLayoutsByTabId),
ptyIdsByTabId: omitByTabId(s.ptyIdsByTabId),
+19 -1
View File
@@ -11,7 +11,8 @@ import type {
Repo,
SearchResult,
StatsSummary,
Worktree
Worktree,
WorktreeLineage
} from '../../../shared/types'
import {
getDefaultOnboardingState,
@@ -323,6 +324,23 @@ function createWorktreesApi(): NonNullable<Partial<PreloadApi>['worktrees']> {
...updates
})
).worktree,
listLineage: async () =>
(
await callRuntimeResult<{ lineage: Record<string, WorktreeLineage> }>(
'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 })
},
+2
View File
@@ -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,
+16 -2
View File
@@ -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
+52 -1
View File
@@ -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<string, unknown>
}
// ─── 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<string, SparsePreset[]>
worktreeMeta: Record<string, WorktreeMeta>
worktreeLineageById: Record<string, WorktreeLineage>
settings: GlobalSettings
ui: PersistedUIState
githubCache: {
+127
View File
@@ -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<LineageScenario> {
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)
})
})