Add multi-repo folder workspaces (v1) (#5172)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Brennan Benson
2026-06-11 02:34:01 -07:00
committed by GitHub
co-authored by Orca
parent 7fbb3003f2
commit 91e354ccb1
99 changed files with 8285 additions and 761 deletions
+211
View File
@@ -1,11 +1,14 @@
/* eslint-disable max-lines -- Why: runtime behavior is stateful and cross-cutting, so these tests stay in one file to preserve the end-to-end invariants around handles, waits, and graph sync. */
import { afterEach, describe, expect, it, vi } from 'vitest'
import { EventEmitter } from 'events'
import { randomUUID } from 'crypto'
import { lstat, mkdir, mkdtemp, rm, writeFile } from 'fs/promises'
import { tmpdir } from 'os'
import { join } from 'path'
import { ipcMain } from 'electron'
import type {
FolderWorkspace,
ProjectGroup,
TerminalLayoutSnapshot,
WorktreeLineage,
WorktreeMeta,
@@ -506,6 +509,10 @@ const TEST_REPO_ID = 'repo-1'
const TEST_REPO_PATH = '/tmp/repo'
const TEST_WORKTREE_PATH = '/tmp/worktree-a'
const TEST_WORKTREE_ID = `${TEST_REPO_ID}::${TEST_WORKTREE_PATH}`
const TEST_FOLDER_PROJECT_GROUP_ID = 'folder-project-group-1'
const TEST_FOLDER_WORKSPACE_ID = 'folder-workspace-1'
const TEST_FOLDER_WORKSPACE_KEY = `folder:${TEST_FOLDER_WORKSPACE_ID}`
const TEST_FOLDER_WORKSPACE_PATH = '/tmp/platform'
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
const HEADLESS_LEAF_ID = '11111111-1111-4111-8111-111111111111'
const HEADLESS_SECOND_LEAF_ID = '22222222-2222-4222-8222-222222222222'
@@ -623,6 +630,52 @@ function createRuntime(): OrcaRuntimeService {
return new OrcaRuntimeService(store)
}
function makeFolderProjectGroup(overrides: Partial<ProjectGroup> = {}): ProjectGroup {
return {
id: TEST_FOLDER_PROJECT_GROUP_ID,
name: 'Platform',
parentPath: TEST_FOLDER_WORKSPACE_PATH,
parentGroupId: null,
createdFrom: 'folder-scan',
tabOrder: 0,
isCollapsed: false,
color: null,
createdAt: 1,
updatedAt: 1,
...overrides
}
}
function makeFolderWorkspace(overrides: Partial<FolderWorkspace> = {}): FolderWorkspace {
return {
...overrides,
id: overrides.id ?? TEST_FOLDER_WORKSPACE_ID,
projectGroupId: overrides.projectGroupId ?? TEST_FOLDER_PROJECT_GROUP_ID,
name: overrides.name ?? 'Refund fix',
folderPath: overrides.folderPath ?? TEST_FOLDER_WORKSPACE_PATH,
linkedTask: overrides.linkedTask ?? null,
comment: overrides.comment ?? '',
isArchived: overrides.isArchived ?? false,
isUnread: overrides.isUnread ?? false,
isPinned: overrides.isPinned ?? false,
sortOrder: overrides.sortOrder ?? 0,
lastActivityAt: overrides.lastActivityAt ?? 1,
createdAt: overrides.createdAt ?? 1,
updatedAt: overrides.updatedAt ?? 1
}
}
function createFolderWorkspaceRuntimeStore(
folderWorkspace: FolderWorkspace = makeFolderWorkspace(),
projectGroup: ProjectGroup = makeFolderProjectGroup()
) {
return {
...store,
getProjectGroups: () => [projectGroup],
getFolderWorkspaces: () => [folderWorkspace]
}
}
function makeRpcRequest(method: string, params?: unknown): RpcRequest {
return { id: 'req-1', authToken: 'tok', method, params }
}
@@ -3952,6 +4005,86 @@ describe('OrcaRuntimeService', () => {
})
})
it.each([
{ label: 'canonical folder workspace selector', selector: TEST_FOLDER_WORKSPACE_KEY },
{ label: 'id-prefixed folder workspace selector', selector: `id:${TEST_FOLDER_WORKSPACE_KEY}` }
])('creates background terminal sessions for a $label', async ({ selector }) => {
const folderPath = await mkdtemp(join(tmpdir(), 'orca-runtime-folder-workspace-'))
const spawn = vi.fn().mockResolvedValue({ id: 'pty-folder' })
const folderWorkspace = makeFolderWorkspace({ folderPath })
const projectGroup = makeFolderProjectGroup({ parentPath: folderPath })
const runtime = new OrcaRuntimeService(
createFolderWorkspaceRuntimeStore(folderWorkspace, projectGroup) as never
)
runtime.setPtyController({
spawn,
write: () => true,
kill: () => true,
getForegroundProcess: async () => null
})
await expect(
runtime.createTerminal(selector, {
command: 'codex',
title: 'multi-repo worker'
})
).resolves.toMatchObject({
worktreeId: TEST_FOLDER_WORKSPACE_KEY,
title: 'multi-repo worker',
surface: 'background'
})
const spawnCall = spawn.mock.calls[0]?.[0] as
| { cwd?: string; env?: Record<string, string>; worktreeId?: string }
| undefined
const spawnedEnv = spawnCall?.env ?? {}
expect(spawnCall).toMatchObject({
cwd: folderPath,
worktreeId: TEST_FOLDER_WORKSPACE_KEY
})
expectStablePaneKeyEnv(spawnedEnv)
expect(spawnedEnv.ORCA_WORKSPACE_ID).toBe(TEST_FOLDER_WORKSPACE_KEY)
expect(spawnedEnv.ORCA_PROJECT_GROUP_ID).toBe(TEST_FOLDER_PROJECT_GROUP_ID)
expect(spawnedEnv.ORCA_WORKSPACE_ROOT).toBe(folderPath)
expect(spawnedEnv.ORCA_WORKTREE_ID).toBe(TEST_FOLDER_WORKSPACE_KEY)
})
it('rejects folder workspace terminal creation when the backing path is missing', async () => {
const missingPath = join(tmpdir(), `orca-missing-folder-workspace-${randomUUID()}`)
const spawn = vi.fn().mockResolvedValue({ id: 'pty-folder' })
const folderWorkspace = makeFolderWorkspace({ folderPath: missingPath })
const projectGroup = makeFolderProjectGroup({ parentPath: missingPath })
const runtime = new OrcaRuntimeService(
createFolderWorkspaceRuntimeStore(folderWorkspace, projectGroup) as never
)
runtime.setPtyController({
spawn,
write: () => true,
kill: () => true,
getForegroundProcess: async () => null
})
await expect(runtime.createTerminal(TEST_FOLDER_WORKSPACE_KEY)).rejects.toThrow(
'folder_workspace_path_missing'
)
expect(spawn).not.toHaveBeenCalled()
})
it('rejects folder workspace folderPath updates when the new path is missing', async () => {
const missingPath = join(tmpdir(), `orca-missing-folder-update-${randomUUID()}`)
const folderWorkspace = makeFolderWorkspace()
const runtimeStore = {
...createFolderWorkspaceRuntimeStore(folderWorkspace),
updateFolderWorkspace: vi.fn()
}
const runtime = new OrcaRuntimeService(runtimeStore as never)
await expect(
runtime.updateFolderWorkspace(TEST_FOLDER_WORKSPACE_ID, { folderPath: missingPath })
).rejects.toThrow('folder_workspace_path_missing')
expect(runtimeStore.updateFolderWorkspace).not.toHaveBeenCalled()
})
it('enables Claude Agent Teams only for direct Claude launches when configured in-process', async () => {
const spawn = vi.fn().mockResolvedValue({ id: 'pty-bg' })
const runtimeStore = {
@@ -4166,6 +4299,84 @@ describe('OrcaRuntimeService', () => {
})
})
it('splits folder workspace pty-backed terminal sessions with folder cwd and env', async () => {
const folderPath = await mkdtemp(join(tmpdir(), 'orca-runtime-folder-split-'))
const spawn = vi
.fn()
.mockResolvedValueOnce({ id: 'pty-folder-source' })
.mockResolvedValueOnce({ id: 'pty-folder-split' })
const revealTerminalSession = vi.fn().mockResolvedValue({ tabId: 'tab-folder' })
const folderWorkspace = makeFolderWorkspace({ folderPath })
const projectGroup = makeFolderProjectGroup({ parentPath: folderPath })
const runtime = new OrcaRuntimeService(
createFolderWorkspaceRuntimeStore(folderWorkspace, projectGroup) as never
)
runtime.setPtyController({
spawn,
write: () => true,
kill: () => true,
getForegroundProcess: async () => null
})
runtime.setNotifier({
worktreesChanged: vi.fn(),
reposChanged: vi.fn(),
activateWorktree: vi.fn(),
createTerminal: vi.fn(),
revealTerminalSession,
splitTerminal: vi.fn(),
renameTerminal: vi.fn(),
focusTerminal: vi.fn(),
closeTerminal: vi.fn(),
sleepWorktree: vi.fn(),
terminalFitOverrideChanged: vi.fn(),
terminalDriverChanged: vi.fn()
})
runtime.attachWindow(1)
runtime.syncWindowGraph(1, { tabs: [], leaves: [] })
const { handle } = await runtime.createTerminal(TEST_FOLDER_WORKSPACE_KEY)
const sourceCall = spawn.mock.calls[0]?.[0] as
| { cwd?: string; env?: Record<string, string>; worktreeId?: string }
| undefined
const sourceEnv = sourceCall?.env ?? {}
const sourceLeafId = sourceEnv.ORCA_PANE_KEY.slice(`${sourceEnv.ORCA_TAB_ID}:`.length)
await expect(runtime.splitTerminal(handle, { direction: 'vertical' })).resolves.toMatchObject({
handle: expect.stringMatching(/^term_/),
tabId: sourceEnv.ORCA_TAB_ID,
paneRuntimeId: -1
})
const splitCall = spawn.mock.calls[1]?.[0] as
| { cwd?: string; env?: Record<string, string>; worktreeId?: string }
| undefined
const splitEnv = splitCall?.env ?? {}
const splitLeafId = splitEnv.ORCA_PANE_KEY.slice(`${sourceEnv.ORCA_TAB_ID}:`.length)
expect(sourceCall).toMatchObject({
cwd: folderPath,
worktreeId: TEST_FOLDER_WORKSPACE_KEY
})
expect(splitCall).toMatchObject({
cwd: folderPath,
worktreeId: TEST_FOLDER_WORKSPACE_KEY
})
expectStablePaneKeyEnv(splitEnv)
expect(splitEnv.ORCA_TAB_ID).toBe(sourceEnv.ORCA_TAB_ID)
expect(splitEnv.ORCA_WORKSPACE_ID).toBe(TEST_FOLDER_WORKSPACE_KEY)
expect(splitEnv.ORCA_PROJECT_GROUP_ID).toBe(TEST_FOLDER_PROJECT_GROUP_ID)
expect(splitEnv.ORCA_WORKSPACE_ROOT).toBe(folderPath)
expect(splitEnv.ORCA_WORKTREE_ID).toBe(TEST_FOLDER_WORKSPACE_KEY)
expect(revealTerminalSession).toHaveBeenLastCalledWith(TEST_FOLDER_WORKSPACE_KEY, {
ptyId: 'pty-folder-split',
title: null,
activate: true,
tabId: sourceEnv.ORCA_TAB_ID,
leafId: splitLeafId,
splitFromLeafId: sourceLeafId,
splitDirection: 'vertical'
})
})
it('returns a background handle when inactive tab adoption fails after spawn', async () => {
const spawn = vi.fn().mockResolvedValue({ id: 'pty-bg' })
const revealTerminalSession = vi.fn().mockRejectedValue(new Error('Renderer timed out'))
+267 -31
View File
@@ -71,6 +71,7 @@ import type {
LinearWorkspaceSelection,
NestedRepoScanResult,
ProjectGroup,
FolderWorkspace,
ProjectGroupImportMode,
ProjectGroupImportResult,
MemorySnapshot,
@@ -120,6 +121,11 @@ import {
isPathInsideOrEqual,
normalizeRuntimePathForComparison
} from '../../shared/cross-platform-path'
import { folderWorkspaceKey, parseWorkspaceKey } from '../../shared/workspace-scope'
import type {
FolderWorkspacePathStatus,
FolderWorkspacePathStatusRequest
} from '../../shared/folder-workspace-path-status'
import {
buildKnownOrcaWorkspaceLayouts,
isLegacyRepoForExternalWorktreeVisibility,
@@ -487,6 +493,12 @@ import { killAllProcessesForWorktree } from './worktree-teardown'
import { MOBILE_SUBSCRIBE_SCROLLBACK_ROWS } from './scrollback-limits'
import type { IFilesystemProvider, IPtyProvider } from '../providers/types'
import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch'
import {
assertFolderWorkspacePathUsable,
getFolderWorkspacePathStatus,
getFolderWorkspacePathStatusForPath,
inferFolderWorkspacePathConnection
} from '../project-groups/folder-workspace-path-status'
import { getSshGitProvider, requireSshGitProvider } from '../providers/ssh-git-dispatch'
import { detectRepoIconAndUpstream } from '../repo-icon-autodetect'
import { githubAvatarIcon } from '../../shared/repo-icon'
@@ -540,6 +552,10 @@ type RuntimeStore = {
updateProjectGroup?: Store['updateProjectGroup']
deleteProjectGroup?: Store['deleteProjectGroup']
moveProjectToGroup?: Store['moveProjectToGroup']
getFolderWorkspaces?: Store['getFolderWorkspaces']
createFolderWorkspace?: Store['createFolderWorkspace']
updateFolderWorkspace?: Store['updateFolderWorkspace']
removeFolderWorkspace?: Store['removeFolderWorkspace']
removeProject?: Store['removeProject']
reorderRepos?: Store['reorderRepos']
getAllWorktreeMeta: Store['getAllWorktreeMeta']
@@ -1194,6 +1210,13 @@ type ResolvedWorktree = Worktree & {
git: GitWorktreeInfo
}
type TerminalWorkspaceLaunchScope = {
id: string
path: string
connectionId: string | null
folderWorkspace: FolderWorkspace | null
}
type WorktreeLineageInput = {
parentWorktree?: string
cwdParentWorktree?: string
@@ -6487,9 +6510,14 @@ export class OrcaRuntimeService {
return this.store?.getProjectGroups?.() ?? []
}
listFolderWorkspaces(): FolderWorkspace[] {
return this.store?.getFolderWorkspaces?.() ?? []
}
async createProjectGroup(input: {
name: string
parentPath?: string | null
connectionId?: string | null
parentGroupId?: string | null
createdFrom?: ProjectGroup['createdFrom']
}): Promise<ProjectGroup> {
@@ -6499,6 +6527,7 @@ export class OrcaRuntimeService {
const group = this.store.createProjectGroup({
name: input.name,
parentPath: input.parentPath ?? null,
connectionId: input.connectionId ?? null,
parentGroupId: input.parentGroupId ?? null,
createdFrom: input.createdFrom ?? 'manual'
})
@@ -6548,6 +6577,118 @@ export class OrcaRuntimeService {
return moved
}
async createFolderWorkspace(input: {
projectGroupId: string
name?: string
folderPath?: string | null
connectionId?: string | null
linkedTask?: FolderWorkspace['linkedTask']
createdWithAgent?: FolderWorkspace['createdWithAgent']
pendingFirstAgentMessageRename?: boolean
}): Promise<FolderWorkspace> {
if (!this.store?.createFolderWorkspace) {
throw new Error('runtime_unavailable')
}
const projectGroups = this.store.getProjectGroups?.() ?? []
const group = projectGroups.find((entry) => entry.id === input.projectGroupId)
const folderPath =
typeof input.folderPath === 'string' && input.folderPath.trim().length > 0
? input.folderPath
: group?.parentPath
if (!group || !folderPath) {
throw new Error('folder_workspace_project_group_not_found')
}
const status = await getFolderWorkspacePathStatusForPath(
{
folderPath,
projectGroupId: group.id,
connectionId: input.connectionId ?? group.connectionId ?? null,
projectGroups,
repos: this.store.getRepos()
},
{ getSshFilesystemProvider }
)
assertFolderWorkspacePathUsable(status)
const workspace = this.store.createFolderWorkspace(input)
this.notifyReposChanged()
return workspace
}
async getFolderWorkspacePathStatus(
request: FolderWorkspacePathStatusRequest
): Promise<FolderWorkspacePathStatus> {
if (!this.store) {
throw new Error('runtime_unavailable')
}
return getFolderWorkspacePathStatus(this.store, request, { getSshFilesystemProvider })
}
async updateFolderWorkspace(
folderWorkspaceId: string,
updates: Partial<
Pick<
FolderWorkspace,
| 'name'
| 'folderPath'
| 'linkedTask'
| 'comment'
| 'isArchived'
| 'isUnread'
| 'isPinned'
| 'sortOrder'
| 'manualOrder'
| 'workspaceStatus'
| 'createdWithAgent'
| 'pendingFirstAgentMessageRename'
| 'firstAgentMessageRenameError'
| 'lastActivityAt'
>
>
): Promise<FolderWorkspace | null> {
if (!this.store?.updateFolderWorkspace) {
throw new Error('runtime_unavailable')
}
if (typeof updates.folderPath === 'string' && updates.folderPath.trim().length > 0) {
const workspace = this.store
.getFolderWorkspaces?.()
.find((entry) => entry.id === folderWorkspaceId)
if (!workspace) {
return null
}
const projectGroups = this.store.getProjectGroups?.() ?? []
const status = await getFolderWorkspacePathStatusForPath(
{
folderPath: updates.folderPath,
projectGroupId: workspace.projectGroupId,
connectionId:
workspace.connectionId ??
projectGroups.find((entry) => entry.id === workspace.projectGroupId)?.connectionId ??
null,
projectGroups,
repos: this.store.getRepos()
},
{ getSshFilesystemProvider }
)
assertFolderWorkspacePathUsable(status)
}
const updated = this.store.updateFolderWorkspace(folderWorkspaceId, updates)
if (updated) {
this.notifyReposChanged()
}
return updated
}
async deleteFolderWorkspace(folderWorkspaceId: string): Promise<{ deleted: boolean }> {
if (!this.store?.removeFolderWorkspace) {
throw new Error('runtime_unavailable')
}
const deleted = this.store.removeFolderWorkspace(folderWorkspaceId)
if (deleted) {
this.notifyReposChanged()
}
return { deleted }
}
async scanNestedRepos(path: string): Promise<NestedRepoScanResult> {
if (!isAbsolute(path)) {
throw new Error('Project path must be an absolute path')
@@ -6605,6 +6746,8 @@ export class OrcaRuntimeService {
parentPath: args.parentPath,
groupName: args.groupName,
mode: args.mode,
connectionId: null,
repoPaths: selection.selectedPaths,
createGroup: (input) => this.store!.createProjectGroup!(input)
})
const results: ProjectGroupImportResult['projects'] = selection.rejectedPaths.map(
@@ -11147,8 +11290,7 @@ export class OrcaRuntimeService {
if (!this.ptyController?.spawn) {
throw new Error('runtime_unavailable')
}
const worktree = await this.resolveWorktreeSelector(worktreeSelector)
const repo = this.store?.getRepo(worktree.repoId)
const workspace = await this.resolveTerminalWorkspaceLaunchScope(worktreeSelector)
const preAllocatedHandle = this.createPreAllocatedTerminalHandle()
// Why: mint tabId in main before spawn so paneKey is known at PTY env
// build time. Hook-based agent status (Claude/Codex/Cursor/Gemini) keys
@@ -11184,23 +11326,23 @@ export class OrcaRuntimeService {
shimBin
}).env
})
const env = {
...baseEnv,
...agentTeamsPlan?.env,
ORCA_PANE_KEY: paneKey,
ORCA_TAB_ID: tabId,
ORCA_WORKTREE_ID: worktree.id
}
const env = this.buildTerminalWorkspaceEnv(
workspace,
baseEnv,
paneKey,
tabId,
agentTeamsPlan?.env
)
const result = await this.ptyController.spawn({
cols: 120,
rows: 40,
cwd: worktree.path,
cwd: workspace.path,
command: agentTeamsPlan?.command ?? opts.command,
env,
envToDelete: agentTeamsPlan?.envToDelete,
telemetry: opts.telemetry,
connectionId: repo?.connectionId ?? null,
worktreeId: worktree.id,
connectionId: workspace.connectionId,
worktreeId: workspace.id,
preAllocatedHandle,
tabId,
leafId,
@@ -11208,7 +11350,7 @@ export class OrcaRuntimeService {
...(opts.persistHostSessionBinding ? { persistHostSessionBinding: true } : {})
})
this.registerPreAllocatedHandleForPty(result.id, preAllocatedHandle)
this.registerPty(result.id, worktree.id, repo?.connectionId ?? null)
this.registerPty(result.id, workspace.id, workspace.connectionId)
const pty = this.getOrCreatePtyWorktreeRecord(result.id)
if (pty) {
if (opts.title) {
@@ -11225,7 +11367,7 @@ export class OrcaRuntimeService {
}
const handle = pty ? this.issuePtyHandle(pty) : preAllocatedHandle
if (pty) {
this.publishPtyBackedMobileSessionTerminal(worktree.id, pty, {
this.publishPtyBackedMobileSessionTerminal(workspace.id, pty, {
tabId,
leafId,
title: opts.title ?? null,
@@ -11239,7 +11381,7 @@ export class OrcaRuntimeService {
// failing here must not strand a live process without returning a handle.
// Pass the pre-minted tabId so the renderer adopts under the same id
// already baked into the PTY env — keeps paneKey hook attribution intact.
await this.notifier.revealTerminalSession(worktree.id, {
await this.notifier.revealTerminalSession(workspace.id, {
ptyId: result.id,
title: opts.title ?? null,
activate: opts.activate === true,
@@ -11251,7 +11393,7 @@ export class OrcaRuntimeService {
console.warn(`[terminal-create] failed to create inactive tab for ${result.id}:`, err)
}
}
return { handle, worktreeId: worktree.id, title: opts.title ?? null, surface }
return { handle, worktreeId: workspace.id, title: opts.title ?? null, surface }
}
this.assertGraphReady()
@@ -11259,7 +11401,7 @@ export class OrcaRuntimeService {
// Why: mirrors browserTabCreate — when no worktree is specified, pass
// undefined so the renderer uses its current active worktree.
const worktreeId = worktreeSelector
? (await this.resolveWorktreeSelector(worktreeSelector)).id
? (await this.resolveTerminalWorkspaceLaunchScope(worktreeSelector)).id
: undefined
const requestId = randomUUID()
@@ -11814,29 +11956,23 @@ export class OrcaRuntimeService {
throw new Error('terminal_handle_stale')
}
const direction = opts.direction ?? 'horizontal'
const worktree = await this.resolveWorktreeSelector(`id:${pty.worktreeId}`)
const repo = this.store?.getRepo(worktree.repoId)
const workspace = await this.resolveTerminalWorkspaceLaunchScope(`id:${pty.worktreeId}`)
const leafId = randomUUID()
const preAllocatedHandle = this.createPreAllocatedTerminalHandle()
const paneKey = makePaneKey(parentTabId, leafId)
const result = await this.ptyController.spawn({
cols: 120,
rows: 40,
cwd: worktree.path,
cwd: workspace.path,
command: opts.command,
env: {
...opts.env,
ORCA_PANE_KEY: paneKey,
ORCA_TAB_ID: parentTabId,
ORCA_WORKTREE_ID: worktree.id
},
env: this.buildTerminalWorkspaceEnv(workspace, opts.env ?? {}, paneKey, parentTabId),
envToDelete: opts.envToDelete,
connectionId: repo?.connectionId ?? null,
worktreeId: worktree.id,
connectionId: workspace.connectionId,
worktreeId: workspace.id,
preAllocatedHandle
})
this.registerPreAllocatedHandleForPty(result.id, preAllocatedHandle)
this.registerPty(result.id, worktree.id, repo?.connectionId ?? null)
this.registerPty(result.id, workspace.id, workspace.connectionId)
const createdPty = this.getOrCreatePtyWorktreeRecord(result.id)
if (createdPty) {
createdPty.tabId = parentTabId
@@ -11844,7 +11980,7 @@ export class OrcaRuntimeService {
}
try {
await this.notifier?.revealTerminalSession?.(worktree.id, {
await this.notifier?.revealTerminalSession?.(workspace.id, {
ptyId: result.id,
title: null,
activate: opts.activate !== false,
@@ -11859,7 +11995,7 @@ export class OrcaRuntimeService {
throw error
}
if (createdPty) {
this.publishPtyBackedMobileSessionTerminal(worktree.id, createdPty, {
this.publishPtyBackedMobileSessionTerminal(workspace.id, createdPty, {
tabId: parentTabId,
leafId,
title: null,
@@ -12063,6 +12199,101 @@ export class OrcaRuntimeService {
}
}
private resolveFolderWorkspaceConnectionId(workspace: FolderWorkspace): string | null {
const repos = this.store?.getRepos() ?? []
const projectGroups = this.store?.getProjectGroups?.() ?? []
const connection = inferFolderWorkspacePathConnection({
folderPath: workspace.folderPath,
projectGroupId: workspace.projectGroupId,
connectionId: workspace.connectionId ?? null,
projectGroups,
repos
})
if (connection.kind === 'ambiguous') {
// Why: a single PTY can only be spawned on one runtime target; mixed
// child repo connections need an explicit V2 routing decision.
throw new Error('folder_workspace_connection_ambiguous')
}
return connection.kind === 'ssh' ? connection.connectionId : null
}
private async resolveFolderWorkspaceLaunchScope(
selector: string
): Promise<TerminalWorkspaceLaunchScope | null> {
const workspaceSelector = selector.startsWith('id:') ? selector.slice(3) : selector
const parsed = parseWorkspaceKey(workspaceSelector)
if (parsed?.type !== 'folder') {
return null
}
const workspace = this.store
?.getFolderWorkspaces?.()
.find((entry) => entry.id === parsed.folderWorkspaceId)
if (!workspace) {
throw new Error('selector_not_found')
}
if (!this.store) {
throw new Error('runtime_unavailable')
}
const status = await getFolderWorkspacePathStatus(
this.store,
{ scope: 'folder-workspace', folderWorkspaceId: workspace.id },
{ getSshFilesystemProvider }
)
assertFolderWorkspacePathUsable(status)
return {
id: folderWorkspaceKey(workspace.id),
path: workspace.folderPath,
connectionId: this.resolveFolderWorkspaceConnectionId(workspace),
folderWorkspace: workspace
}
}
private async resolveTerminalWorkspaceLaunchScope(
selector: string
): Promise<TerminalWorkspaceLaunchScope> {
const folderScope = await this.resolveFolderWorkspaceLaunchScope(selector)
if (folderScope) {
return folderScope
}
const workspaceSelector = selector.startsWith('id:') ? selector.slice(3) : selector
const parsed = parseWorkspaceKey(workspaceSelector)
const worktreeSelector = parsed?.type === 'worktree' ? `id:${parsed.worktreeId}` : selector
const worktree = await this.resolveWorktreeSelector(worktreeSelector)
const repo = this.store?.getRepo(worktree.repoId) ?? null
return {
id: worktree.id,
path: worktree.path,
connectionId: repo?.connectionId ?? null,
folderWorkspace: null
}
}
private buildTerminalWorkspaceEnv(
scope: TerminalWorkspaceLaunchScope,
baseEnv: Record<string, string>,
paneKey: string,
tabId: string,
agentTeamsEnv?: Record<string, string>
): Record<string, string> {
const env = {
...baseEnv,
...agentTeamsEnv,
ORCA_PANE_KEY: paneKey,
ORCA_TAB_ID: tabId,
ORCA_WORKTREE_ID: scope.id
}
if (!scope.folderWorkspace) {
return env
}
return {
...env,
ORCA_WORKSPACE_ID: scope.id,
ORCA_PROJECT_GROUP_ID: scope.folderWorkspace.projectGroupId,
ORCA_WORKSPACE_ROOT: scope.folderWorkspace.folderPath
}
}
private async resolveWorktreeSelector(selector: string): Promise<ResolvedWorktree> {
const worktrees = await this.listResolvedWorktrees()
let candidates: ResolvedWorktree[]
@@ -12687,6 +12918,11 @@ export class OrcaRuntimeService {
this.notifyWorktreesChanged(repoId)
}
notifyFolderWorkspaceChanged(): void {
this.invalidateResolvedWorktreeCache()
this.notifyReposChanged()
}
private recordPtyWorktree(
ptyId: string,
worktreeId: string,
@@ -0,0 +1,98 @@
import { z } from 'zod'
import { defineMethod, type RpcMethod } from '../core'
import { OptionalFiniteNumber, OptionalString, requiredString } from '../schemas'
import { isTuiAgent } from '../../../../shared/tui-agent-config'
const FolderWorkspaceLinkedTask = z
.object({
provider: z.enum(['github', 'gitlab', 'linear', 'jira']),
type: z.enum(['issue', 'pr', 'mr']),
number: z.number().finite(),
title: requiredString('Missing linked task title'),
url: requiredString('Missing linked task URL'),
linearIdentifier: OptionalString,
jiraIdentifier: OptionalString,
repoId: OptionalString
})
.nullable()
const FolderWorkspaceCreate = z.object({
projectGroupId: requiredString('Missing project group id'),
name: OptionalString,
folderPath: OptionalString.nullable().optional(),
connectionId: OptionalString.nullable().optional(),
linkedTask: FolderWorkspaceLinkedTask.optional(),
createdWithAgent: z.string().refine(isTuiAgent).optional(),
pendingFirstAgentMessageRename: z.boolean().optional()
})
const FolderWorkspaceUpdate = z.object({
folderWorkspaceId: requiredString('Missing folder workspace id'),
updates: z.object({
name: OptionalString,
folderPath: OptionalString,
linkedTask: FolderWorkspaceLinkedTask.optional(),
comment: z.string().optional(),
isArchived: z.boolean().optional(),
isUnread: z.boolean().optional(),
isPinned: z.boolean().optional(),
sortOrder: OptionalFiniteNumber,
manualOrder: OptionalFiniteNumber,
workspaceStatus: OptionalString,
createdWithAgent: z.string().refine(isTuiAgent).optional(),
pendingFirstAgentMessageRename: z.boolean().optional(),
firstAgentMessageRenameError: z.string().nullable().optional(),
lastActivityAt: OptionalFiniteNumber
})
})
const FolderWorkspaceSelector = z.object({
folderWorkspaceId: requiredString('Missing folder workspace id')
})
const FolderWorkspacePathStatus = z.discriminatedUnion('scope', [
z.object({
scope: z.literal('folder-workspace'),
folderWorkspaceId: requiredString('Missing folder workspace id')
}),
z.object({
scope: z.literal('project-group'),
projectGroupId: requiredString('Missing project group id')
})
])
export const FOLDER_WORKSPACE_METHODS: RpcMethod[] = [
defineMethod({
name: 'folderWorkspace.list',
params: null,
handler: (_params, { runtime }) => ({
folderWorkspaces: runtime.listFolderWorkspaces()
})
}),
defineMethod({
name: 'folderWorkspace.create',
params: FolderWorkspaceCreate,
handler: async (params, { runtime }) => ({
folderWorkspace: await runtime.createFolderWorkspace(params)
})
}),
defineMethod({
name: 'folderWorkspace.update',
params: FolderWorkspaceUpdate,
handler: async (params, { runtime }) => ({
folderWorkspace: await runtime.updateFolderWorkspace(params.folderWorkspaceId, params.updates)
})
}),
defineMethod({
name: 'folderWorkspace.delete',
params: FolderWorkspaceSelector,
handler: async (params, { runtime }) => runtime.deleteFolderWorkspace(params.folderWorkspaceId)
}),
defineMethod({
name: 'folderWorkspace.getPathStatus',
params: FolderWorkspacePathStatus,
handler: async (params, { runtime }) => ({
status: await runtime.getFolderWorkspacePathStatus(params)
})
})
]
+68 -1
View File
@@ -287,7 +287,29 @@ describe('repo RPC methods', () => {
createProjectGroup: vi.fn().mockResolvedValue(group),
updateProjectGroup: vi.fn().mockResolvedValue({ ...group, name: 'Core' }),
deleteProjectGroup: vi.fn().mockResolvedValue({ deleted: true }),
moveProjectToGroup: vi.fn().mockResolvedValue({ id: 'repo-1', projectGroupId: group.id })
moveProjectToGroup: vi.fn().mockResolvedValue({ id: 'repo-1', projectGroupId: group.id }),
listFolderWorkspaces: vi.fn().mockReturnValue([
{
id: 'folder-workspace-1',
projectGroupId: group.id,
name: 'Refund fix',
folderPath: '/srv/platform',
comment: '',
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 1,
lastActivityAt: 0,
createdAt: 1,
updatedAt: 1
}
]),
createFolderWorkspace: vi.fn().mockResolvedValue({ id: 'folder-workspace-2' }),
updateFolderWorkspace: vi.fn().mockResolvedValue({ id: 'folder-workspace-1', comment: 'x' }),
deleteFolderWorkspace: vi.fn().mockResolvedValue({ deleted: true }),
getFolderWorkspacePathStatus: vi
.fn()
.mockResolvedValue({ path: '/srv/platform', exists: true })
} as unknown as OrcaRuntimeService
const dispatcher = new RpcDispatcher({ runtime, methods: REPO_METHODS })
@@ -313,6 +335,28 @@ describe('repo RPC methods', () => {
order: 2
})
)
const folderListResponse = await dispatcher.dispatch(makeRequest('folderWorkspace.list'))
await dispatcher.dispatch(
makeRequest('folderWorkspace.create', {
projectGroupId: group.id,
name: 'Refund fix'
})
)
await dispatcher.dispatch(
makeRequest('folderWorkspace.update', {
folderWorkspaceId: 'folder-workspace-1',
updates: { comment: 'x' }
})
)
await dispatcher.dispatch(
makeRequest('folderWorkspace.delete', { folderWorkspaceId: 'folder-workspace-1' })
)
const statusResponse = await dispatcher.dispatch(
makeRequest('folderWorkspace.getPathStatus', {
scope: 'folder-workspace',
folderWorkspaceId: 'folder-workspace-1'
})
)
expect(runtime.listProjectGroups).toHaveBeenCalled()
expect(runtime.createProjectGroup).toHaveBeenCalledWith({
@@ -326,10 +370,33 @@ describe('repo RPC methods', () => {
})
expect(runtime.deleteProjectGroup).toHaveBeenCalledWith(group.id)
expect(runtime.moveProjectToGroup).toHaveBeenCalledWith('repo-1', group.id, 2)
expect(runtime.listFolderWorkspaces).toHaveBeenCalled()
expect(runtime.createFolderWorkspace).toHaveBeenCalledWith({
projectGroupId: group.id,
name: 'Refund fix'
})
expect(runtime.updateFolderWorkspace).toHaveBeenCalledWith('folder-workspace-1', {
comment: 'x'
})
expect(runtime.deleteFolderWorkspace).toHaveBeenCalledWith('folder-workspace-1')
expect(runtime.getFolderWorkspacePathStatus).toHaveBeenCalledWith({
scope: 'folder-workspace',
folderWorkspaceId: 'folder-workspace-1'
})
expect(moveResponse).toMatchObject({
ok: true,
result: { repo: { id: 'repo-1', projectGroupId: group.id } }
})
expect(folderListResponse).toMatchObject({
ok: true,
result: {
folderWorkspaces: [expect.objectContaining({ id: 'folder-workspace-1' })]
}
})
expect(statusResponse).toMatchObject({
ok: true,
result: { status: { path: '/srv/platform', exists: true } }
})
})
it('allows separate nested-repo imports without a group name', async () => {
+3
View File
@@ -4,6 +4,7 @@ import { OptionalFiniteNumber, OptionalString, requiredString } from '../schemas
import { sanitizeRepoIcon } from '../../../../shared/repo-icon'
import { normalizeRepoBadgeColor } from '../../../../shared/repo-badge-color'
import { normalizeRepoSourceControlAiOverrides } from '../../../../shared/source-control-ai'
import { FOLDER_WORKSPACE_METHODS } from './folder-workspace'
const RepoSelector = z.object({
repo: requiredString('Missing repo selector')
@@ -95,6 +96,7 @@ const RepoReorder = z.object({
const ProjectGroupCreate = z.object({
name: requiredString('Missing group name'),
parentPath: OptionalString,
connectionId: OptionalString.nullable().optional(),
parentGroupId: OptionalString.nullable().optional(),
createdFrom: z.enum(['manual', 'folder-scan', 'migration']).optional()
})
@@ -187,6 +189,7 @@ export const REPO_METHODS: RpcMethod[] = [
repo: await runtime.moveProjectToGroup(params.repo, params.groupId ?? null, params.order)
})
}),
...FOLDER_WORKSPACE_METHODS,
defineMethod({
name: 'projectGroup.scanNested',
params: ProjectGroupScanNested,