refactor(cli): group workspace, terminal, and host owners

This commit is contained in:
Neil
2026-11-12 04:49:09 -08:00
parent fbec96cf29
commit 8a55b78459
121 changed files with 824 additions and 1178 deletions
+4 -1
View File
@@ -9,7 +9,10 @@ import {
import { getRequiredStringFlag } from '../flags'
import { printResult } from '../command-result-output'
import { RuntimeClientError } from '../runtime/types'
import { getRequiredWorktreeSelector, resolveCurrentWorktreeSelector } from '../selectors'
import {
getRequiredWorktreeSelector,
resolveCurrentWorktreeSelector
} from '../workspace-selection/workspace-selector'
export const AGENT_LAUNCH_HANDLERS: Record<string, CommandHandler> = {
'agent launch': async ({ flags, client, cwd, json, rawArgs }) => {
@@ -12,7 +12,7 @@ import { getRepoRoutingConnectionId } from '../../shared/execution-host'
import { getManagedOrcadSshTargetId } from '../../shared/execution-host/managed-orcad-execution-host'
import { listEnvironments } from '../../shared/remote-runtime/host-store/runtime-environment-store'
import { RuntimeClient } from '../runtime/client'
import { fetchSshTargetSummaries } from '../host-selector-alternatives'
import { fetchSshTargetSummaries } from '../hosts/host-selector-alternatives'
/** Empty selectors mean the execution host cannot change. */
export type AutomationDestinationTarget = { repo?: string; workspace?: string }
+5 -2
View File
@@ -34,12 +34,15 @@ import {
readAutomationRunsPage
} from './automation-runs-paging'
import { RuntimeClientError } from '../runtime/types'
import { getOptionalWorktreeSelector, resolveCurrentWorktreeSelector } from '../selectors'
import {
getOptionalWorktreeSelector,
resolveCurrentWorktreeSelector
} from '../workspace-selection/workspace-selector'
import {
assertWorkspaceTargetFlagsCompatible,
hasWorkspaceProjectTarget,
resolveProjectCreateTarget
} from '../worktree-project-target'
} from '../workspaces/worktree-project-target'
import {
getEnabledFlag,
getOptionalProviderFlag,
+2 -2
View File
@@ -3,12 +3,12 @@ import type { RuntimeStatus } from '../../shared/runtime-types'
import { getOptionalStringFlag, getPresentStringFlag } from '../flags'
import type { RuntimeClient } from '../runtime-client'
import { RuntimeClientError } from '../runtime/types'
import { assertLocalCwdWorktreeSelector } from '../local-environment-selector'
import { assertLocalCwdWorktreeSelector } from '../hosts/local-environment-selector'
import {
getBrowserWorktreeSelector,
normalizeWorktreeSelectorForCaller,
resolveCurrentWorktreeSelector
} from '../selectors'
} from '../workspace-selection/workspace-selector'
type BrowserCliTarget = {
worktree?: string
+1 -1
View File
@@ -5,7 +5,7 @@ import type {
import type { CommandHandler } from '../dispatch'
import { getPresentStringFlag } from '../flags'
import { printResult } from '../command-result-output'
import { resolveRepoPathArgument } from '../repo-path-arguments'
import { resolveRepoPathArgument } from '../projects/repo-path-arguments'
export const BROWSER_EXTENSION_HANDLERS: Record<string, CommandHandler> = {
'extension list': async ({ flags, client, json }) => {
+1 -1
View File
@@ -13,7 +13,7 @@ import type {
BrowserUploadResult
} from '../../shared/browser/runtime/runtime-browser-contracts'
import type { CommandHandler } from '../dispatch'
import { resolveRepoPathArgument } from '../repo-path-arguments'
import { resolveRepoPathArgument } from '../projects/repo-path-arguments'
import { printResult } from '../command-result-output'
import {
getOptionalNumberFlag,
+1 -1
View File
@@ -21,7 +21,7 @@ import {
} from '../flags'
import { RuntimeClientError } from '../runtime/types'
import { isBrowserTabSplitDirection } from '../../shared/browser-tab-split-direction'
import { getBrowserWorktreeSelector } from '../selectors'
import { getBrowserWorktreeSelector } from '../workspace-selection/workspace-selector'
import { getBrowserCommandTarget } from './browser-command-target'
export const BROWSER_TAB_HANDLERS: Record<string, CommandHandler> = {
+1 -1
View File
@@ -4,7 +4,7 @@ import {
stripAutomationOwnerConflictCode
} from '../shared/automations/ownership/automation-owner-conflict'
import { automationOwnerConflictRecovery } from './automations/automation-owner-conflict-recovery'
import { worktreeSelectorRecovery } from './worktree-selector-recovery'
import { worktreeSelectorRecovery } from './workspaces/worktree-selector-recovery'
import { ambiguousWorkspaceChoices, selectorAmbiguityRecovery } from './selector-ambiguity-recovery'
import type { RuntimeRpcFailure } from './runtime-client'
import { RuntimeClientError, RuntimeRpcFailureError } from './runtime/types'
@@ -0,0 +1,34 @@
import type { ComputerAppQuery } from '../../shared/computer-use-runtime-types'
import type { RuntimeClient } from '../runtime/client'
import { RuntimeClientError } from '../runtime/types'
import { getOptionalStringFlag, getRequiredStringFlag } from '../flags'
import { getBrowserWorktreeSelector } from '../workspace-selection/workspace-selector'
export type ComputerCliTarget = {
session?: string
worktree?: string
app: ComputerAppQuery
}
export async function getComputerCommandTarget(
flags: Map<string, string | boolean>,
cwd: string,
client: RuntimeClient
): Promise<ComputerCliTarget> {
const app = getRequiredStringFlag(flags, 'app')
const session = getOptionalStringFlag(flags, 'session')
const worktree = getOptionalStringFlag(flags, 'worktree')
if (session && worktree) {
throw new RuntimeClientError(
'invalid_argument',
'Computer-use targeting accepts either --session or --worktree, not both'
)
}
if (session) {
return { session, app }
}
return {
app,
worktree: await getBrowserWorktreeSelector(flags, cwd, client)
}
}
+1 -1
View File
@@ -20,7 +20,7 @@ import {
formatListWindows
} from './computer-format'
import { printResult } from '../command-result-output'
import { getComputerCommandTarget } from '../selectors'
import { getComputerCommandTarget } from './computer-command-target'
import {
getComputerActionObserveFlags,
getComputerObserveFlags,
@@ -0,0 +1,98 @@
import type { MemorySnapshot, WorktreeMemory } from '../../shared/process-stats-types'
export function formatMemorySnapshot(snapshot: MemorySnapshot): string {
const topWorktrees = [...snapshot.worktrees].sort((a, b) => b.memory - a.memory).slice(0, 10)
const hostAvailable = snapshot.host.availableMemory ?? snapshot.host.freeMemory
const hostAvailableSource = snapshot.host.availableMemorySource ?? 'free-memory'
const lines = [
`collectedAt: ${new Date(snapshot.collectedAt).toISOString()}`,
`totalMemory: ${formatByteCount(snapshot.totalMemory)}`,
`processMemoryMetric: ${formatProcessMemoryMetric(snapshot.processMemoryMetric)}`,
...formatCommitLines(snapshot),
`totalCpu: ${formatCpu(snapshot.totalCpu)}`,
[
`hostUsed: ${formatByteCount(snapshot.host.usedMemory)}`,
`/ ${formatByteCount(snapshot.host.totalMemory)}`,
`(${snapshot.host.memoryUsagePercent.toFixed(1)}%)`
].join(' '),
[`hostAvailable: ${formatByteCount(hostAvailable)}`, `(${hostAvailableSource})`].join(' '),
[
`app: ${formatByteCount(snapshot.app.memory)}`,
`(main ${formatByteCount(snapshot.app.main.memory)},`,
`renderer ${formatByteCount(snapshot.app.renderer.memory)},`,
`other ${formatByteCount(snapshot.app.other.memory)})`
].join(' '),
`worktrees: ${snapshot.worktrees.length}`
]
if (topWorktrees.length === 0) {
lines.push('topWorktrees: none')
return lines.join('\n')
}
lines.push('', 'Top worktrees:')
for (const worktree of topWorktrees) {
lines.push(formatWorktreeMemoryLine(worktree))
}
if (snapshot.worktrees.length > topWorktrees.length) {
lines.push(`... ${snapshot.worktrees.length - topWorktrees.length} more worktrees`)
}
return lines.join('\n')
}
function formatWorktreeMemoryLine(worktree: WorktreeMemory): string {
return [
`- ${worktree.worktreeName}`,
`${formatByteCount(worktree.memory)}`,
...(worktree.privateMemory === undefined
? []
: [`${formatByteCount(worktree.privateMemory)} committed`]),
`${formatCpu(worktree.cpu)}`,
`${worktree.sessions.length} session${worktree.sessions.length === 1 ? '' : 's'}`
].join(' ')
}
// Missing commit fields mean unknown usage, not zero.
function formatCommitLines(snapshot: MemorySnapshot): string[] {
if (typeof snapshot.totalPrivateMemory !== 'number') {
return []
}
return [
`totalPrivateMemory: ${formatByteCount(snapshot.totalPrivateMemory)}`,
`processCommitMetric: ${formatProcessCommitMetric(snapshot.processCommitMetric)}`
]
}
function formatProcessCommitMetric(metric: MemorySnapshot['processCommitMetric']): string {
return metric === 'private-bytes'
? 'summed private bytes; committed memory, counted whether resident or paged out'
: `summed ${metric ?? 'unknown'}`
}
function formatCpu(cpu: number): string {
return `${cpu.toFixed(1)}%`
}
function formatProcessMemoryMetric(metric: MemorySnapshot['processMemoryMetric']): string {
if (metric === 'footprint') {
return 'summed memory footprint (Activity Monitor); includes graphics memory'
}
return metric === 'working-set'
? 'summed working set; shared pages may repeat'
: 'summed RSS; shared or aliased pages may repeat'
}
function formatByteCount(bytes: number): string {
if (!Number.isFinite(bytes) || bytes <= 0) {
return '0 B'
}
const units = ['B', 'KB', 'MB', 'GB', 'TB']
let value = bytes
let unitIndex = 0
while (value >= 1024 && unitIndex < units.length - 1) {
value /= 1024
unitIndex += 1
}
const formatted = value >= 10 || unitIndex === 0 ? value.toFixed(0) : value.toFixed(1)
return `${formatted} ${units[unitIndex]}`
}
@@ -0,0 +1,81 @@
import type { RuntimeClient } from '../runtime/client'
import { RuntimeClientError } from '../runtime/types'
import { assertLocalCwdWorktreeSelector } from '../hosts/local-environment-selector'
import { getOptionalStringFlag } from '../flags'
import {
resolveCallerPaneWorktreeSelector,
type WorkspaceSelectionPurpose
} from '../workspace-selection/caller-host-worktree-selection'
import { resolveCurrentWorktreeSelector } from '../workspace-selection/workspace-selector'
export type EmulatorCliTarget = {
worktree?: string
device?: string
emulator?: string // Orca id from list
}
async function optionalCurrentWorktreeSelector(
cwd: string,
client: RuntimeClient,
purpose: WorkspaceSelectionPurpose = 'worktree'
) {
try {
return await resolveCurrentWorktreeSelector(cwd, client, purpose)
} catch (error) {
if (error instanceof RuntimeClientError && error.code === 'selector_ambiguous') {
throw error
}
return undefined
}
}
export async function getEmulatorWorktreeSelector(
flags: Map<string, string | boolean>,
cwd: string,
client: RuntimeClient
): Promise<string | undefined> {
const explicit = getOptionalStringFlag(flags, 'worktree')
if (explicit === 'all') {
return undefined
}
if (explicit) {
if (explicit === 'active' || explicit === 'current') {
assertLocalCwdWorktreeSelector(explicit, client)
return resolveCurrentWorktreeSelector(cwd, client)
}
return explicit
}
if (client.isRemote) {
return undefined
}
const terminalWorktreeId = process.env.ORCA_WORKTREE_ID
if (terminalWorktreeId?.trim()) {
const scoped = await resolveCallerPaneWorktreeSelector(terminalWorktreeId, client)
if (scoped) {
return scoped
}
}
const folderWorkspaceId = process.env.ORCA_WORKSPACE_ID?.trim()
if (folderWorkspaceId?.startsWith('folder:')) {
return folderWorkspaceId
}
return optionalCurrentWorktreeSelector(cwd, client)
}
export async function getEmulatorCommandTarget(
flags: Map<string, string | boolean>,
cwd: string,
client: RuntimeClient
): Promise<EmulatorCliTarget> {
const device = getOptionalStringFlag(flags, 'device')
const emulator = getOptionalStringFlag(flags, 'emulator')
const worktree = await getEmulatorWorktreeSelector(flags, cwd, client)
if (device || emulator) {
return {
device: device || undefined,
emulator: emulator || undefined,
worktree
}
}
return { worktree }
}
+2 -2
View File
@@ -2,14 +2,14 @@ import type { CommandHandler } from '../dispatch'
import { formatLogcat } from './emulator-logcat-format'
import { parseEmulatorPermissionRequest } from './emulator-permissions-args'
import { printResult } from '../command-result-output'
import { resolveRepoPathArgument } from '../repo-path-arguments'
import { resolveRepoPathArgument } from '../projects/repo-path-arguments'
import {
getOptionalPositiveIntegerFlag,
getOptionalStringFlag,
getRequiredFiniteNumber,
getRequiredStringFlag
} from '../flags'
import { getEmulatorCommandTarget } from '../selectors'
import { getEmulatorCommandTarget } from './emulator-command-target'
import { RuntimeClientError } from '../runtime/types'
import { EMULATOR_ATTACH_RPC_TIMEOUT_MS } from '../../shared/emulator-attach-timeouts'
+4 -1
View File
@@ -10,7 +10,10 @@ import { getOptionalStringFlag, getRequiredStringFlag } from '../flags'
import { printResult } from '../command-result-output'
import { RuntimeClientError } from '../runtime/types'
import { callFileOpen } from './file-open-call'
import { getOptionalWorktreeSelector, resolveCurrentWorktreeSelector } from '../selectors'
import {
getOptionalWorktreeSelector,
resolveCurrentWorktreeSelector
} from '../workspace-selection/workspace-selector'
type FileOpenMode = 'edit' | 'diff'
type OpenChangedMode = FileOpenMode | 'both'
+8 -8
View File
@@ -3,10 +3,10 @@ import { BROWSER_HANDLER_GROUPS } from './browser/browser-handler-groups'
import { JIRA_HANDLER_GROUP } from './jira/jira-handler-group'
import { LINEAR_HANDLER_GROUP } from './linear/linear-handler-group'
import { REFERENCE_HANDLER_GROUP } from './reference-handler-group'
import { SERVE_PAIRING_HANDLER_GROUPS } from './serve-pairing-handler-groups'
import { SERVE_PAIRING_HANDLER_GROUPS } from './server/serve-pairing-handler-groups'
import { PLUGIN_HANDLER_GROUPS } from './plugin-handler-groups'
import { HOST_HANDLER_GROUPS } from './host-handler-groups'
import { WORKTREE_HANDLER_GROUPS } from './worktree-handler-groups'
import { HOST_HANDLER_GROUPS } from './hosts/host-handler-groups'
import { WORKTREE_HANDLER_GROUPS } from './workspaces/worktree-handler-groups'
export type HandlerGroup = {
name: string
@@ -29,12 +29,12 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [
name: 'serve-reset-identity',
keys: ['serve reset-identity'],
load: async () =>
(await import('./handlers/serve-reset-identity.js')).SERVE_RESET_IDENTITY_HANDLERS
(await import('./server/serve-reset-identity.js')).SERVE_RESET_IDENTITY_HANDLERS
},
{
name: 'serve-service',
keys: ['serve service install', 'serve service status', 'serve service uninstall'],
load: async () => (await import('./handlers/serve-service.js')).SERVE_SERVICE_HANDLERS
load: async () => (await import('./server/serve-service.js')).SERVE_SERVICE_HANDLERS
},
{
name: 'account',
@@ -76,7 +76,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [
'project setup-update',
'project setup-delete'
],
load: async () => (await import('./handlers/project.js')).PROJECT_HANDLERS
load: async () => (await import('./projects/project.js')).PROJECT_HANDLERS
},
{
name: 'repo',
@@ -88,7 +88,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [
'repo set-base-ref',
'repo search-refs'
],
load: async () => (await import('./handlers/repo.js')).REPO_HANDLERS
load: async () => (await import('./projects/repo.js')).REPO_HANDLERS
},
...WORKTREE_HANDLER_GROUPS,
{
@@ -112,7 +112,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [
'terminal close',
'terminal split'
],
load: async () => (await import('./handlers/terminal.js')).TERMINAL_HANDLERS
load: async () => (await import('./terminals/terminal.js')).TERMINAL_HANDLERS
},
...BROWSER_HANDLER_GROUPS,
{
+1 -1
View File
@@ -9,7 +9,7 @@ import {
} from '../flags'
import { printResult } from '../command-result-output'
import { RuntimeClientError } from '../runtime-client'
import { getRequiredWorktreeSelector } from '../selectors'
import { getRequiredWorktreeSelector } from '../workspace-selection/workspace-selector'
type ConnectorDelivery = { outcome: string; reason?: string; reopened?: boolean }
+2 -2
View File
@@ -1,8 +1,8 @@
import type { MemorySnapshot } from '../../shared/process-stats-types'
import type { CommandHandler } from '../dispatch'
import { formatMemorySnapshot } from '../workspace-format'
import { formatMemorySnapshot } from '../diagnostics/memory-snapshot-format'
import { printResult } from '../command-result-output'
import { TERMINAL_DAEMON_HANDLERS } from './terminal-daemon'
import { TERMINAL_DAEMON_HANDLERS } from '../terminals/terminal-daemon'
export const DIAGNOSTICS_HANDLERS: Record<string, CommandHandler> = {
'diagnostics memory': async ({ client, json }) => {
@@ -5,7 +5,7 @@ const getTerminalHandleMock = vi.hoisted(() => vi.fn())
const originalTerminalHandle = process.env.ORCA_TERMINAL_HANDLE
const originalPaneKey = process.env.ORCA_PANE_KEY
vi.mock('../command-result-output', () => ({ printResult: vi.fn() }))
vi.mock('../selectors', () => ({ getTerminalHandle: getTerminalHandleMock }))
vi.mock('../terminals/terminal-selector', () => ({ getTerminalHandle: getTerminalHandleMock }))
import { ORCHESTRATION_HANDLERS } from './orchestration'
import { RuntimeClientError } from '../runtime-client'
@@ -7,7 +7,7 @@ const originalPaneKey = process.env.ORCA_PANE_KEY
const printResultMock = vi.hoisted(() => vi.fn())
vi.mock('../command-result-output', () => ({ printResult: printResultMock }))
vi.mock('../selectors', () => ({ getTerminalHandle: getTerminalHandleMock }))
vi.mock('../terminals/terminal-selector', () => ({ getTerminalHandle: getTerminalHandleMock }))
import { ORCHESTRATION_HANDLERS } from './orchestration'
@@ -3,7 +3,7 @@ import { afterEach, expect, it, vi } from 'vitest'
const callMock = vi.fn()
const printResultMock = vi.hoisted(() => vi.fn())
vi.mock('../command-result-output', () => ({ printResult: printResultMock }))
vi.mock('../selectors', () => ({ getTerminalHandle: vi.fn() }))
vi.mock('../terminals/terminal-selector', () => ({ getTerminalHandle: vi.fn() }))
import { ORCHESTRATION_HANDLERS } from './orchestration'
import { orchestrationTestContext } from './orchestration-handler-test-context'
+11 -27
View File
@@ -5,7 +5,7 @@ const { callMock, getTerminalHandleMock } = vi.hoisted(() => ({
getTerminalHandleMock: vi.fn()
}))
vi.mock('../runtime-client', async () => {
vi.mock('../runtime/client', async () => {
// Error formatting uses instanceof, so preserve the production error classes.
const { RuntimeClientError, RuntimeRpcFailureError } = await import('../runtime/types.js')
class RuntimeClient {
@@ -23,7 +23,16 @@ vi.mock('../runtime-client', async () => {
}
})
vi.mock('../selectors', async (importOriginal) => ({
vi.mock('../runtime/metadata', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
getDefaultUserDataPath: vi.fn(() => '/tmp/orca-user-data')
}))
vi.mock('../runtime/launch', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
serveOrcaApp: vi.fn()
}))
vi.mock('../terminals/terminal-selector', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
getTerminalHandle: getTerminalHandleMock
}))
@@ -75,31 +84,6 @@ describe('orchestration gate commands carry caller identity', () => {
const paramsFor = (method: string): Record<string, unknown> =>
callMock.mock.calls.find((call) => call[0] === method)?.[1] as Record<string, unknown>
it('remints a stale environment handle before authorizing gateCreate', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_stale'
process.env.ORCA_PANE_KEY = 'tab_coord:leaf_coord'
callMock.mockImplementation(async (method: string) => {
if (method === 'terminal.resolveIdentity') {
return okFixture('req_identity', { identity: { handle: 'term_stale', live: false } })
}
if (method === 'terminal.resolvePane') {
return okFixture('req_pane', { terminal: { handle: 'term_live' } })
}
return okFixture('req_gate', {
gate: { id: 'gate_1', task_id: 'task_1', status: 'pending' }
})
})
await main(
['orchestration', 'gate-create', '--task', 'task_1', '--question', 'ship?', '--json'],
'/tmp/repo'
)
expect(paramsFor('orchestration.gateCreate')).toEqual(
expect.objectContaining({ from: 'term_live' })
)
})
it('inspects a named Run without resolving a caller terminal', async () => {
getTerminalHandleMock.mockRejectedValue(
new RuntimeClientError('no_active_terminal', 'no active terminal')
@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
const callMock = vi.fn()
vi.mock('../command-result-output', () => ({ printResult: vi.fn() }))
vi.mock('../selectors', () => ({ getTerminalHandle: vi.fn() }))
vi.mock('../terminals/terminal-selector', () => ({ getTerminalHandle: vi.fn() }))
import { printResult } from '../command-result-output'
import { ORCHESTRATION_HANDLERS } from './orchestration'
@@ -3,7 +3,7 @@ import { afterEach, expect, it, vi } from 'vitest'
const callMock = vi.fn()
const originalExitCode = process.exitCode
vi.mock('../command-result-output', () => ({ printResult: vi.fn() }))
vi.mock('../selectors', () => ({ getTerminalHandle: vi.fn() }))
vi.mock('../terminals/terminal-selector', () => ({ getTerminalHandle: vi.fn() }))
import { printResult } from '../command-result-output'
import { ORCHESTRATION_HANDLERS } from './orchestration'
@@ -6,7 +6,7 @@ vi.mock('../command-result-output', async (importOriginal) => {
const original = await importOriginal<{ printResult: typeof printResult }>()
return { printResult: vi.fn(original.printResult) }
})
vi.mock('../selectors', () => ({ getTerminalHandle: vi.fn() }))
vi.mock('../terminals/terminal-selector', () => ({ getTerminalHandle: vi.fn() }))
import { ORCHESTRATION_HANDLERS } from './orchestration'
import { printResult } from '../command-result-output'
+1 -1
View File
@@ -5,7 +5,7 @@ const getTerminalHandleMock = vi.hoisted(() => vi.fn())
const originalExitCode = process.exitCode
vi.mock('../command-result-output', () => ({ printResult: vi.fn() }))
vi.mock('../selectors', () => ({ getTerminalHandle: getTerminalHandleMock }))
vi.mock('../terminals/terminal-selector', () => ({ getTerminalHandle: getTerminalHandleMock }))
import { ORCHESTRATION_HANDLERS } from './orchestration'
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('../../selectors', () => ({ getTerminalHandle: vi.fn() }))
vi.mock('../../terminals/terminal-selector', () => ({ getTerminalHandle: vi.fn() }))
import { ORCHESTRATION_HANDLERS } from '../orchestration'
import { orchestrationTestContext } from '../orchestration-handler-test-context'
@@ -1,156 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('../../selectors', () => ({ getTerminalHandle: vi.fn() }))
import { ORCHESTRATION_HANDLERS } from '../orchestration'
import { orchestrationTestContext } from '../orchestration-handler-test-context'
const HUGE = 'x'.repeat(10_000)
// check delivers mail and gate-list asks the question, so those bodies print whole; inbox previews them.
const CONTENT = 'c'.repeat(10_000)
const MAX_ROW_CHARS = 500
const MAX_PREVIEW_CHARS = 250
const message = {
id: 'msg_1',
from_handle: 'dispatch:ctx_1',
to_handle: 'run:run_1',
subject: 'Done',
body: HUGE,
type: 'worker_done',
priority: 'normal',
read: 0,
thread_id: 'msg_1',
payload: JSON.stringify({ taskId: 'task_1', dispatchId: 'ctx_1', notes: HUGE }),
created_at: '2026-10-31T00:00:00Z'
}
const LISTS: [string, [string, string][], string, unknown][] = [
[
'task-list',
[['run', 'run_1']],
'tasks',
{
tasks: [
{ id: 'task_1', spec: HUGE, status: 'completed', result: HUGE, dispatch_id: 'ctx_1' }
],
count: 1
}
],
[
'worker-list',
[['run', 'run_1']],
'workers',
{
workers: [
{
dispatchId: 'ctx_1',
taskId: 'task_1',
runId: 'run_1',
workerState: 'failed',
dispatchStatus: 'failed',
agentTerminalHandle: 'term_1',
terminalState: 'released',
lastError: HUGE,
output: HUGE,
projection: {
host: { id: 'local' },
stage: { activity: 'failed' },
liveness: { verdict: 'exited' },
nextAction: { argv: [] },
description: HUGE
}
}
],
counts: { released: 1 },
page: { hasMore: false, nextCursor: null, total: 1 }
}
],
[
'gate-list',
[['run', 'run_1']],
'gates',
{
gates: [
{
id: 'gate_1',
task_id: 'task_1',
question: CONTENT,
options: '["yes","no"]',
status: 'resolved',
resolution: HUGE
}
],
count: 1
}
],
[
'run-list',
[],
'runs',
{ runs: [{ id: 'run_1', objective: HUGE, legacy: 0 }], nextCursor: null }
],
['inbox', [], 'messages', { messages: [message], count: 1 }],
[
'check',
[['run', 'run_1']],
'messages',
{
runId: 'run_1',
deliveryId: 'delivery_1',
deliveryAcknowledged: true,
messages: [{ ...message, body: CONTENT, payload: CONTENT }],
count: 1
}
]
]
async function printed(command: string, flags: [string, string][], result: unknown, json: boolean) {
const callMock = vi.fn().mockResolvedValue({ id: 'req_1', ok: true, result, _meta: {} })
const log = vi
.spyOn(console, 'log')
.mockClear()
.mockImplementation(() => {})
await ORCHESTRATION_HANDLERS[`orchestration ${command}`](
orchestrationTestContext(callMock, new Map(flags), json)
)
return log.mock.calls.map(([line]) => String(line)).join('\n')
}
describe('concise orchestration list output', () => {
beforeEach(() => {
vi.stubEnv('ORCA_TERMINAL_HANDLE', 'term_coord')
vi.stubEnv('ORCA_AGENT_SESSION_ID', undefined)
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it.each(LISTS)(
'keeps each %s row short when stored text is huge',
async (command, flags, key, result) => {
const rawText = await printed(command, flags, result, false)
const json: { result: Record<string, { body?: string }[]> } = JSON.parse(
await printed(command, flags, result, true)
)
const items = json.result[key]
if (command === 'check') {
expect(rawText).toContain(CONTENT)
expect(items[0]?.body).toBe(CONTENT)
} else {
for (const item of items) {
expect(item.body?.length ?? 0).toBeLessThanOrEqual(MAX_PREVIEW_CHARS)
}
}
const rows = [rawText, ...items.map((row) => JSON.stringify(row))].flatMap((output) =>
output.replaceAll(CONTENT, '').split('\n')
)
expect(rows.length).toBeGreaterThan(1)
for (const row of rows) {
expect(row.length).toBeLessThan(MAX_ROW_CHARS)
}
}
)
})
@@ -1,6 +1,6 @@
import { getOptionalStringFlag, getPresentStringFlag } from '../../flags'
import { type RuntimeClient, RuntimeClientError } from '../../runtime-client'
import { getTerminalHandle } from '../../selectors'
import { getTerminalHandle } from '../../terminals/terminal-selector'
import { hasStructuredSessionMarker } from '../../../shared/structured-session-marker'
import {
injectedSessionAddress,
@@ -1,79 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { RuntimeClient, RuntimeClientError } from '../runtime-client'
import { parseArgs } from '../args'
import { TERMINAL_HANDLERS } from './terminal'
afterEach(() => vi.restoreAllMocks())
describe('terminal set-pane-title', () => {
it.each(['REVIEWER', ''])('sends an explicit title %j to the pane method', async (title) => {
const parsed = parseArgs([
'terminal',
'set-pane-title',
'--terminal',
'term-1',
'--title',
title
])
const client = new RuntimeClient()
const call = vi.spyOn(client, 'call').mockResolvedValue({
id: 'request',
ok: true,
result: {
paneTitle: { handle: 'term-1', tabId: 'tab-1', leafId: 'leaf-1', title: title || null }
},
_meta: { runtimeId: 'runtime-1' }
})
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
await TERMINAL_HANDLERS['terminal set-pane-title']({
flags: parsed.flags,
client,
cwd: '/tmp',
json: true
})
expect(call).toHaveBeenCalledExactlyOnceWith('terminal.setPaneTitle', {
terminal: 'term-1',
title
})
expect(JSON.parse(String(log.mock.calls[0]?.[0]))).toMatchObject({
result: { paneTitle: { title: title || null } }
})
})
it.each([{ args: [] }, { args: ['--title'] }])(
'refuses a missing title before resolving a terminal (%j)',
async ({ args }) => {
const client = new RuntimeClient()
const call = vi.spyOn(client, 'call')
const parsed = parseArgs(['terminal', 'set-pane-title', ...args])
await expect(
TERMINAL_HANDLERS['terminal set-pane-title']({
flags: parsed.flags,
client,
cwd: '/tmp',
json: true
})
).rejects.toMatchObject({ code: 'invalid_argument' })
expect(call).not.toHaveBeenCalled()
}
)
it('propagates an older host refusal without falling back to tab rename', async () => {
const client = new RuntimeClient()
const call = vi
.spyOn(client, 'call')
.mockRejectedValue(new RuntimeClientError('method_not_found', 'Unknown method'))
await expect(
TERMINAL_HANDLERS['terminal set-pane-title']({
flags: new Map([
['terminal', 'term-1'],
['title', 'REVIEWER']
]),
client,
cwd: '/tmp',
json: true
})
).rejects.toMatchObject({ code: 'method_not_found' })
expect(call).toHaveBeenCalledTimes(1)
})
})
@@ -1,79 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { RuntimeClient } from '../runtime-client'
const mocks = vi.hoisted(() => ({ revealPairedTerminalOnLocalDesktop: vi.fn() }))
vi.mock('../paired-terminal-desktop-reveal', () => ({
revealPairedTerminalOnLocalDesktop: mocks.revealPairedTerminalOnLocalDesktop
}))
import { TERMINAL_HANDLERS } from './terminal'
function focusResponse(navigated: boolean) {
return {
id: 'req-focus',
ok: true,
result: { focus: { handle: 'term-1', tabId: 'tab-1', worktreeId: 'wt-1', navigated } },
_meta: { runtimeId: 'runtime-1' }
}
}
async function runSwitch(options: { call: RuntimeClient['call']; isRemote: boolean }) {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
const client = new RuntimeClient('/tmp/orca-switch-test', 60_000, null, null)
vi.spyOn(client, 'call').mockImplementation(options.call)
vi.spyOn(client, 'isRemote', 'get').mockReturnValue(options.isRemote)
await TERMINAL_HANDLERS['terminal switch']({
flags: new Map([['terminal', 'term-1']]),
client,
cwd: '/tmp/worktree',
json: true
})
return JSON.parse(String(log.mock.calls[0]?.[0]))
}
describe('terminal switch on a paired environment', () => {
afterEach(() => {
vi.restoreAllMocks()
mocks.revealPairedTerminalOnLocalDesktop.mockReset()
})
it('shows the terminal in the local desktop when the windowless server cannot (#24688)', async () => {
const call = vi.fn().mockResolvedValue(focusResponse(false))
mocks.revealPairedTerminalOnLocalDesktop.mockResolvedValue(true)
const printed = await runSwitch({ call, isRemote: true })
expect(call).toHaveBeenCalledWith('terminal.focus', { terminal: 'term-1', navigation: 'host' })
expect(mocks.revealPairedTerminalOnLocalDesktop).toHaveBeenCalledWith(
expect.objectContaining({ isRemote: true }),
'term-1'
)
expect(printed).toMatchObject({ ok: true, result: { focus: { navigated: true } } })
})
it('keeps navigated false when no local desktop shows that environment', async () => {
const call = vi.fn().mockResolvedValue(focusResponse(false))
mocks.revealPairedTerminalOnLocalDesktop.mockResolvedValue(false)
const printed = await runSwitch({ call, isRemote: true })
expect(mocks.revealPairedTerminalOnLocalDesktop).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({ isRemote: true }),
'term-1'
)
expect(printed).toMatchObject({ result: { focus: { navigated: false } } })
})
it.each([
['a local terminal the host could not navigate to', false, false],
['a remote host that navigated itself', true, true]
])('leaves %s alone', async (_case, isRemote, navigated) => {
const call = vi.fn().mockResolvedValue(focusResponse(navigated))
const printed = await runSwitch({ call, isRemote })
expect(mocks.revealPairedTerminalOnLocalDesktop).not.toHaveBeenCalled()
expect(printed).toMatchObject({ result: { focus: { navigated } } })
})
})
+28
View File
@@ -0,0 +1,28 @@
import type { PublicKnownRuntimeEnvironment } from '../../shared/remote-runtime/host-catalog/runtime-environments'
export function formatEnvironmentList(result: {
environments: PublicKnownRuntimeEnvironment[]
}): string {
if (result.environments.length === 0) {
return 'No saved environments.'
}
return result.environments
.map(
(environment) =>
`${environment.id} ${environment.name} ${environment.endpoints[0]?.endpoint ?? 'no-endpoint'}`
)
.join('\n')
}
export function formatEnvironment(environment: PublicKnownRuntimeEnvironment): string {
return [
`id: ${environment.id}`,
`name: ${environment.name}`,
`runtimeId: ${environment.runtimeId ?? 'unknown'}`,
`lastUsedAt: ${environment.lastUsedAt ?? 'never'}`,
`preferredEndpointId: ${environment.preferredEndpointId}`,
...environment.endpoints.map(
(endpoint) => `endpoint: ${endpoint.id} ${endpoint.kind} ${endpoint.endpoint}`
)
].join('\n')
}
@@ -1,21 +1,19 @@
import type { CommandHandler } from '../dispatch'
import { formatEnvironment, formatEnvironmentList } from '../workspace-format'
import { formatHostList, formatHostName, type HostNameResult } from '../hosts/host-format'
import { formatEnvironment, formatEnvironmentList } from './environment-format'
import { formatHostList, formatHostName, type HostNameResult } from './host-format'
import { printResult } from '../command-result-output'
import { parseHostFlag } from '../execution-host-flag'
import { parseHostFlag } from './execution-host-flag'
import {
fetchSshTargetSummaries,
listSshTargets,
LOCAL_HOST_LIST_NAME,
normalizeTypedName,
type SshTargetSummary
} from '../host-selector-alternatives'
import {
getDefaultUserDataPath,
RuntimeClientError,
type RuntimeClient,
type RuntimeRpcSuccess
} from '../runtime-client'
} from './host-selector-alternatives'
import { normalizeTypedName } from '../../shared/typed-name-normalization'
import { getDefaultUserDataPath } from '../runtime/metadata'
import { RuntimeClientError } from '../runtime/types'
import type { RuntimeClient } from '../runtime/client'
import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope'
import { rejectRemoteSelectionFlags } from '../remote-selection-flag-rejection'
import { redactRuntimeEnvironment } from '../../shared/remote-runtime/host-catalog/runtime-environments'
@@ -28,7 +26,7 @@ import {
type EnvironmentRemoveResult
} from '../runtime/environments'
import { exchangeCliPairingCode } from '../runtime/environment-pairing-exchange'
import { refuseReservedEnvironmentName } from '../local-environment-selector'
import { refuseReservedEnvironmentName } from './local-environment-selector'
import { listEnvironments } from '../../shared/remote-runtime/host-store/runtime-environment-store'
export const ENVIRONMENT_HANDLERS: Record<string, CommandHandler> = {
@@ -4,7 +4,7 @@ import {
parseExecutionHostId,
toSshExecutionHostId,
type ParsedExecutionHost
} from '../shared/execution-host'
} from '../../shared/execution-host'
import {
ambiguousEnvironments,
ambiguousSshTargets,
@@ -13,14 +13,13 @@ import {
findSshTargetByName,
fetchSshTargetSummaries,
LOCAL_HOST_LIST_NAME,
normalizeTypedName,
resolveSshHostTargetId,
stripWrappingQuotes,
type EnvironmentSummary,
type SshTargetSummary
} from './host-selector-alternatives'
import type { RuntimeClient } from './runtime-client'
import { RuntimeClientError } from './runtime/types'
import { normalizeTypedName, stripWrappingQuotes } from '../../shared/typed-name-normalization'
import type { RuntimeClient } from '../runtime/client'
import { RuntimeClientError } from '../runtime/types'
import { isLocalEnvironmentSelector } from './local-environment-selector'
export type HostFlagRoutingSelection = {
@@ -76,9 +75,9 @@ export async function resolveHostFlagEnvironmentId(
}
const [{ resolveEnvironment }, { getDefaultUserDataPath }, { listEnvironments }] =
await Promise.all([
import('./runtime/environments.js'),
import('./runtime-client.js'),
import('../shared/remote-runtime/host-store/runtime-environment-store.js')
import('../runtime/environments.js'),
import('../runtime/metadata.js'),
import('../../shared/remote-runtime/host-store/runtime-environment-store.js')
])
const userDataPath = getDefaultUserDataPath()
const environments = listEnvironments(userDataPath).map((candidate) => ({
@@ -218,9 +217,9 @@ export async function resolveHostFlagTarget(
return host
}
const [, { getDefaultUserDataPath }, { listEnvironments }] = await Promise.all([
import('./runtime/environments.js'),
import('./runtime-client.js'),
import('../shared/remote-runtime/host-store/runtime-environment-store.js')
import('../runtime/environments.js'),
import('../runtime/metadata.js'),
import('../../shared/remote-runtime/host-store/runtime-environment-store.js')
])
const environments = listEnvironments(getDefaultUserDataPath()).map((candidate) => ({
id: candidate.id,
@@ -296,9 +295,9 @@ export async function resolveEnvironmentSelectorForStore(
listSshTargetsForSuggestion: () => Promise<SshTargetSummary[]>
): Promise<string> {
const [, { getDefaultUserDataPath }, { listEnvironments }] = await Promise.all([
import('./runtime/environments.js'),
import('./runtime-client.js'),
import('../shared/remote-runtime/host-store/runtime-environment-store.js')
import('../runtime/environments.js'),
import('../runtime/metadata.js'),
import('../../shared/remote-runtime/host-store/runtime-environment-store.js')
])
const environments = listEnvironments(getDefaultUserDataPath()).map((candidate) => ({
id: candidate.id,
@@ -1,4 +1,4 @@
import type { HandlerGroup } from './handler-group-manifest'
import type { HandlerGroup } from '../handler-group-manifest'
// The machines Orca reaches: saved hosts and paired environments, the Orca servers it manages on
// them, and recipe VMs.
@@ -14,7 +14,7 @@ export const HOST_HANDLER_GROUPS: readonly HandlerGroup[] = [
'environment show',
'environment rm'
],
load: async () => (await import('./handlers/environment.js')).ENVIRONMENT_HANDLERS
load: async () => (await import('./environment.js')).ENVIRONMENT_HANDLERS
},
{
name: 'managed-server',
@@ -27,16 +27,16 @@ export const HOST_HANDLER_GROUPS: readonly HandlerGroup[] = [
'environment cancel-stop',
'environment forget'
],
load: async () => (await import('./handlers/managed-server.js')).MANAGED_SERVER_HANDLERS
load: async () => (await import('./managed-server.js')).MANAGED_SERVER_HANDLERS
},
{
name: 'vm',
keys: ['vm recipe doctor'],
load: async () => (await import('./handlers/vm.js')).VM_HANDLERS
load: async () => (await import('./vm.js')).VM_HANDLERS
},
{
name: 'vm-env',
keys: ['vm env doctor'],
load: async () => (await import('./handlers/vm-env.js')).VM_ENV_HANDLERS
load: async () => (await import('./vm-env.js')).VM_ENV_HANDLERS
}
]
@@ -8,8 +8,8 @@ import {
listSshTargets,
resolveSshHostTargetId
} from './host-selector-alternatives'
import { RuntimeClient } from './runtime-client'
import { okFixture } from './test-fixtures'
import { RuntimeClient } from '../runtime/client'
import { okFixture } from '../test-fixtures'
const SSH_TARGETS = [{ id: 'ssh-1755000000000-a1b2c3', label: 'openclaw' }]
const ENVIRONMENTS = [{ id: '03ef704c-b180-4b10-998d-e28fbd5de9a3', name: 'awin' }]
@@ -48,20 +48,6 @@ describe('findEnvironmentByName', () => {
describe('crossKindNextSteps', () => {
const alternatives = { sshTargets: SSH_TARGETS, environments: ENVIRONMENTS }
it('points an SSH name at the SSH flag when a server was asked for', () => {
const steps = crossKindNextSteps('openclaw', alternatives, 'environment')
expect(steps.join('\n')).toContain('--host ssh:ssh-1755000000000-a1b2c3')
expect(steps.join('\n')).toContain('is an SSH target')
})
it('points a server name at --environment when an SSH target was asked for', () => {
const steps = crossKindNextSteps('awin', alternatives, 'ssh')
expect(steps.join('\n')).toContain('--environment awin')
expect(steps.join('\n')).toContain('is a paired Orca server')
})
it('says nothing when the name exists on neither axis', () => {
expect(crossKindNextSteps('nowhere', alternatives, 'ssh')).toEqual([])
})
@@ -110,24 +96,8 @@ describe('resolveSshHostTargetId', () => {
})
describe('listSshTargets', () => {
it('falls back to the older listing when the newer method is absent', async () => {
const { RuntimeClientError } = await import('./runtime/types.js')
const call = vi
.fn()
.mockRejectedValueOnce(new RuntimeClientError('method_not_found', 'Unknown method'))
.mockResolvedValueOnce(okFixture('targets', { targets: SSH_TARGETS }))
.mockRejectedValue(new Error('Legacy state unavailable'))
await expect(listSshTargets(clientWithCall(call))).resolves.toEqual(SSH_TARGETS)
expect(call.mock.calls).toEqual([
['ssh.listTargetSummaries'],
['ssh.listTargets'],
['ssh.getState', { targetId: SSH_TARGETS[0].id }]
])
})
it('enriches legacy target rows from host-owned connection state', async () => {
const { RuntimeClientError } = await import('./runtime/types.js')
const { RuntimeClientError } = await import('../runtime/types.js')
const call = vi
.fn()
.mockRejectedValueOnce(new RuntimeClientError('method_not_found', 'Unknown method'))
@@ -1,5 +1,5 @@
import type { RuntimeClient } from './runtime-client'
import { normalizeTypedName, stripWrappingQuotes } from '../shared/typed-name-normalization'
import type { RuntimeClient } from '../runtime/client'
import { normalizeTypedName } from '../../shared/typed-name-normalization'
export type SshTargetSummary = {
id: string
@@ -29,8 +29,6 @@ export function findSshTargetByName(
return byLabel.length === 1 ? byLabel[0] : undefined
}
export { normalizeTypedName, stripWrappingQuotes }
function matchesByLabel(targets: readonly SshTargetSummary[], name: string): SshTargetSummary[] {
const wanted = normalizeTypedName(name)
return targets.filter((target) => normalizeTypedName(target.label) === wanted)
@@ -159,7 +157,7 @@ export async function resolveSshHostTargetId(
if (matched) {
return matched.id
}
const { RuntimeClientError } = await import('./runtime/types.js')
const { RuntimeClientError } = await import('../runtime/types.js')
const ambiguous = ambiguousSshTargets(targets, targetId)
if (ambiguous.length > 0) {
throw new RuntimeClientError(
@@ -18,8 +18,8 @@ const {
spawnMock: vi.fn()
}))
vi.mock('./runtime-client', async () => {
const { createRuntimeClientModuleMock } = await import('./index-test-harness.js')
vi.mock('../runtime/client', async () => {
const { createRuntimeClientModuleMock } = await import('../index-test-harness.js')
return createRuntimeClientModuleMock({
callMock,
runtimeClientConstructorMock,
@@ -28,23 +28,32 @@ vi.mock('./runtime-client', async () => {
})
})
vi.mock('./runtime/environments', () => ({
vi.mock('../runtime/metadata', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
getDefaultUserDataPath: getDefaultUserDataPathMock
}))
vi.mock('../runtime/launch', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
serveOrcaApp: serveOrcaAppMock
}))
vi.mock('../runtime/environments', () => ({
addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock,
removeEnvironment: vi.fn(),
resolveEnvironment: vi.fn()
}))
vi.mock('../shared/remote-runtime/host-store/runtime-environment-store', () => ({
vi.mock('../../shared/remote-runtime/host-store/runtime-environment-store', () => ({
listEnvironments: listEnvironmentsMock
}))
vi.mock('child_process', async () => {
const { createChildProcessModuleMock } = await import('./index-test-harness.js')
const { createChildProcessModuleMock } = await import('../index-test-harness.js')
return createChildProcessModuleMock(spawnMock)
})
import { main } from './index'
import { useWorktreeAwarenessEnvironment } from './index-test-harness'
import { main } from '../index'
import { useWorktreeAwarenessEnvironment } from '../index-test-harness'
describe('orca cli worktree awareness', () => {
useWorktreeAwarenessEnvironment({
@@ -1,7 +1,7 @@
import { normalizeTypedName } from '../shared/typed-name-normalization'
import type { RuntimeClient } from './runtime-client'
import { RuntimeClientError } from './runtime/types'
import { quoteCliCommandArgument } from './shell-command-quote'
import { normalizeTypedName } from '../../shared/typed-name-normalization'
import type { RuntimeClient } from '../runtime/client'
import { RuntimeClientError } from '../runtime/types'
import { quoteCliCommandArgument } from '../shell-command-quote'
/** `--environment local`: the caller's own Orca, even over an ambient ORCA_ENVIRONMENT or pairing code. */
export const LOCAL_ENVIRONMENT = 'local'
@@ -13,8 +13,8 @@ export function isLocalEnvironmentSelector(value: unknown): value is string {
/** `local` is reserved, so a saved entry named local is reached only by its id. */
export async function savedEnvironmentNamedLocal(): Promise<{ id: string } | undefined> {
const [{ getDefaultUserDataPath }, { listEnvironments }] = await Promise.all([
import('./runtime-client.js'),
import('../shared/remote-runtime/host-store/runtime-environment-store.js')
import('../runtime/metadata.js'),
import('../../shared/remote-runtime/host-store/runtime-environment-store.js')
])
return listEnvironments(getDefaultUserDataPath()).find((environment) =>
isLocalEnvironmentSelector(environment.name)
@@ -2,7 +2,8 @@
import type { OrcadManagedRuntimeStatus } from '../../shared/orcad-managed-runtime'
import type { HandlerContext } from '../dispatch'
import { printResult } from '../command-result-output'
import { RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client'
import { RuntimeClientError } from '../runtime/types'
import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope'
const STATUS_ATTEMPTS = 15
const STATUS_RETRY_MS = 2_000
@@ -8,12 +8,13 @@ import type {
OrcadManagedStopResult
} from '../../shared/orcad-managed-runtime'
import { ORCAD_RECOVERY_CHANGED_STATE_CODE } from '../../shared/orcad-managed-runtime'
import { MANAGED_SERVER_RUNTIME_CAPABILITY } from '../../shared/protocol-version'
import { MANAGED_SERVER_RUNTIME_CAPABILITY } from '../../shared/host-runtime-capabilities'
import type { RuntimeStatus } from '../../shared/runtime-session-contracts'
import type { CommandHandler, HandlerContext } from '../dispatch'
import { getRequiredStringFlag } from '../flags'
import { printResult } from '../command-result-output'
import { RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client'
import { RuntimeClientError } from '../runtime/types'
import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope'
import { formatManagedServerStatus } from './managed-server-format'
import { reportAfterClosedConnection } from './managed-server-reconnect'
@@ -2,8 +2,8 @@ import {
parseExecutionHostId,
type ExecutionHostId,
type ParsedExecutionHost
} from '../shared/execution-host'
import type { RuntimeListingHostScope } from '../shared/runtime-listing-host-scope'
} from '../../shared/execution-host'
import type { RuntimeListingHostScope } from '../../shared/runtime-listing-host-scope'
import { findEnvironmentByName } from './host-selector-alternatives'
export type OmittedHostScopeSelector = {
@@ -40,9 +40,9 @@ export async function resolveOmittedHostScopeSelectors(
async function listPairedEnvironments(): Promise<{ id: string; name: string }[]> {
const [, { getDefaultUserDataPath }, { listEnvironments }] = await Promise.all([
import('./runtime/environments.js'),
import('./runtime-client.js'),
import('../shared/remote-runtime/host-store/runtime-environment-store.js')
import('../runtime/environments.js'),
import('../runtime/metadata.js'),
import('../../shared/remote-runtime/host-store/runtime-environment-store.js')
])
return listEnvironments(getDefaultUserDataPath()).map((environment) => ({
id: environment.id,
@@ -1,17 +1,15 @@
import { existsSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import type { CommandHandler } from '../dispatch'
import { RuntimeClientError } from '../runtime-client'
import { RuntimeClientError } from '../runtime/types'
import { parseOrcaYaml } from '../../shared/orca-yaml'
import {
getEphemeralVmRecipeResultProjectRoot,
type EphemeralVmRecipeDoctorCheck,
type EphemeralVmRecipeDoctorResult
} from '../../shared/ephemeral-vm-recipes'
import {
getEphemeralVmRecipeResultWarnings,
redactEphemeralVmRecipeDiagnosticText
} from '../../shared/ephemeral-vm-recipe-diagnostics'
import { getEphemeralVmRecipeResultWarnings } from '../../shared/ephemeral-vm-recipe-diagnostics'
import { redactEphemeralVmRecipeDiagnosticText } from '../../shared/ephemeral-vm-recipe-diagnostic-redaction'
// This module uses Node fs/path; exporting it through the shared barrel would break browser bundles.
import { doctorEphemeralVmRecipe } from '../../shared/ephemeral-vm-recipe-doctor'
import {
+3 -4
View File
@@ -13,8 +13,8 @@ import { dispatch } from './dispatch'
import {
resolveEnvironmentSelectorForStore,
resolveHostFlagEnvironmentId
} from './execution-host-flag'
import { fetchSshTargetSummaries, listSshTargets } from './host-selector-alternatives'
} from './hosts/execution-host-flag'
import { fetchSshTargetSummaries, listSshTargets } from './hosts/host-selector-alternatives'
import { reportCliError } from './cli-error'
import { RuntimeClientError } from './runtime/types'
import { cliErrorExitCode } from './cli-exit-code'
@@ -27,10 +27,9 @@ import { ignoresRemoteSelection } from './remote-selection-scope'
import {
isLocalEnvironmentSelector,
refuseLocalManagementSelector
} from './local-environment-selector'
} from './hosts/local-environment-selector'
export { COMMAND_SPECS } from './specs'
export { buildCurrentWorktreeSelector, normalizeWorktreeSelector } from './selectors'
const COMMAND_PATHS = COMMAND_SPECS.flatMap((spec) => specPaths(spec))
@@ -6,7 +6,7 @@ const callMock = vi.hoisted(() => vi.fn())
const getTerminalHandleMock = vi.hoisted(() => vi.fn())
vi.mock('./command-result-output', () => ({ printResult: vi.fn() }))
vi.mock('./selectors', () => ({ getTerminalHandle: getTerminalHandleMock }))
vi.mock('./terminals/terminal-selector', () => ({ getTerminalHandle: getTerminalHandleMock }))
import { ORCHESTRATION_HANDLERS } from './handlers/orchestration'
import { findCommandSpec } from './args'
@@ -5,7 +5,7 @@ const callMock = vi.hoisted(() => vi.fn())
const getTerminalHandleMock = vi.hoisted(() => vi.fn())
vi.mock('./command-result-output', () => ({ printResult: vi.fn() }))
vi.mock('./selectors', () => ({ getTerminalHandle: getTerminalHandleMock }))
vi.mock('./terminals/terminal-selector', () => ({ getTerminalHandle: getTerminalHandleMock }))
import { ORCHESTRATION_HANDLERS } from './handlers/orchestration'
@@ -5,7 +5,7 @@ import type {
ProjectHostSetupDeleteResult,
ProjectHostSetupResult,
ProjectHostSetupUpdateResult
} from '../shared/project-types'
} from '../../shared/project-types'
export function formatProjectList(result: { projects: Project[] }): string {
if (result.projects.length === 0) {
@@ -1,8 +1,8 @@
import { normalizeExecutionHostId } from '../shared/execution-host'
import type { Project, ProjectHostSetup } from '../shared/project-types'
import { normalizeTypedName } from './host-selector-alternatives'
import type { RuntimeClient } from './runtime-client'
import { RuntimeClientError } from './runtime-client'
import { normalizeExecutionHostId } from '../../shared/execution-host'
import type { Project, ProjectHostSetup } from '../../shared/project-types'
import { normalizeTypedName } from '../../shared/typed-name-normalization'
import type { RuntimeClient } from '../runtime/client'
import { RuntimeClientError } from '../runtime/types'
function matchesName(value: string | undefined, selector: string): boolean {
return value !== undefined && normalizeTypedName(value) === normalizeTypedName(selector)
@@ -11,7 +11,7 @@ import type {
ProjectHostSetupUpdateResult
} from '../../shared/project-types'
import { getSshTargetIdForExecutionHost, type ExecutionHostId } from '../../shared/execution-host'
import type { RuntimeStatus } from '../../shared/runtime-types'
import type { RuntimeStatus } from '../../shared/runtime-session-contracts'
import { PROJECT_HOST_SETUP_HOST_TARGET_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities'
import type { CommandHandler, HandlerContext } from '../dispatch'
import {
@@ -21,17 +21,18 @@ import {
formatProjectHostSetupResult,
formatProjectHostSetupUpdateResult,
formatProjectList
} from '../project-format'
} from './project-format'
import { printResult } from '../command-result-output'
import {
hostFilterMatchesHostId,
parseHostFlag,
resolveHostFlagTarget
} from '../execution-host-flag'
} from '../hosts/execution-host-flag'
import { getOptionalRepoKind, getOptionalStringFlag, getRequiredStringFlag } from '../flags'
import { findProjectSetups, resolveProjectIdSelector } from '../project-selector'
import { resolveRepoPathArgument } from '../repo-path-arguments'
import { RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client'
import { findProjectSetups, resolveProjectIdSelector } from './project-selector'
import { resolveRepoPathArgument } from './repo-path-arguments'
import { RuntimeClientError } from '../runtime/types'
import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope'
async function callProjectHostSetup<TResult>(
client: HandlerContext['client'],
+27
View File
@@ -0,0 +1,27 @@
import type {
RuntimeRepoList,
RuntimeRepoSearchRefs
} from '../../shared/runtime-worktree-contracts'
export function formatRepoList(result: RuntimeRepoList): string {
if (result.repos.length === 0) {
return 'No repos found.'
}
return result.repos.map((repo) => `${repo.id} ${repo.displayName} ${repo.path}`).join('\n')
}
export function formatRepoShow(result: { repo: Record<string, unknown> }): string {
return Object.entries(result.repo)
.map(
([key, value]) =>
`${key}: ${typeof value === 'object' ? JSON.stringify(value) : String(value)}`
)
.join('\n')
}
export function formatRepoRefs(result: RuntimeRepoSearchRefs): string {
if (result.refs.length === 0) {
return 'No refs found.'
}
return result.truncated ? `${result.refs.join('\n')}\n\ntruncated: yes` : result.refs.join('\n')
}
@@ -1,5 +1,5 @@
import { resolve as resolvePath } from 'node:path'
import { RuntimeClientError } from './runtime-client'
import { RuntimeClientError } from '../runtime/types'
function isAbsoluteServerPath(value: string): boolean {
return (
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { parseArgs, validateCommandAndFlags } from '../args'
import { dispatch } from '../dispatch'
import { RuntimeClient } from '../runtime-client'
import { RuntimeClient } from '../runtime/client'
import { CORE_COMMAND_SPECS } from '../specs/core'
describe('repo set worktree visibility', () => {
@@ -33,24 +33,6 @@ describe('repo set worktree visibility', () => {
vi.restoreAllMocks()
})
it.each([
{ visibility: 'show', stored: 'show', repo: 'id:repo-1' },
{ visibility: 'hide', stored: 'hide', repo: 'name:Repo with spaces' },
{ visibility: 'inherit', stored: null, repo: String.raw`path:C:\Repos\My repo` },
{ visibility: 'show', stored: 'show', repo: 'path:/tmp/My repo' }
])(
'sets $visibility for $repo without changing other fields',
async ({ visibility, stored, repo }) => {
await run(['--repo', repo, '--external-worktree-visibility', visibility, '--json'])
expect(client.call).toHaveBeenCalledExactlyOnceWith('repo.update', {
repo,
updates: { externalWorktreeVisibility: stored }
})
expect(console.log).toHaveBeenCalledExactlyOnceWith(JSON.stringify(reply, null, 2))
}
)
it.each([
{ args: ['--repo', 'id:repo-1'], message: 'Missing required --external-worktree-visibility' },
{
@@ -1,15 +1,18 @@
import type { RuntimeRepoList, RuntimeRepoSearchRefs } from '../../shared/runtime-types'
import type {
RuntimeRepoList,
RuntimeRepoSearchRefs
} from '../../shared/runtime-worktree-contracts'
import type { CommandHandler } from '../dispatch'
import { formatRepoList, formatRepoRefs, formatRepoShow } from '../workspace-format'
import { formatRepoList, formatRepoRefs, formatRepoShow } from './repo-format'
import { printResult } from '../command-result-output'
import {
getOptionalPositiveIntegerFlag,
getOptionalRepoKind,
getRequiredStringFlag
} from '../flags'
import { resolveRepoPathArgument } from '../repo-path-arguments'
import { resolveRepoPathArgument } from './repo-path-arguments'
import { RuntimeClientError } from '../runtime/types'
import { attachCliErrorData } from './worktree-setup-decision-recovery'
import { attachCliErrorData } from '../workspaces/worktree-setup-decision-recovery'
export const REPO_HANDLERS: Record<string, CommandHandler> = {
'repo list': async ({ client, json }) => {
+1 -54
View File
@@ -11,7 +11,7 @@ import { sendRequest } from './transport'
import { formatCliError } from '../cli-error'
import { RuntimeClient } from './client'
import { getRuntimeMetadataPath } from '../../shared/runtime-bootstrap'
import { requestWorktreeRemoval } from '../handlers/worktree-removal-request'
import { requestWorktreeRemoval } from '../workspaces/worktree-removal-request'
vi.mock('node:net', async (importOriginal) => {
const net = await importOriginal<typeof Net>()
@@ -296,59 +296,6 @@ describe.skipIf(process.platform === 'win32')('runtime transport', () => {
}
})
it('refreshes the per-call timeout when the runtime sends keepalive frames', async () => {
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-transport-'))
roots.push(userDataPath)
const endpoint = join(userDataPath, 'runtime.sock')
let acceptRequest!: (request: { id: string; peer: Socket }) => void
const received = new Promise<{ id: string; peer: Socket }>((resolve) => {
acceptRequest = resolve
})
const server = createServer((socket) => {
sockets.add(socket)
socket.once('close', () => sockets.delete(socket))
socket.once('data', (data) => {
const request: { id: string } = JSON.parse(String(data).trim())
acceptRequest({ id: request.id, peer: socket })
})
})
servers.add(server)
await new Promise<void>((resolve) => server.listen(endpoint, resolve))
const metadata: RuntimeMetadata = {
runtimeId: 'runtime-1',
pid: 123,
transports: [{ kind: 'unix', endpoint }],
authToken: 'token',
startedAt: 1
}
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
const response = sendRequest<{ satisfied: boolean }>(
metadata,
'terminal.wait',
undefined,
200
).then(
(value) => ({ response: value }),
(error: unknown) => ({ error })
)
const client = requestSocket()
const { id, peer } = await received
await vi.advanceTimersByTimeAsync(150)
const keepalive = once(client, 'data')
peer.write('{"_keepalive":true}\n')
await keepalive
await vi.advanceTimersByTimeAsync(150)
peer.write(
`${JSON.stringify({ id, ok: true, result: { satisfied: true }, _meta: { runtimeId: 'runtime-1' } })}\n`
)
expect(await response).toMatchObject({
response: { ok: true, result: { satisfied: true } }
})
expect(vi.getTimerCount()).toBe(0)
})
it('rejects promptly when the runtime closes the socket before responding', async () => {
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-transport-'))
roots.push(userDataPath)
+1 -1
View File
@@ -17,7 +17,7 @@ import {
import './websocket-transport'
import '../../shared/remote-runtime/requests/remote-runtime-prepared-request-admission'
import { RuntimeClient } from './client'
import '../handlers/worktree-removal-request'
import '../workspaces/worktree-removal-request'
import { launchOrcaApp } from './launch'
import './environments'
import {
@@ -1,15 +1,15 @@
import type { HandlerGroup } from './handler-group-manifest'
import type { HandlerGroup } from '../handler-group-manifest'
// Split from handler-group-manifest.ts to keep it under the max-lines limit.
export const SERVE_PAIRING_HANDLER_GROUPS: readonly HandlerGroup[] = [
{
name: 'serve-restore',
keys: ['serve restore resume'],
load: async () => (await import('./handlers/serve-restore.js')).SERVE_RESTORE_HANDLERS
load: async () => (await import('./serve-restore.js')).SERVE_RESTORE_HANDLERS
},
{
name: 'pair',
keys: ['pair'],
load: async () => (await import('./handlers/pair.js')).PAIR_HANDLERS
load: async () => (await import('./pair.js')).PAIR_HANDLERS
}
]
@@ -18,8 +18,8 @@ const {
spawnMock: vi.fn()
}))
vi.mock('./runtime-client', async () => {
const { createRuntimeClientModuleMock } = await import('./index-test-harness.js')
vi.mock('../runtime/client', async () => {
const { createRuntimeClientModuleMock } = await import('../index-test-harness.js')
return createRuntimeClientModuleMock({
callMock,
runtimeClientConstructorMock,
@@ -28,23 +28,32 @@ vi.mock('./runtime-client', async () => {
})
})
vi.mock('./runtime/environments', () => ({
vi.mock('../runtime/metadata', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
getDefaultUserDataPath: getDefaultUserDataPathMock
}))
vi.mock('../runtime/launch', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
serveOrcaApp: serveOrcaAppMock
}))
vi.mock('../runtime/environments', () => ({
addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock,
removeEnvironment: vi.fn(),
resolveEnvironment: vi.fn()
}))
vi.mock('../shared/remote-runtime/host-store/runtime-environment-store', () => ({
vi.mock('../../shared/remote-runtime/host-store/runtime-environment-store', () => ({
listEnvironments: listEnvironmentsMock
}))
vi.mock('child_process', async () => {
const { createChildProcessModuleMock } = await import('./index-test-harness.js')
const { createChildProcessModuleMock } = await import('../index-test-harness.js')
return createChildProcessModuleMock(spawnMock)
})
import { main } from './index'
import { useWorktreeAwarenessEnvironment } from './index-test-harness'
import { main } from '../index'
import { useWorktreeAwarenessEnvironment } from '../index-test-harness'
describe('orca cli worktree awareness', () => {
useWorktreeAwarenessEnvironment({
@@ -1,8 +1,8 @@
import { toRuntimeExecutionHostId } from '../shared/execution-host'
import type { RuntimeTerminalShow } from '../shared/runtime-types'
import type { RuntimeTerminalReveal } from '../shared/workspace-layout/terminal-surfaces/terminal-pane-reveal'
import { RuntimeClient } from './runtime-client'
import { resolveEnvironment } from './runtime/environments'
import { toRuntimeExecutionHostId } from '../../shared/execution-host'
import type { RuntimeTerminalShow } from '../../shared/runtime-terminal-contracts'
import type { RuntimeTerminalReveal } from '../../shared/workspace-layout/terminal-surfaces/terminal-pane-reveal'
import { RuntimeClient } from '../runtime/client'
import { resolveEnvironment } from '../runtime/environments'
/** Paired servers have no window; reveal their pane through a local desktop if one is available. */
export async function revealPairedTerminalOnLocalDesktop(
@@ -1,13 +1,14 @@
import type {
RuntimeTerminalClose,
RuntimeWorktreeTerminalCloseResult
} from '../../shared/runtime-types'
} from '../../shared/runtime-terminal-contracts'
import type { CommandHandler } from '../dispatch'
import { formatTerminalClose } from '../terminal-format'
import { formatTerminalClose } from './terminal-format'
import { reportCliError } from '../cli-error'
import { printResult } from '../command-result-output'
import { RuntimeClientError } from '../runtime-client'
import { getRequiredWorktreeSelector, getTerminalHandle } from '../selectors'
import { RuntimeClientError } from '../runtime/types'
import { getRequiredWorktreeSelector } from '../workspace-selection/workspace-selector'
import { getTerminalHandle } from './terminal-selector'
import { describeUnconfirmedCloseStop } from '../../shared/terminal/pty/lifecycle/pty-liveness-verdict'
/** A false stop receipt is an error only when the host supplied a liveness verdict. */
@@ -4,7 +4,7 @@ import {
type PtyProcessCeilingState
} from '../../shared/terminal/pty/native-process/pty-process-ceiling-state'
import { printResult } from '../command-result-output'
import { RuntimeClientError } from '../runtime-client'
import { RuntimeClientError } from '../runtime/types'
type SeveredDaemonStatus = {
pid: number
@@ -1,12 +1,14 @@
import {
PTY_LIVE_NOTE,
describeUnconfirmedCloseStop
} from '../shared/terminal/pty/lifecycle/pty-liveness-verdict'
import { describeTerminalWaitBlockedReason } from '../shared/terminal/runtime-policy/terminal-wait-blocked-reason-legacy-alias'
import { formatListingHostScope, type WithAnnotatedHostScope } from './omitted-host-scope-selectors'
} from '../../shared/terminal/pty/lifecycle/pty-liveness-verdict'
import { describeTerminalWaitBlockedReason } from '../../shared/terminal/runtime-policy/terminal-wait-blocked-reason-legacy-alias'
import {
formatListingHostScope,
type WithAnnotatedHostScope
} from '../hosts/omitted-host-scope-selectors'
import type {
RuntimeTerminalClose,
RuntimeTerminalCreate,
RuntimeTerminalFocus,
RuntimeTerminalListResult,
RuntimeTerminalVisualLayout,
@@ -15,12 +17,13 @@ import type {
RuntimeTerminalVisualTab,
RuntimeTerminalRead,
RuntimeTerminalRename,
RuntimeTerminalSend,
RuntimeTerminalSetPaneTitle,
RuntimeTerminalShow,
RuntimeTerminalSplit,
RuntimeTerminalWait
} from '../shared/runtime-types'
} from '../../shared/runtime-terminal-contracts'
import type { RuntimeTerminalCreate } from '../../shared/runtime-terminal-create-contract'
import type { RuntimeTerminalSend } from '../../shared/runtime-terminal-send-contract'
export function formatTerminalList(
result: WithAnnotatedHostScope<RuntimeTerminalListResult>
@@ -18,8 +18,8 @@ const {
spawnMock: vi.fn()
}))
vi.mock('./runtime-client', async () => {
const { createRuntimeClientModuleMock } = await import('./index-test-harness.js')
vi.mock('../runtime/client', async () => {
const { createRuntimeClientModuleMock } = await import('../index-test-harness.js')
return createRuntimeClientModuleMock({
callMock,
runtimeClientConstructorMock,
@@ -28,24 +28,33 @@ vi.mock('./runtime-client', async () => {
})
})
vi.mock('./runtime/environments', () => ({
vi.mock('../runtime/metadata', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
getDefaultUserDataPath: getDefaultUserDataPathMock
}))
vi.mock('../runtime/launch', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
serveOrcaApp: serveOrcaAppMock
}))
vi.mock('../runtime/environments', () => ({
addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock,
removeEnvironment: vi.fn(),
resolveEnvironment: vi.fn()
}))
vi.mock('../shared/remote-runtime/host-store/runtime-environment-store', () => ({
vi.mock('../../shared/remote-runtime/host-store/runtime-environment-store', () => ({
listEnvironments: listEnvironmentsMock
}))
vi.mock('child_process', async () => {
const { createChildProcessModuleMock } = await import('./index-test-harness.js')
const { createChildProcessModuleMock } = await import('../index-test-harness.js')
return createChildProcessModuleMock(spawnMock)
})
import { main } from './index'
import { okFixture, queueFixtures } from './test-fixtures'
import { useWorktreeAwarenessEnvironment } from './index-test-harness'
import { main } from '../index'
import { okFixture, queueFixtures } from '../test-fixtures'
import { useWorktreeAwarenessEnvironment } from '../index-test-harness'
function readFixture(overrides: Record<string, unknown> = {}) {
return okFixture('req_terminal_read', {
+22
View File
@@ -0,0 +1,22 @@
import type { RuntimeClient } from '../runtime/client'
import { getPresentStringFlag } from '../flags'
import type { WorkspaceSelectionPurpose } from '../workspace-selection/caller-host-worktree-selection'
import { getBrowserWorktreeSelector } from '../workspace-selection/workspace-selector'
export async function getTerminalHandle(
flags: Map<string, string | boolean>,
cwd: string,
client: RuntimeClient,
options: { requireUnambiguous?: boolean; purpose?: WorkspaceSelectionPurpose } = {}
): Promise<string> {
const explicit = getPresentStringFlag(flags, 'terminal')
if (explicit) {
return explicit
}
const worktree = await getBrowserWorktreeSelector(flags, cwd, client, options.purpose)
const response = await client.call<{ handle: string }>('terminal.resolveActive', {
worktree,
...(options.requireUnambiguous ? { requireUnambiguous: true } : {})
})
return response.result.handle
}
@@ -1,14 +1,14 @@
import type { RuntimeTerminalSend } from '../../shared/runtime-types'
import type { RuntimeTerminalSend } from '../../shared/runtime-terminal-send-contract'
import '../../shared/protocol-version'
import { TERMINAL_PROMPT_DELIVERY_RUNTIME_CAPABILITY } from '../../shared/terminal/runtime-policy/terminal-runtime-capabilities'
import type { CommandHandler } from '../dispatch'
import { formatTerminalSend, terminalSendWarnings } from '../terminal-format'
import { formatTerminalSend, terminalSendWarnings } from './terminal-format'
import { printResult } from '../command-result-output'
import { getOptionalPositiveIntegerFlag, getOptionalStringFlag } from '../flags'
import { readRetryRequestFlag } from '../retry-request-flag'
import { RuntimeClientError } from '../runtime-client'
import { RuntimeClientError } from '../runtime/types'
import { attachUnverifiedTerminalPromptRecovery } from '../runtime/terminal-prompt-mutation-recovery'
import { getTerminalHandle } from '../selectors'
import { getTerminalHandle } from './terminal-selector'
type TerminalSendResult = { send: RuntimeTerminalSend; warnings?: string[] }
@@ -0,0 +1,26 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { RuntimeClient } from '../runtime/client'
import { parseArgs } from '../args'
import { TERMINAL_HANDLERS } from './terminal'
afterEach(() => vi.restoreAllMocks())
describe('terminal set-pane-title', () => {
it.each([{ args: [] }, { args: ['--title'] }])(
'refuses a missing title before resolving a terminal (%j)',
async ({ args }) => {
const client = new RuntimeClient()
const call = vi.spyOn(client, 'call')
const parsed = parseArgs(['terminal', 'set-pane-title', ...args])
await expect(
TERMINAL_HANDLERS['terminal set-pane-title']({
flags: parsed.flags,
client,
cwd: '/tmp',
json: true
})
).rejects.toMatchObject({ code: 'invalid_argument' })
expect(call).not.toHaveBeenCalled()
}
)
})
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { RuntimeClient } from '../runtime-client'
import type { CliStatusResult } from '../../shared/runtime-types'
import { RuntimeClient } from '../runtime/client'
import type { CliStatusResult } from '../../shared/runtime-session-contracts'
import '../../shared/protocol-version'
import { TERMINAL_SPLIT_RETRY_RUNTIME_CAPABILITY } from '../../shared/terminal/runtime-policy/terminal-runtime-capabilities'
import { TERMINAL_HANDLERS } from './terminal'
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { RuntimeClient } from '../runtime-client'
import type { CliStatusResult } from '../../shared/runtime-types'
import { RuntimeClient } from '../runtime/client'
import type { CliStatusResult } from '../../shared/runtime-session-contracts'
import '../../shared/protocol-version'
import { TERMINAL_PROMPT_DELIVERY_RUNTIME_CAPABILITY } from '../../shared/terminal/runtime-policy/terminal-runtime-capabilities'
import { TERMINAL_HANDLERS } from './terminal'
@@ -1,5 +1,5 @@
import type { RuntimeTerminalCreate } from '../../shared/runtime-terminal-create-contract'
import type {
RuntimeTerminalCreate,
RuntimeTerminalFocus,
RuntimeTerminalListResult,
RuntimeTerminalRead,
@@ -8,9 +8,9 @@ import type {
RuntimeTerminalShow,
RuntimeTerminalSplit,
RuntimeTerminalWait
} from '../../shared/runtime-types'
} from '../../shared/runtime-terminal-contracts'
import type { CommandHandler } from '../dispatch'
import { shouldUseRendererBackedInteractiveTerminal } from '../codex-command-classification'
import { shouldUseRendererBackedInteractiveTerminal } from './codex-command-classification'
import {
formatTerminalCreate,
formatTerminalFocus,
@@ -21,7 +21,7 @@ import {
formatTerminalShow,
formatTerminalSplit,
formatTerminalWait
} from '../terminal-format'
} from './terminal-format'
import { printResult } from '../command-result-output'
import {
getOptionalPositiveIntegerFlag,
@@ -32,8 +32,8 @@ import {
import {
annotateOmittedHostScope,
type WithAnnotatedHostScope
} from '../omitted-host-scope-selectors'
import { RuntimeClientError } from '../runtime-client'
} from '../hosts/omitted-host-scope-selectors'
import { RuntimeClientError } from '../runtime/types'
import {
isSupportedWindowsShellOverride,
listSupportedWindowsShellOverrides
@@ -46,10 +46,10 @@ import {
import {
getBrowserWorktreeSelector,
getOptionalWorktreeSelector,
getRequiredWorktreeSelector,
getTerminalHandle
} from '../selectors'
import { revealPairedTerminalOnLocalDesktop } from '../paired-terminal-desktop-reveal'
getRequiredWorktreeSelector
} from '../workspace-selection/workspace-selector'
import { getTerminalHandle } from './terminal-selector'
import { revealPairedTerminalOnLocalDesktop } from './paired-terminal-desktop-reveal'
import { terminalCloseHandler } from './terminal-close'
import { terminalSendHandler } from './terminal-send'
-251
View File
@@ -1,251 +0,0 @@
import { formatAddressLines, formatParentLine, type WorkspaceAnnotation } from './workspace-address'
import type { PublicKnownRuntimeEnvironment } from '../shared/remote-runtime/host-catalog/runtime-environments'
import type {
RuntimeRepoList,
RuntimeRepoSearchRefs,
RuntimeWorktreeListResult,
RuntimeWorktreePsResult,
RuntimeWorktreeRecord
} from '../shared/runtime-types'
import type { MemorySnapshot, WorktreeMemory } from '../shared/process-stats-types'
import { formatListingHostScope, type WithAnnotatedHostScope } from './omitted-host-scope-selectors'
import { formatWorktreePsTerminalFields } from './worktree-ps-terminal-verdict'
import { formatWorktreePsProgramStatus } from './worktree-ps-program-status'
export function formatMemorySnapshot(snapshot: MemorySnapshot): string {
const topWorktrees = [...snapshot.worktrees].sort((a, b) => b.memory - a.memory).slice(0, 10)
const hostAvailable = snapshot.host.availableMemory ?? snapshot.host.freeMemory
const hostAvailableSource = snapshot.host.availableMemorySource ?? 'free-memory'
const lines = [
`collectedAt: ${new Date(snapshot.collectedAt).toISOString()}`,
`totalMemory: ${formatByteCount(snapshot.totalMemory)}`,
`processMemoryMetric: ${formatProcessMemoryMetric(snapshot.processMemoryMetric)}`,
...formatCommitLines(snapshot),
`totalCpu: ${formatCpu(snapshot.totalCpu)}`,
[
`hostUsed: ${formatByteCount(snapshot.host.usedMemory)}`,
`/ ${formatByteCount(snapshot.host.totalMemory)}`,
`(${snapshot.host.memoryUsagePercent.toFixed(1)}%)`
].join(' '),
[`hostAvailable: ${formatByteCount(hostAvailable)}`, `(${hostAvailableSource})`].join(' '),
[
`app: ${formatByteCount(snapshot.app.memory)}`,
`(main ${formatByteCount(snapshot.app.main.memory)},`,
`renderer ${formatByteCount(snapshot.app.renderer.memory)},`,
`other ${formatByteCount(snapshot.app.other.memory)})`
].join(' '),
`worktrees: ${snapshot.worktrees.length}`
]
if (topWorktrees.length === 0) {
lines.push('topWorktrees: none')
return lines.join('\n')
}
lines.push('', 'Top worktrees:')
for (const worktree of topWorktrees) {
lines.push(formatWorktreeMemoryLine(worktree))
}
if (snapshot.worktrees.length > topWorktrees.length) {
lines.push(`... ${snapshot.worktrees.length - topWorktrees.length} more worktrees`)
}
return lines.join('\n')
}
function formatWorktreeMemoryLine(worktree: WorktreeMemory): string {
return [
`- ${worktree.worktreeName}`,
`${formatByteCount(worktree.memory)}`,
...(worktree.privateMemory === undefined
? []
: [`${formatByteCount(worktree.privateMemory)} committed`]),
`${formatCpu(worktree.cpu)}`,
`${worktree.sessions.length} session${worktree.sessions.length === 1 ? '' : 's'}`
].join(' ')
}
// Missing commit fields mean unknown usage, not zero.
function formatCommitLines(snapshot: MemorySnapshot): string[] {
if (typeof snapshot.totalPrivateMemory !== 'number') {
return []
}
return [
`totalPrivateMemory: ${formatByteCount(snapshot.totalPrivateMemory)}`,
`processCommitMetric: ${formatProcessCommitMetric(snapshot.processCommitMetric)}`
]
}
function formatProcessCommitMetric(metric: MemorySnapshot['processCommitMetric']): string {
return metric === 'private-bytes'
? 'summed private bytes; committed memory, counted whether resident or paged out'
: `summed ${metric ?? 'unknown'}`
}
function formatCpu(cpu: number): string {
return `${cpu.toFixed(1)}%`
}
function formatProcessMemoryMetric(metric: MemorySnapshot['processMemoryMetric']): string {
if (metric === 'footprint') {
return 'summed memory footprint (Activity Monitor); includes graphics memory'
}
return metric === 'working-set'
? 'summed working set; shared pages may repeat'
: 'summed RSS; shared or aliased pages may repeat'
}
function formatByteCount(bytes: number): string {
if (!Number.isFinite(bytes) || bytes <= 0) {
return '0 B'
}
const units = ['B', 'KB', 'MB', 'GB', 'TB']
let value = bytes
let unitIndex = 0
while (value >= 1024 && unitIndex < units.length - 1) {
value /= 1024
unitIndex += 1
}
const formatted = value >= 10 || unitIndex === 0 ? value.toFixed(0) : value.toFixed(1)
return `${formatted} ${units[unitIndex]}`
}
export function formatEnvironmentList(result: {
environments: PublicKnownRuntimeEnvironment[]
}): string {
if (result.environments.length === 0) {
return 'No saved environments.'
}
return result.environments
.map(
(environment) =>
`${environment.id} ${environment.name} ${environment.endpoints[0]?.endpoint ?? 'no-endpoint'}`
)
.join('\n')
}
export function formatEnvironment(environment: PublicKnownRuntimeEnvironment): string {
return [
`id: ${environment.id}`,
`name: ${environment.name}`,
`runtimeId: ${environment.runtimeId ?? 'unknown'}`,
`lastUsedAt: ${environment.lastUsedAt ?? 'never'}`,
`preferredEndpointId: ${environment.preferredEndpointId}`,
...environment.endpoints.map(
(endpoint) => `endpoint: ${endpoint.id} ${endpoint.kind} ${endpoint.endpoint}`
)
].join('\n')
}
type AnnotatedPsRow = RuntimeWorktreePsResult['worktrees'][number] & Partial<WorkspaceAnnotation>
export function formatWorktreePs(
result: WithAnnotatedHostScope<
Omit<RuntimeWorktreePsResult, 'worktrees'> & { worktrees: AnnotatedPsRow[] }
>
): string {
const scope = formatListingHostScope(result.hostScope)
if (result.worktrees.length === 0) {
return `No worktrees found.\n${scope}`
}
const body = result.worktrees
.map(
(worktree) =>
`${worktree.repo} ${worktree.branch} host=${worktree.hostId ?? 'unverifiable'} ${formatWorktreePsTerminalFields(worktree)} unread:${worktree.unread ? 'yes' : 'no'}${formatWorktreePsProgramStatus(worktree.agents)}\n${worktree.path}${formatWorktreePsLocation(worktree)}${worktree.preview ? `\npreview: ${worktree.preview}` : ''}`
)
.join('\n\n')
const bodyWithScope = `${body}\n\n${scope}`
return result.truncated
? `${bodyWithScope}\ntruncated: showing ${result.worktrees.length} of ${result.totalCount}`
: bodyWithScope
}
function formatWorktreePsLocation(worktree: AnnotatedPsRow): string {
const annotation = workspaceAnnotationOf(worktree)
return annotation
? `${formatParentLine(annotation)}${formatAddressLines(annotation)}`
: formatWorktreePsParent(worktree)
}
/** The parent line, in the sidebar's precedence: worktree, then folder workspace, then another machine. */
function formatWorktreePsParent(worktree: RuntimeWorktreePsResult['worktrees'][number]): string {
const parent =
worktree.parentWorktreeId ??
worktree.workspaceLineage?.parentWorkspaceKey ??
(worktree.crossStoreParent
? `${worktree.crossStoreParent.parent.workspaceKey} on another machine`
: null)
return parent ? `\nparent: ${parent}` : ''
}
export function formatRepoList(result: RuntimeRepoList): string {
if (result.repos.length === 0) {
return 'No repos found.'
}
return result.repos.map((repo) => `${repo.id} ${repo.displayName} ${repo.path}`).join('\n')
}
export function formatRepoShow(result: { repo: Record<string, unknown> }): string {
return Object.entries(result.repo)
.map(
([key, value]) =>
`${key}: ${typeof value === 'object' ? JSON.stringify(value) : String(value)}`
)
.join('\n')
}
export function formatRepoRefs(result: RuntimeRepoSearchRefs): string {
if (result.refs.length === 0) {
return 'No refs found.'
}
return result.truncated ? `${result.refs.join('\n')}\n\ntruncated: yes` : result.refs.join('\n')
}
export function formatWorktreeList(
result: WithAnnotatedHostScope<RuntimeWorktreeListResult>
): string {
const scope = formatListingHostScope(result.hostScope)
if (result.worktrees.length === 0) {
return `No worktrees found.\n${scope}`
}
const body = result.worktrees
.map((worktree) => {
const childCount = worktree.childWorktreeIds?.length ?? 0
return `${String(worktree.id)} ${String(worktree.branch)} host=${String(worktree.hostId ?? 'unverifiable')} ${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')
const bodyWithScope = `${body}\n\n${scope}`
return result.truncated
? `${bodyWithScope}\ntruncated: showing ${result.worktrees.length} of ${result.totalCount}`
: bodyWithScope
}
const ANNOTATION_KEYS = new Set(['environment', 'address', 'addressUnavailable', 'parent'])
function workspaceAnnotationOf(record: Partial<WorkspaceAnnotation>): WorkspaceAnnotation | null {
const { environment, address, addressUnavailable, parent } = record
return environment
? {
environment,
address: address ?? null,
parent: parent ?? null,
...(addressUnavailable ? { addressUnavailable } : {})
}
: null
}
export function formatWorktreeShow(result: {
worktree: RuntimeWorktreeRecord & Partial<WorkspaceAnnotation>
}): string {
const worktree = result.worktree
const annotation = workspaceAnnotationOf(worktree)
const fields = Object.entries(worktree)
.filter(([key]) => !annotation || !ANNOTATION_KEYS.has(key))
.map(
([key, value]) =>
`${key}: ${typeof value === 'object' ? JSON.stringify(value) : String(value)}`
)
.join('\n')
return annotation
? `${fields}${formatParentLine(annotation)}${formatAddressLines(annotation)}`
: fields
}
+4 -1
View File
@@ -11,7 +11,10 @@ import { printResult } from '../command-result-output'
import { formatPortsScan } from './ports-format'
import { RuntimeClientError, RuntimeRpcFailureError } from '../runtime/types'
import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope'
import { normalizeWorktreeSelectorForCaller, resolveCurrentWorktreeSelector } from '../selectors'
import {
normalizeWorktreeSelectorForCaller,
resolveCurrentWorktreeSelector
} from '../workspace-selection/workspace-selector'
type PortsTarget = { selector: string; worktreePath: string | null }
@@ -2,9 +2,9 @@ import { resolve as resolvePath } from 'node:path'
import {
isPathInsideOrEqual,
normalizeRuntimePathForComparison
} from '../shared/cross-platform-path'
import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../shared/execution-host'
import { resolveRealPathSync } from '../shared/real-path-sync'
} from '../../shared/cross-platform-path'
import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../shared/execution-host'
import { resolveRealPathSync } from '../../shared/real-path-sync'
// One CLI process is one command, so the folder prefilter and ranking share each resolution.
const realPaths = new Map<string, string>()
@@ -1,11 +1,16 @@
import type { FolderWorkspace } from '../shared/folder-workspaces/folder-workspace-types'
import { getFolderSourceRepos } from '../shared/folder-workspaces/folder-workspace-source-repos'
import type { ProjectGroup } from '../shared/project-group-types'
import type { Repo } from '../shared/repo-types'
import { folderWorkspaceKey, parseWorkspaceKey, type WorkspaceKey } from '../shared/workspace-scope'
import { getOptionalStringFlag } from './flags'
import { RuntimeClientError, type RuntimeClient } from './runtime-client'
import { getOptionalWorktreeSelector } from './selectors'
import type { FolderWorkspace } from '../../shared/folder-workspaces/folder-workspace-types'
import { getFolderSourceRepos } from '../../shared/folder-workspaces/folder-workspace-source-repos'
import type { ProjectGroup } from '../../shared/project-group-types'
import type { Repo } from '../../shared/repo-types'
import {
folderWorkspaceKey,
parseWorkspaceKey,
type WorkspaceKey
} from '../../shared/workspace-scope'
import { getOptionalStringFlag } from '../flags'
import { RuntimeClientError } from '../runtime/types'
import type { RuntimeClient } from '../runtime/client'
import { getOptionalWorktreeSelector } from './workspace-selector'
export type FolderWorkspaceRepoChoice = {
repo: string
@@ -1,23 +1,21 @@
import { resolve as resolvePath } from 'node:path'
import type { TuiAgent } from '../shared/agent-launch/catalog/tui-agent'
import { projectGroupIdFromRepoId } from '../shared/folder-workspaces/folder-workspace-worktree'
import { isFloatingWorkspaceId } from '../shared/floating-workspace-worktree'
import { parseWorkspaceKey } from '../shared/workspace-scope'
import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent'
import { projectGroupIdFromRepoId } from '../../shared/folder-workspaces/folder-workspace-worktree'
import { isFloatingWorkspaceId } from '../../shared/floating-workspace-worktree'
import { parseWorkspaceKey } from '../../shared/workspace-scope'
import {
LOCAL_EXECUTION_HOST_ID,
parseExecutionHostId,
toSshExecutionHostId,
type ExecutionHostId
} from '../shared/execution-host'
import { readOrchestrationCompatibilityEvidence } from '../shared/orchestration/orchestration-compatibility-evidence'
import type { RuntimeWorktreeListResult } from '../shared/runtime-types'
import type { RuntimeClient } from './runtime-client'
import { RuntimeClientError } from './runtime/types'
} from '../../shared/execution-host'
import { readOrchestrationCompatibilityEvidence } from '../../shared/orchestration/orchestration-compatibility-evidence'
import type { RuntimeWorktreeListResult } from '../../shared/runtime-worktree-contracts'
import type { RuntimeClient } from '../runtime/client'
import { RuntimeClientError } from '../runtime/types'
import { refuseUnresolvedOwner, type CatalogRow } from './workspace-catalog-row'
import { createCwdContainment, isOnCallerFilesystem } from './caller-cwd-containment'
export type { CatalogRow }
/** Group-level folder workspaces join the catalog keyed `folder:<id>`, beside repo-backed rows. */
function isFolderRow(row: CatalogRow): boolean {
return parseWorkspaceKey(row.id)?.type === 'folder'
@@ -1,14 +1,14 @@
import { createCwdContainment, isOnCallerFilesystem } from './caller-cwd-containment'
import { getCallerExecutionHostId } from './caller-host-worktree-selection'
import { resolveQualifiedFolderWorkspaceResult } from '../shared/folder-workspaces/folder-workspace-execution-host'
import type { FolderWorkspace } from '../shared/folder-workspaces/folder-workspace-types'
import type { ProjectGroup } from '../shared/project-group-types'
import type { Repo } from '../shared/repo-types'
import type { RuntimeWorktreeListResult } from '../shared/runtime-types'
import { folderWorkspaceKey } from '../shared/workspace-scope'
import { resolveQualifiedFolderWorkspaceResult } from '../../shared/folder-workspaces/folder-workspace-execution-host'
import type { FolderWorkspace } from '../../shared/folder-workspaces/folder-workspace-types'
import type { ProjectGroup } from '../../shared/project-group-types'
import type { Repo } from '../../shared/repo-types'
import type { RuntimeWorktreeListResult } from '../../shared/runtime-worktree-contracts'
import { folderWorkspaceKey } from '../../shared/workspace-scope'
import type { CatalogRow } from './workspace-catalog-row'
import type { RuntimeClient } from './runtime-client'
import { RuntimeClientError } from './runtime/types'
import type { RuntimeClient } from '../runtime/client'
import { RuntimeClientError } from '../runtime/types'
/** An older Orca without the folder catalog keeps its repo-backed rows; any other failure is real. */
async function readOptional<TResult>(read: Promise<TResult>): Promise<TResult | undefined> {
@@ -2,14 +2,12 @@ import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, describe, expect, it, vi } from 'vitest'
import {
selectEnclosingWorktreeSelectionOnHost,
type CatalogRow
} from './caller-host-worktree-selection'
import { selectEnclosingWorktreeSelectionOnHost } from './caller-host-worktree-selection'
import type { CatalogRow } from './workspace-catalog-row'
import { readEnclosingWorkspaceCatalog } from './enclosing-workspace-catalog'
import { RuntimeClient } from './runtime-client'
import { RuntimeClientError } from './runtime/types'
import { okFixture } from './test-fixtures'
import { RuntimeClient } from '../runtime/client'
import { RuntimeClientError } from '../runtime/types'
import { okFixture } from '../test-fixtures'
const hubFolder = { id: 'folder:hub', path: '/tmp/hub', hostId: 'local' as const }
const innerFolder = { id: 'folder:inner', path: '/tmp/hub/inner', hostId: 'local' as const }
@@ -1,7 +1,7 @@
import type { RuntimeWorktreeRecord } from '../shared/runtime-types'
import { parseWorkspaceKey } from '../shared/workspace-scope'
import type { RuntimeClient } from './runtime-client'
import { RuntimeClientError } from './runtime/types'
import type { RuntimeWorktreeRecord } from '../../shared/runtime-worktree-contracts'
import { parseWorkspaceKey } from '../../shared/workspace-scope'
import type { RuntimeClient } from '../runtime/client'
import { RuntimeClientError } from '../runtime/types'
export function mayNameFolderWorkspace(selector: string): boolean {
return selector.startsWith('path:') || selector.startsWith('name:')
@@ -1,6 +1,6 @@
import type { RuntimeWorktreeRecord } from '../shared/runtime-types'
import { parseWorkspaceKey } from '../shared/workspace-scope'
import { RuntimeClientError } from './runtime/types'
import type { RuntimeWorktreeRecord } from '../../shared/runtime-worktree-contracts'
import { parseWorkspaceKey } from '../../shared/workspace-scope'
import { RuntimeClientError } from '../runtime/types'
/** One workspace the cwd rule can pick: a repo-backed row or a group-level folder keyed `folder:<id>`. */
export type CatalogRow = Pick<RuntimeWorktreeRecord, 'id' | 'path' | 'hostId'> & {
@@ -1,17 +1,15 @@
import { resolve as resolvePath } from 'node:path'
import type { ComputerAppQuery } from '../shared/runtime-types'
import { resolveFolderWorkspaceSelector } from './folder-workspace-selector'
import { resolveCallerDistroPathSelector } from './wsl-caller-path-selector'
import type { RuntimeClient } from './runtime-client'
import { RuntimeClientError } from './runtime/types'
import { assertLocalCwdWorktreeSelector } from './local-environment-selector'
import { isLaunchedByAnotherRuntime } from './runtime/runtime-source-fence'
import { getOptionalStringFlag, getPresentStringFlag, getRequiredStringFlag } from './flags'
import type { RuntimeClient } from '../runtime/client'
import { RuntimeClientError } from '../runtime/types'
import { assertLocalCwdWorktreeSelector } from '../hosts/local-environment-selector'
import { isLaunchedByAnotherRuntime } from '../runtime/runtime-source-fence'
import { getOptionalStringFlag, getRequiredStringFlag } from '../flags'
import { readEnclosingWorkspaceCatalog } from './enclosing-workspace-catalog'
import {
getCallerExecutionHostId,
getCallerWorkspaceIds,
resolveCallerPaneWorktreeSelector,
selectWorktreeCreateCwdContext,
selectEnclosingWorktreeSelectionOnHost,
selectCallerTerminalWorkspace,
@@ -20,12 +18,6 @@ import {
type HostScopedWorktreeSelection
} from './caller-host-worktree-selection'
export type ComputerCliTarget = {
session?: string
worktree?: string
app: ComputerAppQuery
}
export function buildCurrentWorktreeSelector(cwd: string): string {
return `path:${resolvePath(cwd)}`
}
@@ -126,21 +118,6 @@ export async function getRequiredWorktreeSelector(
return await normalizeWorktreeSelectorForCaller(value, cwd, client, selectorPurpose(name))
}
async function optionalCurrentWorktreeSelector(
cwd: string,
client: RuntimeClient,
purpose: WorkspaceSelectionPurpose = 'worktree'
) {
try {
return await resolveCurrentWorktreeSelector(cwd, client, purpose)
} catch (error) {
if (error instanceof RuntimeClientError && error.code === 'selector_ambiguous') {
throw error
}
return undefined
}
}
// Remote commands leave worktree unset to use server-side focus.
export async function getBrowserWorktreeSelector(
flags: Map<string, string | boolean>,
@@ -178,101 +155,3 @@ export async function getBrowserWorktreeSelector(
// An Orca terminal knows its workspace; without this an unmanaged cwd lands in the focused one.
return selectCallerTerminalWorkspace(catalog, hostId)
}
export async function getTerminalHandle(
flags: Map<string, string | boolean>,
cwd: string,
client: RuntimeClient,
options: { requireUnambiguous?: boolean; purpose?: WorkspaceSelectionPurpose } = {}
): Promise<string> {
const explicit = getPresentStringFlag(flags, 'terminal')
if (explicit) {
return explicit
}
const worktree = await getBrowserWorktreeSelector(flags, cwd, client, options.purpose)
const response = await client.call<{ handle: string }>('terminal.resolveActive', {
worktree,
...(options.requireUnambiguous ? { requireUnambiguous: true } : {})
})
return response.result.handle
}
export async function getComputerCommandTarget(
flags: Map<string, string | boolean>,
cwd: string,
client: RuntimeClient
): Promise<ComputerCliTarget> {
const app = getRequiredStringFlag(flags, 'app')
const session = getOptionalStringFlag(flags, 'session')
const worktree = getOptionalStringFlag(flags, 'worktree')
if (session && worktree) {
throw new RuntimeClientError(
'invalid_argument',
'Computer-use targeting accepts either --session or --worktree, not both'
)
}
if (session) {
return { session, app }
}
return {
app,
worktree: await getBrowserWorktreeSelector(flags, cwd, client)
}
}
export type EmulatorCliTarget = {
worktree?: string
device?: string
emulator?: string // Orca id from list
}
export async function getEmulatorWorktreeSelector(
flags: Map<string, string | boolean>,
cwd: string,
client: RuntimeClient
): Promise<string | undefined> {
const explicit = getOptionalStringFlag(flags, 'worktree')
if (explicit === 'all') {
return undefined
}
if (explicit) {
if (explicit === 'active' || explicit === 'current') {
assertLocalCwdWorktreeSelector(explicit, client)
return resolveCurrentWorktreeSelector(cwd, client)
}
return explicit
}
if (client.isRemote) {
return undefined
}
const terminalWorktreeId = process.env.ORCA_WORKTREE_ID
if (terminalWorktreeId?.trim()) {
const scoped = await resolveCallerPaneWorktreeSelector(terminalWorktreeId, client)
if (scoped) {
return scoped
}
}
const folderWorkspaceId = process.env.ORCA_WORKSPACE_ID?.trim()
if (folderWorkspaceId?.startsWith('folder:')) {
return folderWorkspaceId
}
return optionalCurrentWorktreeSelector(cwd, client)
}
export async function getEmulatorCommandTarget(
flags: Map<string, string | boolean>,
cwd: string,
client: RuntimeClient
): Promise<EmulatorCliTarget> {
const device = getOptionalStringFlag(flags, 'device')
const emulator = getOptionalStringFlag(flags, 'emulator')
const worktree = await getEmulatorWorktreeSelector(flags, cwd, client)
if (device || emulator) {
return {
device: device || undefined,
emulator: emulator || undefined,
worktree
}
}
return { worktree }
}
@@ -1,9 +1,9 @@
// These selectors also reach worktree rm, so translate only with proof of the caller's distro.
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { RuntimeWorktreeRecord } from '../shared/runtime-types'
import type { RuntimeClient } from './runtime-client'
import { RuntimeClientError } from './runtime/types'
import { normalizeWorktreeSelectorForCaller } from './selectors'
import type { RuntimeWorktreeRecord } from '../../shared/runtime-worktree-contracts'
import type { RuntimeClient } from '../runtime/client'
import { RuntimeClientError } from '../runtime/types'
import { normalizeWorktreeSelectorForCaller } from './workspace-selector'
const UBUNTU = 'Ubuntu-24.04'
const DEBIAN = 'Debian'
@@ -1,12 +1,12 @@
import type { FolderWorkspace } from '../shared/folder-workspaces/folder-workspace-types'
import type { RuntimeWorktreeListResult } from '../shared/runtime-types'
import type { FolderWorkspace } from '../../shared/folder-workspaces/folder-workspace-types'
import type { RuntimeWorktreeListResult } from '../../shared/runtime-worktree-contracts'
import {
isWslUncPathForCallerLinuxPath,
isWslUncPathForLinuxMountedPath
} from '../shared/cross-platform-path'
import { parseWslUncPath } from '../shared/wsl-paths'
import type { RuntimeClient } from './runtime-client'
import { RuntimeClientError, RuntimeRpcFailureError } from './runtime/types'
} from '../../shared/cross-platform-path'
import { parseWslUncPath } from '../../shared/wsl-paths'
import type { RuntimeClient } from '../runtime/client'
import { RuntimeClientError, RuntimeRpcFailureError } from '../runtime/types'
async function listFolderPaths(client: RuntimeClient): Promise<string[]> {
try {
@@ -1,5 +1,5 @@
import type { RuntimeClient } from '../runtime-client'
import type { RuntimeStatus } from '../../shared/runtime-types'
import type { RuntimeClient } from '../runtime/client'
import type { RuntimeStatus } from '../../shared/runtime-session-contracts'
import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR } from '../../shared/worktree/id'
import { WORKTREE_FOLDER_SETUP_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities'
@@ -1,16 +1,18 @@
import type { RuntimeStatus } from '../../shared/runtime-session-contracts'
import type {
RuntimeStatus,
RuntimeWorktreeRecord,
RuntimeWorktreeRemoveResult,
RuntimeWorktreeSetResult
} from '../../shared/runtime-types'
} from '../../shared/runtime-worktree-contracts'
import type { FolderWorkspace } from '../../shared/folder-workspaces/folder-workspace-types'
import { FOLDER_WORKSPACE_UNIQUE_ID_MUTATION_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities'
import { folderIdOfSelector, folderWorkspaceKey } from '../../shared/workspace-scope'
import { formatWorktreeShow } from '../workspace-format'
import { formatWorktreeShow } from './workspace-format'
import { printResult } from '../command-result-output'
import { getOptionalStringFlag, getOptionalStringFlagAllowingEmpty } from '../flags'
import { RuntimeClientError, type RuntimeClient, type RuntimeRpcSuccess } from '../runtime-client'
import { RuntimeClientError } from '../runtime/types'
import type { RuntimeClient } from '../runtime/client'
import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope'
import { getWorktreeReadFlags } from './worktree-unread-flag'
type Flags = Map<string, string | boolean>
@@ -18,8 +18,8 @@ const {
spawnMock: vi.fn()
}))
vi.mock('./runtime-client', async () => {
const { createRuntimeClientModuleMock } = await import('./index-test-harness.js')
vi.mock('../runtime/client', async () => {
const { createRuntimeClientModuleMock } = await import('../index-test-harness.js')
return createRuntimeClientModuleMock({
callMock,
runtimeClientConstructorMock,
@@ -28,19 +28,28 @@ vi.mock('./runtime-client', async () => {
})
})
vi.mock('../shared/remote-runtime/host-store/runtime-environment-store', () => ({
vi.mock('../runtime/metadata', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
getDefaultUserDataPath: getDefaultUserDataPathMock
}))
vi.mock('../runtime/launch', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
serveOrcaApp: serveOrcaAppMock
}))
vi.mock('../../shared/remote-runtime/host-store/runtime-environment-store', () => ({
listEnvironments: listEnvironmentsMock
}))
vi.mock('child_process', async () => {
const { createChildProcessModuleMock } = await import('./index-test-harness.js')
const { createChildProcessModuleMock } = await import('../index-test-harness.js')
return createChildProcessModuleMock(spawnMock)
})
import { main } from './index'
import { useWorktreeAwarenessEnvironment } from './index-test-harness'
import { RuntimeClientError } from './runtime/types'
import { buildWorktree, okFixture } from './test-fixtures'
import { main } from '../index'
import { useWorktreeAwarenessEnvironment } from '../index-test-harness'
import { RuntimeClientError } from '../runtime/types'
import { buildWorktree, okFixture } from '../test-fixtures'
const SAVED = [
{ id: 'srv-b', name: 'build-box' },
@@ -11,9 +11,9 @@ vi.mock('node:path', async (importOriginal) => {
import {
selectEnclosingRepoOnHost,
selectEnclosingWorktreeSelectionOnHost
} from './caller-host-worktree-selection'
import { buildWorktree } from './test-fixtures'
import { toSshExecutionHostId } from '../shared/execution-host'
} from '../workspace-selection/caller-host-worktree-selection'
import { buildWorktree } from '../test-fixtures'
import { toSshExecutionHostId } from '../../shared/execution-host'
const UPPER = String.raw`\\wsl.localhost\Ubuntu\home\Alice\App`
const LOWER = String.raw`\\wsl$\Ubuntu\home\alice\app`
@@ -1,10 +1,10 @@
import { isUnresolvedOwnerHostId, parseExecutionHostId } from '../shared/execution-host'
import { listEnvironments } from '../shared/remote-runtime/host-store/runtime-environment-store'
import { parseWorkspaceKey } from '../shared/workspace-scope'
import type { CrossStoreParentRef } from '../shared/worktree/lineage-types'
import { LOCAL_ENVIRONMENT } from './local-environment-selector'
import type { RuntimeClient } from './runtime-client'
import { quoteCliCommandArgument } from './shell-command-quote'
import { isUnresolvedOwnerHostId, parseExecutionHostId } from '../../shared/execution-host'
import { listEnvironments } from '../../shared/remote-runtime/host-store/runtime-environment-store'
import { parseWorkspaceKey } from '../../shared/workspace-scope'
import type { CrossStoreParentRef } from '../../shared/worktree/lineage-types'
import { LOCAL_ENVIRONMENT } from '../hosts/local-environment-selector'
import type { RuntimeClient } from '../runtime/client'
import { quoteCliCommandArgument } from '../shell-command-quote'
/** Which Orca answered: `local`, a saved environment, or a one-off pairing-code connection (id null). */
export type WorkspaceEnvironment = { id: string | null; name: string | null }
+103
View File
@@ -0,0 +1,103 @@
import { formatAddressLines, formatParentLine, type WorkspaceAnnotation } from './workspace-address'
import type {
RuntimeWorktreeListResult,
RuntimeWorktreePsResult,
RuntimeWorktreeRecord
} from '../../shared/runtime-worktree-contracts'
import {
formatListingHostScope,
type WithAnnotatedHostScope
} from '../hosts/omitted-host-scope-selectors'
import { formatWorktreePsTerminalFields } from './worktree-ps-terminal-verdict'
import { formatWorktreePsProgramStatus } from './worktree-ps-program-status'
type AnnotatedPsRow = RuntimeWorktreePsResult['worktrees'][number] & Partial<WorkspaceAnnotation>
export function formatWorktreePs(
result: WithAnnotatedHostScope<
Omit<RuntimeWorktreePsResult, 'worktrees'> & { worktrees: AnnotatedPsRow[] }
>
): string {
const scope = formatListingHostScope(result.hostScope)
if (result.worktrees.length === 0) {
return `No worktrees found.\n${scope}`
}
const body = result.worktrees
.map(
(worktree) =>
`${worktree.repo} ${worktree.branch} host=${worktree.hostId ?? 'unverifiable'} ${formatWorktreePsTerminalFields(worktree)} unread:${worktree.unread ? 'yes' : 'no'}${formatWorktreePsProgramStatus(worktree.agents)}\n${worktree.path}${formatWorktreePsLocation(worktree)}${worktree.preview ? `\npreview: ${worktree.preview}` : ''}`
)
.join('\n\n')
const bodyWithScope = `${body}\n\n${scope}`
return result.truncated
? `${bodyWithScope}\ntruncated: showing ${result.worktrees.length} of ${result.totalCount}`
: bodyWithScope
}
function formatWorktreePsLocation(worktree: AnnotatedPsRow): string {
const annotation = workspaceAnnotationOf(worktree)
return annotation
? `${formatParentLine(annotation)}${formatAddressLines(annotation)}`
: formatWorktreePsParent(worktree)
}
/** The parent line, in the sidebar's precedence: worktree, then folder workspace, then another machine. */
function formatWorktreePsParent(worktree: RuntimeWorktreePsResult['worktrees'][number]): string {
const parent =
worktree.parentWorktreeId ??
worktree.workspaceLineage?.parentWorkspaceKey ??
(worktree.crossStoreParent
? `${worktree.crossStoreParent.parent.workspaceKey} on another machine`
: null)
return parent ? `\nparent: ${parent}` : ''
}
export function formatWorktreeList(
result: WithAnnotatedHostScope<RuntimeWorktreeListResult>
): string {
const scope = formatListingHostScope(result.hostScope)
if (result.worktrees.length === 0) {
return `No worktrees found.\n${scope}`
}
const body = result.worktrees
.map((worktree) => {
const childCount = worktree.childWorktreeIds?.length ?? 0
return `${String(worktree.id)} ${String(worktree.branch)} host=${String(worktree.hostId ?? 'unverifiable')} ${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')
const bodyWithScope = `${body}\n\n${scope}`
return result.truncated
? `${bodyWithScope}\ntruncated: showing ${result.worktrees.length} of ${result.totalCount}`
: bodyWithScope
}
const ANNOTATION_KEYS = new Set(['environment', 'address', 'addressUnavailable', 'parent'])
function workspaceAnnotationOf(record: Partial<WorkspaceAnnotation>): WorkspaceAnnotation | null {
const { environment, address, addressUnavailable, parent } = record
return environment
? {
environment,
address: address ?? null,
parent: parent ?? null,
...(addressUnavailable ? { addressUnavailable } : {})
}
: null
}
export function formatWorktreeShow(result: {
worktree: RuntimeWorktreeRecord & Partial<WorkspaceAnnotation>
}): string {
const worktree = result.worktree
const annotation = workspaceAnnotationOf(worktree)
const fields = Object.entries(worktree)
.filter(([key]) => !annotation || !ANNOTATION_KEYS.has(key))
.map(
([key, value]) =>
`${key}: ${typeof value === 'object' ? JSON.stringify(value) : String(value)}`
)
.join('\n')
return annotation
? `${fields}${formatParentLine(annotation)}${formatAddressLines(annotation)}`
: fields
}
@@ -1,6 +1,6 @@
import type { CommandHandler } from '../dispatch'
import { printResult } from '../command-result-output'
import { getRequiredWorktreeSelector } from '../selectors'
import { getRequiredWorktreeSelector } from '../workspace-selection/workspace-selector'
import { folderIdOfSelector } from '../../shared/workspace-scope'
import { refuseFolderWorkspaceActivation } from './folder-workspace-mutations'
@@ -1,6 +1,9 @@
import type { RuntimeWorktreePsSummary, RuntimeWorktreeRecord } from '../../shared/runtime-types'
import type { RuntimeClient } from '../runtime-client'
import { addressableOfPsRow, addressableOfShowRecord, annotateListing } from '../workspace-address'
import type {
RuntimeWorktreePsSummary,
RuntimeWorktreeRecord
} from '../../shared/runtime-worktree-contracts'
import type { RuntimeClient } from '../runtime/client'
import { addressableOfPsRow, addressableOfShowRecord, annotateListing } from './workspace-address'
import { callerOrcaClient } from './worktree-parent-fields'
/** Annotates `worktree ps` rows; the returned function applies them to any rows aligned by index. */
@@ -9,7 +9,10 @@ import {
AGENT_LAUNCH_LOCAL_PRESENTATION_RUNTIME_CAPABILITY,
AGENT_LAUNCH_PROMPT_CARRY_RUNTIME_CAPABILITY
} from '../../shared/agent-launch/contracts/agent-launch-runtime-capability'
import type { RuntimeWorktreeCreateResult, RuntimeWorktreeRecord } from '../../shared/runtime-types'
import type {
RuntimeWorktreeCreateResult,
RuntimeWorktreeRecord
} from '../../shared/runtime-worktree-contracts'
import {
callAgentLaunch,
formatAgentLaunch,
@@ -18,9 +21,10 @@ import {
type CliAgentLaunch,
SURFACE_UNSUPPORTED_MESSAGE
} from '../agents/agent-launch-request'
import { formatWorktreeShow } from '../workspace-format'
import { formatWorktreeShow } from './workspace-format'
import { printResult } from '../command-result-output'
import { RuntimeClientError, type RuntimeClient } from '../runtime-client'
import { RuntimeClientError } from '../runtime/types'
import type { RuntimeClient } from '../runtime/client'
import { printLineageSummary } from './worktree-lineage-summary'
import { printHookWarning } from './worktree-removal-warnings'
import { withSetupDecisionRecovery } from './worktree-setup-decision-recovery'

Some files were not shown because too many files have changed in this diff Show More