fix: address review findings (#2695)

This commit is contained in:
Jinjing
2026-05-23 12:33:49 -07:00
committed by GitHub
parent 669ade2313
commit c93dd901a3
42 changed files with 1110 additions and 270 deletions
+104 -2
View File
@@ -68,7 +68,8 @@ const {
reopenGitLabMRMock,
getGlabKnownHostsMock,
getGitLabWorkItemDetailsMock,
getIssueMock
getIssueMock,
deleteWorktreeHistoryDirMock
} = vi.hoisted(() => {
// Why: SSH runtime tests register providers through the public dispatcher API,
// so the mock needs the same registry semantics as the real module.
@@ -120,7 +121,8 @@ const {
reopenGitLabMRMock: vi.fn(),
getGlabKnownHostsMock: vi.fn(),
getGitLabWorkItemDetailsMock: vi.fn(),
getIssueMock: vi.fn()
getIssueMock: vi.fn(),
deleteWorktreeHistoryDirMock: vi.fn()
}
})
@@ -131,6 +133,10 @@ vi.mock('../git/worktree', () => ({
removeWorktree: removeWorktreeMock
}))
vi.mock('../terminal-history', () => ({
deleteWorktreeHistoryDir: deleteWorktreeHistoryDirMock
}))
vi.mock('../providers/ssh-git-dispatch', () => ({
getSshGitProvider: getSshGitProviderMock,
SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE:
@@ -917,6 +923,102 @@ describe('OrcaRuntimeService', () => {
})
})
it('creates additional workspace metadata for folder-mode repos through runtime create', async () => {
const folderRepo = {
id: 'folder-repo',
path: '/workspace/folder',
displayName: 'Folder',
badgeColor: 'blue',
addedAt: 1,
kind: 'folder' as const
}
const metaById: Record<string, WorktreeMeta> = {}
const runtimeStore = {
...store,
getRepos: () => [folderRepo],
getRepo: (id: string) => (id === folderRepo.id ? folderRepo : undefined),
getAllWorktreeMeta: () => metaById,
getWorktreeMeta: (worktreeId: string) => metaById[worktreeId],
setWorktreeMeta: (worktreeId: string, meta: Partial<WorktreeMeta>) => {
metaById[worktreeId] = { ...(metaById[worktreeId] ?? makeWorktreeMeta()), ...meta }
return metaById[worktreeId]
},
removeWorktreeMeta: (worktreeId: string) => {
delete metaById[worktreeId]
}
}
let deletedWorktreeId = ''
const localProvider = {
listProcesses: vi.fn(async () => [{ id: `${deletedWorktreeId}@@pty-1` }]),
shutdown: vi.fn(async () => undefined)
}
const runtime = new OrcaRuntimeService(runtimeStore as never, undefined, {
getLocalProvider: () => localProvider as never
})
const notifier = { worktreesChanged: vi.fn() }
runtime.setNotifier(notifier as never)
const result = await runtime.createManagedWorktree({
repoSelector: 'id:folder-repo',
name: 'folder-session',
createdWithAgent: 'codex'
})
expect(addWorktreeMock).not.toHaveBeenCalled()
expect(result.worktree).toEqual(
expect.objectContaining({
id: expect.stringMatching(/^folder-repo::\/workspace\/folder::workspace:[0-9a-f-]{36}$/),
repoId: 'folder-repo',
path: '/workspace/folder',
displayName: 'folder-session',
isMainWorktree: false,
createdWithAgent: 'codex'
})
)
expect(metaById[result.worktree.id]).toMatchObject({
instanceId: result.worktree.instanceId,
displayName: 'folder-session',
orcaCreationSource: 'runtime',
createdWithAgent: 'codex'
})
await expect(runtime.showManagedWorktree(`id:${result.worktree.id}`)).resolves.toMatchObject({
id: result.worktree.id,
repoId: 'folder-repo',
path: '/workspace/folder',
displayName: 'folder-session'
})
await expect(runtime.listManagedWorktrees('id:folder-repo')).resolves.toMatchObject({
totalCount: 2,
worktrees: [
expect.objectContaining({
id: 'folder-repo::/workspace/folder',
isMainWorktree: true
}),
expect.objectContaining({
id: result.worktree.id,
isMainWorktree: false
})
]
})
await expect(
runtime.updateManagedWorktreeMeta(`id:${result.worktree.id}`, { comment: 'note' })
).resolves.toMatchObject({
id: result.worktree.id,
comment: 'note'
})
await expect(
runtime.removeManagedWorktree('id:folder-repo::/workspace/folder')
).rejects.toThrow('Cannot delete the project root workspace')
deletedWorktreeId = result.worktree.id
await expect(runtime.removeManagedWorktree(`id:${result.worktree.id}`)).resolves.toEqual({})
expect(localProvider.shutdown).toHaveBeenCalledWith(`${result.worktree.id}@@pty-1`, {
immediate: true
})
expect(metaById[result.worktree.id]).toBeUndefined()
expect(deleteWorktreeHistoryDirMock).toHaveBeenCalledWith(result.worktree.id)
expect(notifier.worktreesChanged).toHaveBeenCalledWith('folder-repo')
})
it('refreshes runtime remote-tracking bases before creating local worktrees', async () => {
const runtime = new OrcaRuntimeService(store)
const refresh = deferred<{ stdout: string; stderr: string }>()
+228 -9
View File
@@ -46,8 +46,9 @@ import type {
TabGroupLayoutNode,
TuiAgent
} from '../../shared/types'
import { splitWorktreeId } from '../../shared/worktree-id'
import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR, splitWorktreeId } from '../../shared/worktree-id'
import { isFolderRepo } from '../../shared/repo-kind'
import { DEFAULT_WORKSPACE_STATUS_ID } from '../../shared/workspace-statuses'
import { buildSetupRunnerCommand } from '../../shared/setup-runner-command'
import { FIRST_PANE_ID } from '../../shared/pane-key'
import { isTerminalLeafId, makePaneKey, parsePaneKey } from '../../shared/stable-pane-id'
@@ -317,8 +318,9 @@ import {
writeIssueCommand
} from '../hooks'
import { DEFAULT_REPO_BADGE_COLOR, getDefaultVoiceSettings } from '../../shared/constants'
import { createFolderWorktree, listRepoWorktrees } from '../repo-worktrees'
import { listRepoWorktrees } from '../repo-worktrees'
import { createWorktreeSymlinks } from '../ipc/worktree-symlinks'
import { deleteWorktreeHistoryDir } from '../terminal-history'
import {
cleanupUnusedWorktreePushTargetRemote,
cleanupUnusedWorktreePushTargetRemoteSsh,
@@ -704,6 +706,92 @@ function getRuntimeWorktreeRemovalOptionsKey(force: boolean, runHooks: boolean):
return `${force ? 'force' : 'normal'}:${runHooks ? 'run-hooks' : 'skip-hooks'}`
}
function getRuntimeFolderWorkspaceRootId(repo: Repo): string {
return `${repo.id}::${repo.path}`
}
function getRuntimeFolderWorkspaceInstanceId(repo: Repo, instanceId: string): string {
return `${getRuntimeFolderWorkspaceRootId(repo)}${FOLDER_WORKSPACE_INSTANCE_SEPARATOR}${instanceId}`
}
function getRuntimeFolderWorkspaceInstanceIdentity(repo: Repo, worktreeId: string): string {
const prefix = `${getRuntimeFolderWorkspaceRootId(repo)}${FOLDER_WORKSPACE_INSTANCE_SEPARATOR}`
return worktreeId.startsWith(prefix) ? worktreeId.slice(prefix.length) : randomUUID()
}
function isRuntimeFolderWorkspaceIdForRepo(repo: Repo, worktreeId: string): boolean {
const rootId = getRuntimeFolderWorkspaceRootId(repo)
return (
worktreeId === rootId ||
worktreeId.startsWith(`${rootId}${FOLDER_WORKSPACE_INSTANCE_SEPARATOR}`)
)
}
function mergeRuntimeFolderWorkspace(repo: Repo, worktreeId: string, meta: WorktreeMeta): Worktree {
return {
id: worktreeId,
...(meta.instanceId !== undefined ? { instanceId: meta.instanceId } : {}),
repoId: repo.id,
path: repo.path,
head: '',
branch: '',
isBare: false,
isMainWorktree: worktreeId === getRuntimeFolderWorkspaceRootId(repo),
displayName: meta.displayName || repo.displayName,
comment: meta.comment || '',
linkedIssue: meta.linkedIssue ?? null,
linkedPR: meta.linkedPR ?? null,
linkedLinearIssue: meta.linkedLinearIssue ?? null,
linkedGitLabMR: meta.linkedGitLabMR ?? null,
linkedGitLabIssue: meta.linkedGitLabIssue ?? null,
isArchived: meta.isArchived ?? false,
isUnread: meta.isUnread ?? false,
isPinned: meta.isPinned ?? false,
sortOrder: meta.sortOrder ?? 0,
...(meta.manualOrder !== undefined ? { manualOrder: meta.manualOrder } : {}),
lastActivityAt: meta.lastActivityAt ?? 0,
...(meta.createdAt !== undefined ? { createdAt: meta.createdAt } : {}),
...(meta.createdWithAgent !== undefined ? { createdWithAgent: meta.createdWithAgent } : {}),
workspaceStatus: meta.workspaceStatus ?? DEFAULT_WORKSPACE_STATUS_ID,
diffComments: meta.diffComments
}
}
function listRuntimeFolderWorkspaces(
store: Pick<RuntimeStore, 'getAllWorktreeMeta' | 'setWorktreeMeta'>,
repo: Repo
): Worktree[] {
const rootId = getRuntimeFolderWorkspaceRootId(repo)
const allMeta = store.getAllWorktreeMeta()
const ids = Object.keys(allMeta).filter((worktreeId) =>
isRuntimeFolderWorkspaceIdForRepo(repo, worktreeId)
)
if (!ids.includes(rootId)) {
ids.unshift(rootId)
} else {
ids.sort((left, right) => {
if (left === rootId) {
return -1
}
if (right === rootId) {
return 1
}
return 0
})
}
return ids.map((worktreeId) => {
const existing = allMeta[worktreeId]
const meta = existing?.instanceId
? existing
: store.setWorktreeMeta(worktreeId, {
instanceId: getRuntimeFolderWorkspaceInstanceIdentity(repo, worktreeId),
...(existing ? {} : { displayName: repo.displayName, lastActivityAt: Date.now() })
})
return mergeRuntimeFolderWorkspace(repo, worktreeId, meta)
})
}
function parseExactWorktreeIdSelector(selector: string): RuntimeWorktreeRemovalTarget | null {
const worktreeId = selector.startsWith('id:') ? selector.slice(3) : selector
const parsed = splitWorktreeId(worktreeId)
@@ -6417,11 +6505,18 @@ export class OrcaRuntimeService {
async listDetectedManagedWorktrees(repoSelector: string): Promise<DetectedWorktreeListResult> {
const repo = await this.resolveRepoSelector(repoSelector)
if (isFolderRepo(repo)) {
const worktrees = listRuntimeFolderWorkspaces(this.requireStore(), repo)
return {
repoId: repo.id,
authoritative: true,
source: 'git',
worktrees: worktrees.map((worktree) => this.toRuntimeDetectedWorktree(repo, worktree))
}
}
let scan: RuntimeWorktreeScanResult
try {
scan = isFolderRepo(repo)
? { ok: true, worktrees: [createFolderWorktree(repo)] }
: await this.listRepoWorktreesForResolution(repo)
scan = await this.listRepoWorktreesForResolution(repo)
} catch {
scan = { ok: false, worktrees: [] }
}
@@ -6902,15 +6997,102 @@ export class OrcaRuntimeService {
}
const repo = await this.resolveRepoSelector(args.repoSelector)
if (isFolderRepo(repo)) {
throw new Error('Folder mode does not support creating worktrees.')
}
const draftStartup = args.startupDraft
? await this.buildStartupForDraft(repo, args.startupDraft, args.createdWithAgent)
: null
const effectiveStartup = args.startup ?? draftStartup?.startup
const effectiveCreatedWithAgent = args.createdWithAgent ?? draftStartup?.agent
const effectiveDraftPaste = args.startupDraftPaste ?? draftStartup?.draftPaste
if (isFolderRepo(repo)) {
const now = Date.now()
const settings = this.store.getSettings()
const instanceId = randomUUID()
const worktreeId = getRuntimeFolderWorkspaceInstanceId(repo, instanceId)
const meta = this.store.setWorktreeMeta(worktreeId, {
instanceId,
displayName: args.displayName?.trim() || args.name,
lastActivityAt: now,
createdAt: now,
orcaCreatedAt: now,
orcaCreationSource: 'runtime',
orcaCreationWorkspaceLayout: {
path: settings.workspaceDir,
nestWorkspaces: settings.nestWorkspaces
},
...(args.linkedIssue !== undefined ? { linkedIssue: args.linkedIssue } : {}),
...(args.linkedPR !== undefined ? { linkedPR: args.linkedPR } : {}),
...(args.linkedLinearIssue !== undefined
? { linkedLinearIssue: args.linkedLinearIssue }
: {}),
...(args.linkedGitLabIssue !== undefined
? { linkedGitLabIssue: args.linkedGitLabIssue }
: {}),
...(args.linkedGitLabMR !== undefined ? { linkedGitLabMR: args.linkedGitLabMR } : {}),
...(effectiveCreatedWithAgent ? { createdWithAgent: effectiveCreatedWithAgent } : {}),
...(args.comment !== undefined ? { comment: args.comment } : {}),
...(args.manualOrder !== undefined ? { manualOrder: args.manualOrder } : {}),
...(args.workspaceStatus !== undefined ? { workspaceStatus: args.workspaceStatus } : {})
})
const worktree = mergeRuntimeFolderWorkspace(repo, worktreeId, meta)
this.invalidateResolvedWorktreeCache()
this.notifier?.worktreesChanged(repo.id)
const shouldActivate = args.activate === true || args.runHooks === true
let warning: string | undefined
let didSpawnStartup = false
if (effectiveStartup && this.ptyController?.spawn) {
try {
const startupTrustAgent = effectiveDraftPaste?.agent ?? effectiveCreatedWithAgent
if (startupTrustAgent) {
this.markLocalWorkspaceTrustedForAgent(startupTrustAgent, worktree.path)
}
const terminal = await this.createTerminal(`id:${worktree.id}`, {
command: effectiveStartup.command,
env: effectiveStartup.env
})
if (effectiveDraftPaste) {
this.pasteStartupDraftWhenReady(terminal.handle, effectiveDraftPaste)
}
didSpawnStartup = true
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
warning = `Failed to create the startup terminal for ${worktree.path}: ${message}`
console.warn(`[worktree-create] ${warning}`)
}
}
if (shouldActivate) {
if (effectiveStartup && !didSpawnStartup) {
this.notifier?.activateWorktree(repo.id, worktree.id, undefined, effectiveStartup)
} else {
this.notifier?.activateWorktree(repo.id, worktree.id)
}
} else if (this.ptyController?.spawn && !didSpawnStartup) {
try {
await this.createTerminal(`id:${worktree.id}`)
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
warning = warning
? `${warning} Also failed to create the initial terminal for ${worktree.path}: ${message}`
: `Failed to create the initial terminal for ${worktree.path}: ${message}`
console.warn(`[worktree-create] ${warning}`)
}
}
return {
worktree: {
...worktree,
parentWorktreeId: null,
childWorktreeIds: [],
lineage: null,
git: {
path: worktree.path,
head: worktree.head,
branch: worktree.branch,
isBare: worktree.isBare,
isMainWorktree: worktree.isMainWorktree
}
},
...(warning ? { warning } : {})
}
}
if (repo.connectionId) {
return await this.createManagedRemoteWorktree(repo, {
...args,
@@ -8259,7 +8441,27 @@ export class OrcaRuntimeService {
throw new Error('repo_not_found')
}
if (isFolderRepo(repo)) {
throw new Error('Folder mode does not support deleting worktrees.')
if (removalTarget.id === getRuntimeFolderWorkspaceRootId(repo)) {
throw new Error(
'Cannot delete the project root workspace. Remove the folder project instead.'
)
}
const localProvider = this.getLocalProvider()
if (localProvider) {
// Why: folder workspace deletion has no Git removal phase where PTYs
// would otherwise be swept; tear them down before hiding the workspace.
await killAllProcessesForWorktree(removalTarget.id, {
runtime: this,
localProvider
}).catch((err) => {
console.warn(`[worktree-teardown] failed for ${removalTarget.id}:`, err)
})
}
store.removeWorktreeMeta(removalTarget.id)
deleteWorktreeHistoryDir(removalTarget.id)
this.invalidateResolvedWorktreeCache()
this.notifier?.worktreesChanged(repo.id)
return {}
}
const provider = repo.connectionId ? requireSshGitProvider(repo.connectionId) : null
const registeredWorktrees = repo.connectionId
@@ -9613,6 +9815,23 @@ export class OrcaRuntimeService {
const now = Date.now()
const perRepoWorktrees = await Promise.all(
this.store.getRepos().map(async (repo) => {
if (isFolderRepo(repo)) {
return listRuntimeFolderWorkspaces(this.requireStore(), repo).map((worktree) => ({
...worktree,
parentWorktreeId: null,
childWorktreeIds: [],
lineage: null,
git: {
path: worktree.path,
head: worktree.head,
branch: worktree.branch,
isBare: worktree.isBare,
isMainWorktree: worktree.isMainWorktree
},
displayName: worktree.displayName,
comment: worktree.comment
}))
}
// Why: mobile startup RPCs share this path. A slow repo scan should
// degrade one repo's metadata, not block all terminal/session loading.
const scan = await withTimeout(