From 8a55b78459cf0fa42d16189bf44d89601886da60 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 04:48:56 -0800 Subject: [PATCH] refactor(cli): group workspace, terminal, and host owners --- src/cli/agents/agent-launch.ts | 5 +- src/cli/automations/automation-destination.ts | 2 +- src/cli/automations/automations.ts | 7 +- src/cli/browser/browser-command-target.ts | 4 +- src/cli/browser/browser-extension.ts | 2 +- src/cli/browser/browser-interact.ts | 2 +- src/cli/browser/browser-tab.ts | 2 +- src/cli/cli-error.ts | 2 +- src/cli/computer/computer-command-target.ts | 34 +++ src/cli/computer/computer.ts | 2 +- src/cli/diagnostics/memory-snapshot-format.ts | 98 +++++++ src/cli/emulator/emulator-command-target.ts | 81 ++++++ src/cli/emulator/emulator.ts | 4 +- src/cli/files/file.ts | 5 +- src/cli/handler-group-manifest.ts | 16 +- src/cli/handlers/connector.ts | 2 +- src/cli/handlers/diagnostics.ts | 4 +- .../orchestration-caller-identity-cli.test.ts | 2 +- .../orchestration-check-identity.test.ts | 2 +- ...ration-federated-legacy-settlement.test.ts | 2 +- .../handlers/orchestration-gate-cli.test.ts | 38 +-- .../orchestration-legacy-read-only.test.ts | 2 +- .../orchestration-lifecycle-rejection.test.ts | 2 +- .../handlers/orchestration-worker-cli.test.ts | 2 +- src/cli/handlers/orchestration.test.ts | 2 +- .../handlers/orchestration/agent-view.test.ts | 2 +- .../concise-list-row-size.test.ts | 156 ----------- .../orchestration/terminal-identity.ts | 2 +- .../handlers/terminal-set-pane-title.test.ts | 79 ------ .../terminal-switch-paired-reveal.test.ts | 79 ------ src/cli/hosts/environment-format.ts | 28 ++ src/cli/{handlers => hosts}/environment.ts | 22 +- src/cli/{ => hosts}/execution-host-flag.ts | 27 +- src/cli/{ => hosts}/host-handler-groups.ts | 10 +- .../host-selector-alternatives.test.ts | 36 +-- .../{ => hosts}/host-selector-alternatives.ts | 8 +- .../index-environment-commands.test.ts | 23 +- .../{ => hosts}/local-environment-selector.ts | 12 +- .../managed-server-format.ts | 0 .../managed-server-reconnect.ts | 3 +- src/cli/{handlers => hosts}/managed-server.ts | 5 +- .../omitted-host-scope-selectors.ts | 10 +- src/cli/{handlers => hosts}/vm-env.ts | 0 src/cli/{handlers => hosts}/vm.ts | 8 +- src/cli/index.ts | 7 +- .../orchestration-session-caller-cli.test.ts | 2 +- ...ion-structured-session-no-identity.test.ts | 2 +- src/cli/{ => projects}/project-format.ts | 2 +- src/cli/{ => projects}/project-selector.ts | 10 +- src/cli/{handlers => projects}/project.ts | 13 +- src/cli/projects/repo-format.ts | 27 ++ src/cli/{ => projects}/repo-path-arguments.ts | 2 +- .../repo-visibility.test.ts | 20 +- src/cli/{handlers => projects}/repo.ts | 11 +- src/cli/runtime/transport.test.ts | 55 +--- src/cli/runtime/websocket-transport.test.ts | 2 +- src/cli/{handlers => server}/pair.ts | 0 .../serve-pairing-handler-groups.ts | 6 +- .../serve-reset-identity.test.ts | 0 .../serve-reset-identity.ts | 0 src/cli/{handlers => server}/serve-restore.ts | 0 .../serve-service-format.ts | 0 .../serve-service.test.ts | 0 src/cli/{handlers => server}/serve-service.ts | 0 .../codex-command-classification.test.ts | 0 .../codex-command-classification.ts | 0 .../index-terminal-commands.test.ts | 23 +- .../paired-terminal-desktop-reveal.ts | 10 +- .../{handlers => terminals}/terminal-close.ts | 9 +- .../terminal-daemon.ts | 2 +- src/cli/{ => terminals}/terminal-format.ts | 15 +- .../terminal-read-screen.test.ts | 25 +- src/cli/terminals/terminal-selector.ts | 22 ++ .../{handlers => terminals}/terminal-send.ts | 8 +- .../terminals/terminal-set-pane-title.test.ts | 26 ++ .../terminal-split.test.ts | 4 +- .../{handlers => terminals}/terminal.test.ts | 4 +- src/cli/{handlers => terminals}/terminal.ts | 20 +- src/cli/workspace-format.ts | 251 ------------------ src/cli/workspace-ports/ports.ts | 5 +- .../caller-cwd-containment.ts | 6 +- .../caller-folder-workspace.ts | 21 +- .../caller-host-worktree-selection.ts | 20 +- .../enclosing-workspace-catalog.ts | 16 +- .../enclosing-workspace-rule.test.ts | 12 +- .../folder-workspace-selector.ts | 8 +- .../workspace-catalog-row.ts | 6 +- .../workspace-selector.ts} | 131 +-------- .../worktree-selector-caller-host.test.ts | 0 .../worktree-selector-wsl-posix-path.test.ts | 8 +- .../wsl-caller-path-selector.ts | 12 +- .../folder-setup-support-warning.ts | 4 +- .../folder-workspace-mutations.ts | 10 +- .../index-worktree-parent-environment.test.ts | 25 +- .../index-worktree-wsl-selection.test.ts | 6 +- src/cli/{ => workspaces}/workspace-address.ts | 14 +- src/cli/workspaces/workspace-format.ts | 103 +++++++ .../worktree-activate.ts | 2 +- .../worktree-address-annotation.ts | 9 +- .../worktree-create-agent-launch.ts | 10 +- .../worktree-create-parent-selector.ts | 5 +- .../worktree-gitlab-link-context.ts | 7 +- .../worktree-gitlab-link.ts | 2 +- .../worktree-handler-groups.ts | 6 +- .../worktree-lineage-summary.ts | 5 +- .../worktree-linear-issue-link.ts | 2 +- .../worktree-link-flag-value.ts | 2 +- .../worktree-parent-environment.ts | 15 +- .../worktree-parent-fields.ts | 13 +- .../worktree-project-target.ts | 16 +- .../worktree-ps-program-status.ts | 4 +- .../worktree-ps-terminal-verdict.ts | 2 +- .../worktree-removal-current-refusal.ts | 7 +- .../worktree-removal-request.ts | 6 +- .../worktree-removal-warnings.ts | 0 .../worktree-review-link-flags.ts | 2 +- .../worktree-selector-recovery.ts | 6 +- .../worktree-setup-decision-recovery.ts | 0 .../worktree-unread-flag.ts | 2 +- src/cli/{handlers => workspaces}/worktree.ts | 16 +- tests/e2e/agent-launch-cli.unit.test.ts | 44 +-- 121 files changed, 824 insertions(+), 1178 deletions(-) create mode 100644 src/cli/computer/computer-command-target.ts create mode 100644 src/cli/diagnostics/memory-snapshot-format.ts create mode 100644 src/cli/emulator/emulator-command-target.ts delete mode 100644 src/cli/handlers/orchestration/concise-list-row-size.test.ts delete mode 100644 src/cli/handlers/terminal-set-pane-title.test.ts delete mode 100644 src/cli/handlers/terminal-switch-paired-reveal.test.ts create mode 100644 src/cli/hosts/environment-format.ts rename src/cli/{handlers => hosts}/environment.ts (94%) rename src/cli/{ => hosts}/execution-host-flag.ts (94%) rename src/cli/{ => hosts}/host-handler-groups.ts (66%) rename src/cli/{ => hosts}/host-selector-alternatives.test.ts (80%) rename src/cli/{ => hosts}/host-selector-alternatives.ts (95%) rename src/cli/{ => hosts}/index-environment-commands.test.ts (73%) rename src/cli/{ => hosts}/local-environment-selector.ts (89%) rename src/cli/{handlers => hosts}/managed-server-format.ts (100%) rename src/cli/{handlers => hosts}/managed-server-reconnect.ts (92%) rename src/cli/{handlers => hosts}/managed-server.ts (98%) rename src/cli/{ => hosts}/omitted-host-scope-selectors.ts (92%) rename src/cli/{handlers => hosts}/vm-env.ts (100%) rename src/cli/{handlers => hosts}/vm.ts (97%) rename src/cli/{ => projects}/project-format.ts (98%) rename src/cli/{ => projects}/project-selector.ts (92%) rename src/cli/{handlers => projects}/project.ts (96%) create mode 100644 src/cli/projects/repo-format.ts rename src/cli/{ => projects}/repo-path-arguments.ts (93%) rename src/cli/{handlers => projects}/repo-visibility.test.ts (70%) rename src/cli/{handlers => projects}/repo.ts (92%) rename src/cli/{handlers => server}/pair.ts (100%) rename src/cli/{ => server}/serve-pairing-handler-groups.ts (54%) rename src/cli/{handlers => server}/serve-reset-identity.test.ts (100%) rename src/cli/{handlers => server}/serve-reset-identity.ts (100%) rename src/cli/{handlers => server}/serve-restore.ts (100%) rename src/cli/{handlers => server}/serve-service-format.ts (100%) rename src/cli/{handlers => server}/serve-service.test.ts (100%) rename src/cli/{handlers => server}/serve-service.ts (100%) rename src/cli/{ => terminals}/codex-command-classification.test.ts (100%) rename src/cli/{ => terminals}/codex-command-classification.ts (100%) rename src/cli/{ => terminals}/index-terminal-commands.test.ts (83%) rename src/cli/{ => terminals}/paired-terminal-desktop-reveal.ts (71%) rename src/cli/{handlers => terminals}/terminal-close.ts (92%) rename src/cli/{handlers => terminals}/terminal-daemon.ts (98%) rename src/cli/{ => terminals}/terminal-format.ts (95%) rename src/cli/{ => terminals}/terminal-read-screen.test.ts (73%) create mode 100644 src/cli/terminals/terminal-selector.ts rename src/cli/{handlers => terminals}/terminal-send.ts (95%) create mode 100644 src/cli/terminals/terminal-set-pane-title.test.ts rename src/cli/{handlers => terminals}/terminal-split.test.ts (94%) rename src/cli/{handlers => terminals}/terminal.test.ts (97%) rename src/cli/{handlers => terminals}/terminal.ts (94%) delete mode 100644 src/cli/workspace-format.ts rename src/cli/{ => workspace-selection}/caller-cwd-containment.ts (93%) rename src/cli/{ => workspace-selection}/caller-folder-workspace.ts (87%) rename src/cli/{ => workspace-selection}/caller-host-worktree-selection.ts (94%) rename src/cli/{ => workspace-selection}/enclosing-workspace-catalog.ts (80%) rename src/cli/{ => workspace-selection}/enclosing-workspace-rule.test.ts (96%) rename src/cli/{ => workspace-selection}/folder-workspace-selector.ts (79%) rename src/cli/{ => workspace-selection}/workspace-catalog-row.ts (87%) rename src/cli/{selectors.ts => workspace-selection/workspace-selector.ts} (57%) rename src/cli/{ => workspace-selection}/worktree-selector-caller-host.test.ts (100%) rename src/cli/{ => workspace-selection}/worktree-selector-wsl-posix-path.test.ts (89%) rename src/cli/{ => workspace-selection}/wsl-caller-path-selector.ts (85%) rename src/cli/{handlers => workspaces}/folder-setup-support-warning.ts (92%) rename src/cli/{handlers => workspaces}/folder-workspace-mutations.ts (94%) rename src/cli/{ => workspaces}/index-worktree-parent-environment.test.ts (91%) rename src/cli/{ => workspaces}/index-worktree-wsl-selection.test.ts (90%) rename src/cli/{ => workspaces}/workspace-address.ts (95%) create mode 100644 src/cli/workspaces/workspace-format.ts rename src/cli/{handlers => workspaces}/worktree-activate.ts (92%) rename src/cli/{handlers => workspaces}/worktree-address-annotation.ts (84%) rename src/cli/{handlers => workspaces}/worktree-create-agent-launch.ts (94%) rename src/cli/{handlers => workspaces}/worktree-create-parent-selector.ts (93%) rename src/cli/{handlers => workspaces}/worktree-gitlab-link-context.ts (91%) rename src/cli/{handlers => workspaces}/worktree-gitlab-link.ts (97%) rename src/cli/{ => workspaces}/worktree-handler-groups.ts (59%) rename src/cli/{handlers => workspaces}/worktree-lineage-summary.ts (95%) rename src/cli/{handlers => workspaces}/worktree-linear-issue-link.ts (95%) rename src/cli/{handlers => workspaces}/worktree-link-flag-value.ts (92%) rename src/cli/{handlers => workspaces}/worktree-parent-environment.ts (94%) rename src/cli/{handlers => workspaces}/worktree-parent-fields.ts (94%) rename src/cli/{ => workspaces}/worktree-project-target.ts (93%) rename src/cli/{ => workspaces}/worktree-ps-program-status.ts (83%) rename src/cli/{ => workspaces}/worktree-ps-terminal-verdict.ts (94%) rename src/cli/{handlers => workspaces}/worktree-removal-current-refusal.ts (90%) rename src/cli/{handlers => workspaces}/worktree-removal-request.ts (92%) rename src/cli/{handlers => workspaces}/worktree-removal-warnings.ts (100%) rename src/cli/{handlers => workspaces}/worktree-review-link-flags.ts (96%) rename src/cli/{ => workspaces}/worktree-selector-recovery.ts (94%) rename src/cli/{handlers => workspaces}/worktree-setup-decision-recovery.ts (100%) rename src/cli/{handlers => workspaces}/worktree-unread-flag.ts (93%) rename src/cli/{handlers => workspaces}/worktree.ts (96%) diff --git a/src/cli/agents/agent-launch.ts b/src/cli/agents/agent-launch.ts index 0e661f3d894..ec99eeb089c 100644 --- a/src/cli/agents/agent-launch.ts +++ b/src/cli/agents/agent-launch.ts @@ -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 = { 'agent launch': async ({ flags, client, cwd, json, rawArgs }) => { diff --git a/src/cli/automations/automation-destination.ts b/src/cli/automations/automation-destination.ts index 1178b63cc45..6765a7b2e36 100644 --- a/src/cli/automations/automation-destination.ts +++ b/src/cli/automations/automation-destination.ts @@ -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 } diff --git a/src/cli/automations/automations.ts b/src/cli/automations/automations.ts index 9291646cd45..bc4a714e397 100644 --- a/src/cli/automations/automations.ts +++ b/src/cli/automations/automations.ts @@ -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, diff --git a/src/cli/browser/browser-command-target.ts b/src/cli/browser/browser-command-target.ts index 5f3cdeceb45..9f9faef38ad 100644 --- a/src/cli/browser/browser-command-target.ts +++ b/src/cli/browser/browser-command-target.ts @@ -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 diff --git a/src/cli/browser/browser-extension.ts b/src/cli/browser/browser-extension.ts index 3ea39ad1b05..1bd892c8eaf 100644 --- a/src/cli/browser/browser-extension.ts +++ b/src/cli/browser/browser-extension.ts @@ -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 = { 'extension list': async ({ flags, client, json }) => { diff --git a/src/cli/browser/browser-interact.ts b/src/cli/browser/browser-interact.ts index adb552be8fd..f156b0a01dc 100644 --- a/src/cli/browser/browser-interact.ts +++ b/src/cli/browser/browser-interact.ts @@ -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, diff --git a/src/cli/browser/browser-tab.ts b/src/cli/browser/browser-tab.ts index 4b8b9f89fb8..06d79c4821b 100644 --- a/src/cli/browser/browser-tab.ts +++ b/src/cli/browser/browser-tab.ts @@ -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 = { diff --git a/src/cli/cli-error.ts b/src/cli/cli-error.ts index 3ac5d47b31f..be20b39a02f 100644 --- a/src/cli/cli-error.ts +++ b/src/cli/cli-error.ts @@ -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' diff --git a/src/cli/computer/computer-command-target.ts b/src/cli/computer/computer-command-target.ts new file mode 100644 index 00000000000..96cca961ee0 --- /dev/null +++ b/src/cli/computer/computer-command-target.ts @@ -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, + cwd: string, + client: RuntimeClient +): Promise { + 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) + } +} diff --git a/src/cli/computer/computer.ts b/src/cli/computer/computer.ts index 0240aa65343..30dd04b8f7f 100644 --- a/src/cli/computer/computer.ts +++ b/src/cli/computer/computer.ts @@ -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, diff --git a/src/cli/diagnostics/memory-snapshot-format.ts b/src/cli/diagnostics/memory-snapshot-format.ts new file mode 100644 index 00000000000..ef7516b2228 --- /dev/null +++ b/src/cli/diagnostics/memory-snapshot-format.ts @@ -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]}` +} diff --git a/src/cli/emulator/emulator-command-target.ts b/src/cli/emulator/emulator-command-target.ts new file mode 100644 index 00000000000..6f5a28b6935 --- /dev/null +++ b/src/cli/emulator/emulator-command-target.ts @@ -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, + cwd: string, + client: RuntimeClient +): Promise { + 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, + cwd: string, + client: RuntimeClient +): Promise { + 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 } +} diff --git a/src/cli/emulator/emulator.ts b/src/cli/emulator/emulator.ts index e6613644921..8619fecfef8 100644 --- a/src/cli/emulator/emulator.ts +++ b/src/cli/emulator/emulator.ts @@ -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' diff --git a/src/cli/files/file.ts b/src/cli/files/file.ts index a3c77a52438..40308b481a2 100644 --- a/src/cli/files/file.ts +++ b/src/cli/files/file.ts @@ -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' diff --git a/src/cli/handler-group-manifest.ts b/src/cli/handler-group-manifest.ts index 27a788fc857..7a72401588c 100644 --- a/src/cli/handler-group-manifest.ts +++ b/src/cli/handler-group-manifest.ts @@ -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, { diff --git a/src/cli/handlers/connector.ts b/src/cli/handlers/connector.ts index 9ae2109977c..d87fdfbd58b 100644 --- a/src/cli/handlers/connector.ts +++ b/src/cli/handlers/connector.ts @@ -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 } diff --git a/src/cli/handlers/diagnostics.ts b/src/cli/handlers/diagnostics.ts index 8bb9841442f..1bfe5ab1ac9 100644 --- a/src/cli/handlers/diagnostics.ts +++ b/src/cli/handlers/diagnostics.ts @@ -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 = { 'diagnostics memory': async ({ client, json }) => { diff --git a/src/cli/handlers/orchestration-caller-identity-cli.test.ts b/src/cli/handlers/orchestration-caller-identity-cli.test.ts index 776204c17bf..764fdb98a00 100644 --- a/src/cli/handlers/orchestration-caller-identity-cli.test.ts +++ b/src/cli/handlers/orchestration-caller-identity-cli.test.ts @@ -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' diff --git a/src/cli/handlers/orchestration-check-identity.test.ts b/src/cli/handlers/orchestration-check-identity.test.ts index 11ffec64684..98df085d5fa 100644 --- a/src/cli/handlers/orchestration-check-identity.test.ts +++ b/src/cli/handlers/orchestration-check-identity.test.ts @@ -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' diff --git a/src/cli/handlers/orchestration-federated-legacy-settlement.test.ts b/src/cli/handlers/orchestration-federated-legacy-settlement.test.ts index ec1360d2e17..b386ccb1691 100644 --- a/src/cli/handlers/orchestration-federated-legacy-settlement.test.ts +++ b/src/cli/handlers/orchestration-federated-legacy-settlement.test.ts @@ -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' diff --git a/src/cli/handlers/orchestration-gate-cli.test.ts b/src/cli/handlers/orchestration-gate-cli.test.ts index f2825d9123c..90a47131c42 100644 --- a/src/cli/handlers/orchestration-gate-cli.test.ts +++ b/src/cli/handlers/orchestration-gate-cli.test.ts @@ -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>()), + getDefaultUserDataPath: vi.fn(() => '/tmp/orca-user-data') +})) + +vi.mock('../runtime/launch', async (importOriginal) => ({ + ...(await importOriginal>()), + serveOrcaApp: vi.fn() +})) +vi.mock('../terminals/terminal-selector', async (importOriginal) => ({ ...(await importOriginal>()), getTerminalHandle: getTerminalHandleMock })) @@ -75,31 +84,6 @@ describe('orchestration gate commands carry caller identity', () => { const paramsFor = (method: string): Record => callMock.mock.calls.find((call) => call[0] === method)?.[1] as Record - 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') diff --git a/src/cli/handlers/orchestration-legacy-read-only.test.ts b/src/cli/handlers/orchestration-legacy-read-only.test.ts index fc9738bea40..bf2d528ecd5 100644 --- a/src/cli/handlers/orchestration-legacy-read-only.test.ts +++ b/src/cli/handlers/orchestration-legacy-read-only.test.ts @@ -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' diff --git a/src/cli/handlers/orchestration-lifecycle-rejection.test.ts b/src/cli/handlers/orchestration-lifecycle-rejection.test.ts index 6efb7d2cc50..d9e54eada37 100644 --- a/src/cli/handlers/orchestration-lifecycle-rejection.test.ts +++ b/src/cli/handlers/orchestration-lifecycle-rejection.test.ts @@ -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' diff --git a/src/cli/handlers/orchestration-worker-cli.test.ts b/src/cli/handlers/orchestration-worker-cli.test.ts index b39b4d5985f..f44ce4bc8cf 100644 --- a/src/cli/handlers/orchestration-worker-cli.test.ts +++ b/src/cli/handlers/orchestration-worker-cli.test.ts @@ -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' diff --git a/src/cli/handlers/orchestration.test.ts b/src/cli/handlers/orchestration.test.ts index 4f95228896f..65a622758db 100644 --- a/src/cli/handlers/orchestration.test.ts +++ b/src/cli/handlers/orchestration.test.ts @@ -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' diff --git a/src/cli/handlers/orchestration/agent-view.test.ts b/src/cli/handlers/orchestration/agent-view.test.ts index 25d5e019b04..4aca1935831 100644 --- a/src/cli/handlers/orchestration/agent-view.test.ts +++ b/src/cli/handlers/orchestration/agent-view.test.ts @@ -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' diff --git a/src/cli/handlers/orchestration/concise-list-row-size.test.ts b/src/cli/handlers/orchestration/concise-list-row-size.test.ts deleted file mode 100644 index 4774d8d6c39..00000000000 --- a/src/cli/handlers/orchestration/concise-list-row-size.test.ts +++ /dev/null @@ -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 } = 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) - } - } - ) -}) diff --git a/src/cli/handlers/orchestration/terminal-identity.ts b/src/cli/handlers/orchestration/terminal-identity.ts index 9df06f688c6..d219b785356 100644 --- a/src/cli/handlers/orchestration/terminal-identity.ts +++ b/src/cli/handlers/orchestration/terminal-identity.ts @@ -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, diff --git a/src/cli/handlers/terminal-set-pane-title.test.ts b/src/cli/handlers/terminal-set-pane-title.test.ts deleted file mode 100644 index 9dfd9086d8d..00000000000 --- a/src/cli/handlers/terminal-set-pane-title.test.ts +++ /dev/null @@ -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) - }) -}) diff --git a/src/cli/handlers/terminal-switch-paired-reveal.test.ts b/src/cli/handlers/terminal-switch-paired-reveal.test.ts deleted file mode 100644 index fb148960a4e..00000000000 --- a/src/cli/handlers/terminal-switch-paired-reveal.test.ts +++ /dev/null @@ -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 } } }) - }) -}) diff --git a/src/cli/hosts/environment-format.ts b/src/cli/hosts/environment-format.ts new file mode 100644 index 00000000000..da273b16ff7 --- /dev/null +++ b/src/cli/hosts/environment-format.ts @@ -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') +} diff --git a/src/cli/handlers/environment.ts b/src/cli/hosts/environment.ts similarity index 94% rename from src/cli/handlers/environment.ts rename to src/cli/hosts/environment.ts index cc426c0c060..11480b5b926 100644 --- a/src/cli/handlers/environment.ts +++ b/src/cli/hosts/environment.ts @@ -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 = { diff --git a/src/cli/execution-host-flag.ts b/src/cli/hosts/execution-host-flag.ts similarity index 94% rename from src/cli/execution-host-flag.ts rename to src/cli/hosts/execution-host-flag.ts index 3720e25fba1..b71ee5656c0 100644 --- a/src/cli/execution-host-flag.ts +++ b/src/cli/hosts/execution-host-flag.ts @@ -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 ): Promise { 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, diff --git a/src/cli/host-handler-groups.ts b/src/cli/hosts/host-handler-groups.ts similarity index 66% rename from src/cli/host-handler-groups.ts rename to src/cli/hosts/host-handler-groups.ts index ed1ef7506b0..70a31c6ef7a 100644 --- a/src/cli/host-handler-groups.ts +++ b/src/cli/hosts/host-handler-groups.ts @@ -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 } ] diff --git a/src/cli/host-selector-alternatives.test.ts b/src/cli/hosts/host-selector-alternatives.test.ts similarity index 80% rename from src/cli/host-selector-alternatives.test.ts rename to src/cli/hosts/host-selector-alternatives.test.ts index 3a5ef8c1d2f..e0cdceca09d 100644 --- a/src/cli/host-selector-alternatives.test.ts +++ b/src/cli/hosts/host-selector-alternatives.test.ts @@ -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')) diff --git a/src/cli/host-selector-alternatives.ts b/src/cli/hosts/host-selector-alternatives.ts similarity index 95% rename from src/cli/host-selector-alternatives.ts rename to src/cli/hosts/host-selector-alternatives.ts index 9e4db8d4508..c6e2636dc42 100644 --- a/src/cli/host-selector-alternatives.ts +++ b/src/cli/hosts/host-selector-alternatives.ts @@ -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( diff --git a/src/cli/index-environment-commands.test.ts b/src/cli/hosts/index-environment-commands.test.ts similarity index 73% rename from src/cli/index-environment-commands.test.ts rename to src/cli/hosts/index-environment-commands.test.ts index c2282c520d5..ab0c59c4309 100644 --- a/src/cli/index-environment-commands.test.ts +++ b/src/cli/hosts/index-environment-commands.test.ts @@ -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>()), + getDefaultUserDataPath: getDefaultUserDataPathMock +})) + +vi.mock('../runtime/launch', async (importOriginal) => ({ + ...(await importOriginal>()), + 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({ diff --git a/src/cli/local-environment-selector.ts b/src/cli/hosts/local-environment-selector.ts similarity index 89% rename from src/cli/local-environment-selector.ts rename to src/cli/hosts/local-environment-selector.ts index 44849c1e87d..a85d88f5e17 100644 --- a/src/cli/local-environment-selector.ts +++ b/src/cli/hosts/local-environment-selector.ts @@ -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) diff --git a/src/cli/handlers/managed-server-format.ts b/src/cli/hosts/managed-server-format.ts similarity index 100% rename from src/cli/handlers/managed-server-format.ts rename to src/cli/hosts/managed-server-format.ts diff --git a/src/cli/handlers/managed-server-reconnect.ts b/src/cli/hosts/managed-server-reconnect.ts similarity index 92% rename from src/cli/handlers/managed-server-reconnect.ts rename to src/cli/hosts/managed-server-reconnect.ts index 4007783aa3d..e100fa69834 100644 --- a/src/cli/handlers/managed-server-reconnect.ts +++ b/src/cli/hosts/managed-server-reconnect.ts @@ -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 diff --git a/src/cli/handlers/managed-server.ts b/src/cli/hosts/managed-server.ts similarity index 98% rename from src/cli/handlers/managed-server.ts rename to src/cli/hosts/managed-server.ts index 9be9aea327a..2626133b1b3 100644 --- a/src/cli/handlers/managed-server.ts +++ b/src/cli/hosts/managed-server.ts @@ -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' diff --git a/src/cli/omitted-host-scope-selectors.ts b/src/cli/hosts/omitted-host-scope-selectors.ts similarity index 92% rename from src/cli/omitted-host-scope-selectors.ts rename to src/cli/hosts/omitted-host-scope-selectors.ts index 2982a73268a..3e87e256cb3 100644 --- a/src/cli/omitted-host-scope-selectors.ts +++ b/src/cli/hosts/omitted-host-scope-selectors.ts @@ -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, diff --git a/src/cli/handlers/vm-env.ts b/src/cli/hosts/vm-env.ts similarity index 100% rename from src/cli/handlers/vm-env.ts rename to src/cli/hosts/vm-env.ts diff --git a/src/cli/handlers/vm.ts b/src/cli/hosts/vm.ts similarity index 97% rename from src/cli/handlers/vm.ts rename to src/cli/hosts/vm.ts index 7419fcbce95..c904747e9b2 100644 --- a/src/cli/handlers/vm.ts +++ b/src/cli/hosts/vm.ts @@ -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 { diff --git a/src/cli/index.ts b/src/cli/index.ts index 5df8d8c6f5d..5d5f94686ec 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -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)) diff --git a/src/cli/orchestration-session-caller-cli.test.ts b/src/cli/orchestration-session-caller-cli.test.ts index 49372109b01..862c8fb1c81 100644 --- a/src/cli/orchestration-session-caller-cli.test.ts +++ b/src/cli/orchestration-session-caller-cli.test.ts @@ -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' diff --git a/src/cli/orchestration-structured-session-no-identity.test.ts b/src/cli/orchestration-structured-session-no-identity.test.ts index cc0235f0e32..ecca72674e7 100644 --- a/src/cli/orchestration-structured-session-no-identity.test.ts +++ b/src/cli/orchestration-structured-session-no-identity.test.ts @@ -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' diff --git a/src/cli/project-format.ts b/src/cli/projects/project-format.ts similarity index 98% rename from src/cli/project-format.ts rename to src/cli/projects/project-format.ts index 82265411146..71eb0088675 100644 --- a/src/cli/project-format.ts +++ b/src/cli/projects/project-format.ts @@ -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) { diff --git a/src/cli/project-selector.ts b/src/cli/projects/project-selector.ts similarity index 92% rename from src/cli/project-selector.ts rename to src/cli/projects/project-selector.ts index 9f5602c2dd9..ff73e93bb6a 100644 --- a/src/cli/project-selector.ts +++ b/src/cli/projects/project-selector.ts @@ -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) diff --git a/src/cli/handlers/project.ts b/src/cli/projects/project.ts similarity index 96% rename from src/cli/handlers/project.ts rename to src/cli/projects/project.ts index 151e085047b..d54fe415c84 100644 --- a/src/cli/handlers/project.ts +++ b/src/cli/projects/project.ts @@ -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( client: HandlerContext['client'], diff --git a/src/cli/projects/repo-format.ts b/src/cli/projects/repo-format.ts new file mode 100644 index 00000000000..853d0cee119 --- /dev/null +++ b/src/cli/projects/repo-format.ts @@ -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 { + 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') +} diff --git a/src/cli/repo-path-arguments.ts b/src/cli/projects/repo-path-arguments.ts similarity index 93% rename from src/cli/repo-path-arguments.ts rename to src/cli/projects/repo-path-arguments.ts index f574eb68179..fed8af7b2ae 100644 --- a/src/cli/repo-path-arguments.ts +++ b/src/cli/projects/repo-path-arguments.ts @@ -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 ( diff --git a/src/cli/handlers/repo-visibility.test.ts b/src/cli/projects/repo-visibility.test.ts similarity index 70% rename from src/cli/handlers/repo-visibility.test.ts rename to src/cli/projects/repo-visibility.test.ts index 0f4bdfc7287..f1fa5ec2610 100644 --- a/src/cli/handlers/repo-visibility.test.ts +++ b/src/cli/projects/repo-visibility.test.ts @@ -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' }, { diff --git a/src/cli/handlers/repo.ts b/src/cli/projects/repo.ts similarity index 92% rename from src/cli/handlers/repo.ts rename to src/cli/projects/repo.ts index 8d4dff111af..64da561fb7b 100644 --- a/src/cli/handlers/repo.ts +++ b/src/cli/projects/repo.ts @@ -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 = { 'repo list': async ({ client, json }) => { diff --git a/src/cli/runtime/transport.test.ts b/src/cli/runtime/transport.test.ts index 31871e1b96f..72b84cfe1e6 100644 --- a/src/cli/runtime/transport.test.ts +++ b/src/cli/runtime/transport.test.ts @@ -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() @@ -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((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) diff --git a/src/cli/runtime/websocket-transport.test.ts b/src/cli/runtime/websocket-transport.test.ts index 355f9ef0101..a0cfb912efa 100644 --- a/src/cli/runtime/websocket-transport.test.ts +++ b/src/cli/runtime/websocket-transport.test.ts @@ -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 { diff --git a/src/cli/handlers/pair.ts b/src/cli/server/pair.ts similarity index 100% rename from src/cli/handlers/pair.ts rename to src/cli/server/pair.ts diff --git a/src/cli/serve-pairing-handler-groups.ts b/src/cli/server/serve-pairing-handler-groups.ts similarity index 54% rename from src/cli/serve-pairing-handler-groups.ts rename to src/cli/server/serve-pairing-handler-groups.ts index 4c1817c57bc..f580c9a0313 100644 --- a/src/cli/serve-pairing-handler-groups.ts +++ b/src/cli/server/serve-pairing-handler-groups.ts @@ -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 } ] diff --git a/src/cli/handlers/serve-reset-identity.test.ts b/src/cli/server/serve-reset-identity.test.ts similarity index 100% rename from src/cli/handlers/serve-reset-identity.test.ts rename to src/cli/server/serve-reset-identity.test.ts diff --git a/src/cli/handlers/serve-reset-identity.ts b/src/cli/server/serve-reset-identity.ts similarity index 100% rename from src/cli/handlers/serve-reset-identity.ts rename to src/cli/server/serve-reset-identity.ts diff --git a/src/cli/handlers/serve-restore.ts b/src/cli/server/serve-restore.ts similarity index 100% rename from src/cli/handlers/serve-restore.ts rename to src/cli/server/serve-restore.ts diff --git a/src/cli/handlers/serve-service-format.ts b/src/cli/server/serve-service-format.ts similarity index 100% rename from src/cli/handlers/serve-service-format.ts rename to src/cli/server/serve-service-format.ts diff --git a/src/cli/handlers/serve-service.test.ts b/src/cli/server/serve-service.test.ts similarity index 100% rename from src/cli/handlers/serve-service.test.ts rename to src/cli/server/serve-service.test.ts diff --git a/src/cli/handlers/serve-service.ts b/src/cli/server/serve-service.ts similarity index 100% rename from src/cli/handlers/serve-service.ts rename to src/cli/server/serve-service.ts diff --git a/src/cli/codex-command-classification.test.ts b/src/cli/terminals/codex-command-classification.test.ts similarity index 100% rename from src/cli/codex-command-classification.test.ts rename to src/cli/terminals/codex-command-classification.test.ts diff --git a/src/cli/codex-command-classification.ts b/src/cli/terminals/codex-command-classification.ts similarity index 100% rename from src/cli/codex-command-classification.ts rename to src/cli/terminals/codex-command-classification.ts diff --git a/src/cli/index-terminal-commands.test.ts b/src/cli/terminals/index-terminal-commands.test.ts similarity index 83% rename from src/cli/index-terminal-commands.test.ts rename to src/cli/terminals/index-terminal-commands.test.ts index 6654ab50182..17352a5c95d 100644 --- a/src/cli/index-terminal-commands.test.ts +++ b/src/cli/terminals/index-terminal-commands.test.ts @@ -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>()), + getDefaultUserDataPath: getDefaultUserDataPathMock +})) + +vi.mock('../runtime/launch', async (importOriginal) => ({ + ...(await importOriginal>()), + 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({ diff --git a/src/cli/paired-terminal-desktop-reveal.ts b/src/cli/terminals/paired-terminal-desktop-reveal.ts similarity index 71% rename from src/cli/paired-terminal-desktop-reveal.ts rename to src/cli/terminals/paired-terminal-desktop-reveal.ts index 15ac101497d..d33269ec805 100644 --- a/src/cli/paired-terminal-desktop-reveal.ts +++ b/src/cli/terminals/paired-terminal-desktop-reveal.ts @@ -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( diff --git a/src/cli/handlers/terminal-close.ts b/src/cli/terminals/terminal-close.ts similarity index 92% rename from src/cli/handlers/terminal-close.ts rename to src/cli/terminals/terminal-close.ts index bb4c005b926..0ef3a486843 100644 --- a/src/cli/handlers/terminal-close.ts +++ b/src/cli/terminals/terminal-close.ts @@ -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. */ diff --git a/src/cli/handlers/terminal-daemon.ts b/src/cli/terminals/terminal-daemon.ts similarity index 98% rename from src/cli/handlers/terminal-daemon.ts rename to src/cli/terminals/terminal-daemon.ts index b3f367b1db1..49c5dca4158 100644 --- a/src/cli/handlers/terminal-daemon.ts +++ b/src/cli/terminals/terminal-daemon.ts @@ -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 diff --git a/src/cli/terminal-format.ts b/src/cli/terminals/terminal-format.ts similarity index 95% rename from src/cli/terminal-format.ts rename to src/cli/terminals/terminal-format.ts index 16924796c2e..37860e107ce 100644 --- a/src/cli/terminal-format.ts +++ b/src/cli/terminals/terminal-format.ts @@ -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 diff --git a/src/cli/terminal-read-screen.test.ts b/src/cli/terminals/terminal-read-screen.test.ts similarity index 73% rename from src/cli/terminal-read-screen.test.ts rename to src/cli/terminals/terminal-read-screen.test.ts index a6c96594f58..cbe5b5a1c47 100644 --- a/src/cli/terminal-read-screen.test.ts +++ b/src/cli/terminals/terminal-read-screen.test.ts @@ -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>()), + getDefaultUserDataPath: getDefaultUserDataPathMock +})) + +vi.mock('../runtime/launch', async (importOriginal) => ({ + ...(await importOriginal>()), + 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 = {}) { return okFixture('req_terminal_read', { diff --git a/src/cli/terminals/terminal-selector.ts b/src/cli/terminals/terminal-selector.ts new file mode 100644 index 00000000000..3b7fa8617b5 --- /dev/null +++ b/src/cli/terminals/terminal-selector.ts @@ -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, + cwd: string, + client: RuntimeClient, + options: { requireUnambiguous?: boolean; purpose?: WorkspaceSelectionPurpose } = {} +): Promise { + 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 +} diff --git a/src/cli/handlers/terminal-send.ts b/src/cli/terminals/terminal-send.ts similarity index 95% rename from src/cli/handlers/terminal-send.ts rename to src/cli/terminals/terminal-send.ts index 36f0db3739d..b082802b5ea 100644 --- a/src/cli/handlers/terminal-send.ts +++ b/src/cli/terminals/terminal-send.ts @@ -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[] } diff --git a/src/cli/terminals/terminal-set-pane-title.test.ts b/src/cli/terminals/terminal-set-pane-title.test.ts new file mode 100644 index 00000000000..b6618c4bab5 --- /dev/null +++ b/src/cli/terminals/terminal-set-pane-title.test.ts @@ -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() + } + ) +}) diff --git a/src/cli/handlers/terminal-split.test.ts b/src/cli/terminals/terminal-split.test.ts similarity index 94% rename from src/cli/handlers/terminal-split.test.ts rename to src/cli/terminals/terminal-split.test.ts index 55baac8441b..3c4033a27d6 100644 --- a/src/cli/handlers/terminal-split.test.ts +++ b/src/cli/terminals/terminal-split.test.ts @@ -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' diff --git a/src/cli/handlers/terminal.test.ts b/src/cli/terminals/terminal.test.ts similarity index 97% rename from src/cli/handlers/terminal.test.ts rename to src/cli/terminals/terminal.test.ts index 9b1c51d56a2..4be9422d0e2 100644 --- a/src/cli/handlers/terminal.test.ts +++ b/src/cli/terminals/terminal.test.ts @@ -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' diff --git a/src/cli/handlers/terminal.ts b/src/cli/terminals/terminal.ts similarity index 94% rename from src/cli/handlers/terminal.ts rename to src/cli/terminals/terminal.ts index 80c84fb75ac..09367ab9dcb 100644 --- a/src/cli/handlers/terminal.ts +++ b/src/cli/terminals/terminal.ts @@ -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' diff --git a/src/cli/workspace-format.ts b/src/cli/workspace-format.ts deleted file mode 100644 index 77a26c4fedf..00000000000 --- a/src/cli/workspace-format.ts +++ /dev/null @@ -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 - -export function formatWorktreePs( - result: WithAnnotatedHostScope< - Omit & { 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 { - 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 -): 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 | 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 -}): 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 -} diff --git a/src/cli/workspace-ports/ports.ts b/src/cli/workspace-ports/ports.ts index cda0773fa69..21f99099f3e 100644 --- a/src/cli/workspace-ports/ports.ts +++ b/src/cli/workspace-ports/ports.ts @@ -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 } diff --git a/src/cli/caller-cwd-containment.ts b/src/cli/workspace-selection/caller-cwd-containment.ts similarity index 93% rename from src/cli/caller-cwd-containment.ts rename to src/cli/workspace-selection/caller-cwd-containment.ts index 861d162d62d..d3c0fcd148d 100644 --- a/src/cli/caller-cwd-containment.ts +++ b/src/cli/workspace-selection/caller-cwd-containment.ts @@ -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() diff --git a/src/cli/caller-folder-workspace.ts b/src/cli/workspace-selection/caller-folder-workspace.ts similarity index 87% rename from src/cli/caller-folder-workspace.ts rename to src/cli/workspace-selection/caller-folder-workspace.ts index 7a5688f4500..0f4efa80738 100644 --- a/src/cli/caller-folder-workspace.ts +++ b/src/cli/workspace-selection/caller-folder-workspace.ts @@ -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 diff --git a/src/cli/caller-host-worktree-selection.ts b/src/cli/workspace-selection/caller-host-worktree-selection.ts similarity index 94% rename from src/cli/caller-host-worktree-selection.ts rename to src/cli/workspace-selection/caller-host-worktree-selection.ts index 2e390975e92..9a63b33ef7c 100644 --- a/src/cli/caller-host-worktree-selection.ts +++ b/src/cli/workspace-selection/caller-host-worktree-selection.ts @@ -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:`, beside repo-backed rows. */ function isFolderRow(row: CatalogRow): boolean { return parseWorkspaceKey(row.id)?.type === 'folder' diff --git a/src/cli/enclosing-workspace-catalog.ts b/src/cli/workspace-selection/enclosing-workspace-catalog.ts similarity index 80% rename from src/cli/enclosing-workspace-catalog.ts rename to src/cli/workspace-selection/enclosing-workspace-catalog.ts index 36e6b2afa17..fb57b7b273b 100644 --- a/src/cli/enclosing-workspace-catalog.ts +++ b/src/cli/workspace-selection/enclosing-workspace-catalog.ts @@ -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(read: Promise): Promise { diff --git a/src/cli/enclosing-workspace-rule.test.ts b/src/cli/workspace-selection/enclosing-workspace-rule.test.ts similarity index 96% rename from src/cli/enclosing-workspace-rule.test.ts rename to src/cli/workspace-selection/enclosing-workspace-rule.test.ts index 8b011029ca6..6776cbc5652 100644 --- a/src/cli/enclosing-workspace-rule.test.ts +++ b/src/cli/workspace-selection/enclosing-workspace-rule.test.ts @@ -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 } diff --git a/src/cli/folder-workspace-selector.ts b/src/cli/workspace-selection/folder-workspace-selector.ts similarity index 79% rename from src/cli/folder-workspace-selector.ts rename to src/cli/workspace-selection/folder-workspace-selector.ts index cf0828a5579..10cb6df731c 100644 --- a/src/cli/folder-workspace-selector.ts +++ b/src/cli/workspace-selection/folder-workspace-selector.ts @@ -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:') diff --git a/src/cli/workspace-catalog-row.ts b/src/cli/workspace-selection/workspace-catalog-row.ts similarity index 87% rename from src/cli/workspace-catalog-row.ts rename to src/cli/workspace-selection/workspace-catalog-row.ts index 11b2e5e834f..a75915139fe 100644 --- a/src/cli/workspace-catalog-row.ts +++ b/src/cli/workspace-selection/workspace-catalog-row.ts @@ -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:`. */ export type CatalogRow = Pick & { diff --git a/src/cli/selectors.ts b/src/cli/workspace-selection/workspace-selector.ts similarity index 57% rename from src/cli/selectors.ts rename to src/cli/workspace-selection/workspace-selector.ts index 1a258e67ab2..ce65d1b5152 100644 --- a/src/cli/selectors.ts +++ b/src/cli/workspace-selection/workspace-selector.ts @@ -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, @@ -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, - cwd: string, - client: RuntimeClient, - options: { requireUnambiguous?: boolean; purpose?: WorkspaceSelectionPurpose } = {} -): Promise { - 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, - cwd: string, - client: RuntimeClient -): Promise { - 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, - cwd: string, - client: RuntimeClient -): Promise { - 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, - cwd: string, - client: RuntimeClient -): Promise { - 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 } -} diff --git a/src/cli/worktree-selector-caller-host.test.ts b/src/cli/workspace-selection/worktree-selector-caller-host.test.ts similarity index 100% rename from src/cli/worktree-selector-caller-host.test.ts rename to src/cli/workspace-selection/worktree-selector-caller-host.test.ts diff --git a/src/cli/worktree-selector-wsl-posix-path.test.ts b/src/cli/workspace-selection/worktree-selector-wsl-posix-path.test.ts similarity index 89% rename from src/cli/worktree-selector-wsl-posix-path.test.ts rename to src/cli/workspace-selection/worktree-selector-wsl-posix-path.test.ts index 75e74e6aa83..8fa27294e5a 100644 --- a/src/cli/worktree-selector-wsl-posix-path.test.ts +++ b/src/cli/workspace-selection/worktree-selector-wsl-posix-path.test.ts @@ -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' diff --git a/src/cli/wsl-caller-path-selector.ts b/src/cli/workspace-selection/wsl-caller-path-selector.ts similarity index 85% rename from src/cli/wsl-caller-path-selector.ts rename to src/cli/workspace-selection/wsl-caller-path-selector.ts index efc1e0d051b..339d8ad739e 100644 --- a/src/cli/wsl-caller-path-selector.ts +++ b/src/cli/workspace-selection/wsl-caller-path-selector.ts @@ -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 { try { diff --git a/src/cli/handlers/folder-setup-support-warning.ts b/src/cli/workspaces/folder-setup-support-warning.ts similarity index 92% rename from src/cli/handlers/folder-setup-support-warning.ts rename to src/cli/workspaces/folder-setup-support-warning.ts index 35ac1902463..c6a43f238f7 100644 --- a/src/cli/handlers/folder-setup-support-warning.ts +++ b/src/cli/workspaces/folder-setup-support-warning.ts @@ -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' diff --git a/src/cli/handlers/folder-workspace-mutations.ts b/src/cli/workspaces/folder-workspace-mutations.ts similarity index 94% rename from src/cli/handlers/folder-workspace-mutations.ts rename to src/cli/workspaces/folder-workspace-mutations.ts index 4fac8469f47..3d85440f550 100644 --- a/src/cli/handlers/folder-workspace-mutations.ts +++ b/src/cli/workspaces/folder-workspace-mutations.ts @@ -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 diff --git a/src/cli/index-worktree-parent-environment.test.ts b/src/cli/workspaces/index-worktree-parent-environment.test.ts similarity index 91% rename from src/cli/index-worktree-parent-environment.test.ts rename to src/cli/workspaces/index-worktree-parent-environment.test.ts index 24659f2c2de..df2bb22f2ac 100644 --- a/src/cli/index-worktree-parent-environment.test.ts +++ b/src/cli/workspaces/index-worktree-parent-environment.test.ts @@ -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>()), + getDefaultUserDataPath: getDefaultUserDataPathMock +})) + +vi.mock('../runtime/launch', async (importOriginal) => ({ + ...(await importOriginal>()), + 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' }, diff --git a/src/cli/index-worktree-wsl-selection.test.ts b/src/cli/workspaces/index-worktree-wsl-selection.test.ts similarity index 90% rename from src/cli/index-worktree-wsl-selection.test.ts rename to src/cli/workspaces/index-worktree-wsl-selection.test.ts index 0da84286a57..bb38042d4e8 100644 --- a/src/cli/index-worktree-wsl-selection.test.ts +++ b/src/cli/workspaces/index-worktree-wsl-selection.test.ts @@ -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` diff --git a/src/cli/workspace-address.ts b/src/cli/workspaces/workspace-address.ts similarity index 95% rename from src/cli/workspace-address.ts rename to src/cli/workspaces/workspace-address.ts index e4a2bb6b1cb..f97c0f74c68 100644 --- a/src/cli/workspace-address.ts +++ b/src/cli/workspaces/workspace-address.ts @@ -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 } diff --git a/src/cli/workspaces/workspace-format.ts b/src/cli/workspaces/workspace-format.ts new file mode 100644 index 00000000000..cd760b29cff --- /dev/null +++ b/src/cli/workspaces/workspace-format.ts @@ -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 + +export function formatWorktreePs( + result: WithAnnotatedHostScope< + Omit & { 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 +): 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 | 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 +}): 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 +} diff --git a/src/cli/handlers/worktree-activate.ts b/src/cli/workspaces/worktree-activate.ts similarity index 92% rename from src/cli/handlers/worktree-activate.ts rename to src/cli/workspaces/worktree-activate.ts index de2c5eeb211..42b414b151c 100644 --- a/src/cli/handlers/worktree-activate.ts +++ b/src/cli/workspaces/worktree-activate.ts @@ -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' diff --git a/src/cli/handlers/worktree-address-annotation.ts b/src/cli/workspaces/worktree-address-annotation.ts similarity index 84% rename from src/cli/handlers/worktree-address-annotation.ts rename to src/cli/workspaces/worktree-address-annotation.ts index a543e1b7f9b..e024de51f1e 100644 --- a/src/cli/handlers/worktree-address-annotation.ts +++ b/src/cli/workspaces/worktree-address-annotation.ts @@ -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. */ diff --git a/src/cli/handlers/worktree-create-agent-launch.ts b/src/cli/workspaces/worktree-create-agent-launch.ts similarity index 94% rename from src/cli/handlers/worktree-create-agent-launch.ts rename to src/cli/workspaces/worktree-create-agent-launch.ts index 60118c47a71..ceedefca77d 100644 --- a/src/cli/handlers/worktree-create-agent-launch.ts +++ b/src/cli/workspaces/worktree-create-agent-launch.ts @@ -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' diff --git a/src/cli/handlers/worktree-create-parent-selector.ts b/src/cli/workspaces/worktree-create-parent-selector.ts similarity index 93% rename from src/cli/handlers/worktree-create-parent-selector.ts rename to src/cli/workspaces/worktree-create-parent-selector.ts index 9c57522bd88..b171c6f2597 100644 --- a/src/cli/handlers/worktree-create-parent-selector.ts +++ b/src/cli/workspaces/worktree-create-parent-selector.ts @@ -1,7 +1,8 @@ import { isWorkspaceKey, worktreeWorkspaceKey } from '../../shared/workspace-scope' import { getOptionalStringFlag } from '../flags' -import { RuntimeClientError, type RuntimeClient } from '../runtime-client' -import { getOptionalParentSelector } from '../caller-folder-workspace' +import { RuntimeClientError } from '../runtime/types' +import type { RuntimeClient } from '../runtime/client' +import { getOptionalParentSelector } from '../workspace-selection/caller-folder-workspace' import { resolveParentEnvironment, type ParentEnvironment } from './worktree-parent-environment' export type CreateParentSelector = { diff --git a/src/cli/handlers/worktree-gitlab-link-context.ts b/src/cli/workspaces/worktree-gitlab-link-context.ts similarity index 91% rename from src/cli/handlers/worktree-gitlab-link-context.ts rename to src/cli/workspaces/worktree-gitlab-link-context.ts index 91e4f3e1185..8a7b60f3941 100644 --- a/src/cli/handlers/worktree-gitlab-link-context.ts +++ b/src/cli/workspaces/worktree-gitlab-link-context.ts @@ -1,9 +1,10 @@ import { parseRemoteProjectRefCandidate } from '../../main/gitlab/projects/project-ref-parser' import type { Repo } from '../../shared/repo-types' -import type { RuntimeWorktreeRecord } from '../../shared/runtime-types' +import type { RuntimeWorktreeRecord } from '../../shared/runtime-worktree-contracts' import { parseGitLabIssueOrMRLink, type ProjectSlug } from '../../shared/new-workspace/gitlab-links' -import { RuntimeClientError, type RuntimeClient } from '../runtime-client' -import type { CliRepoTarget } from '../worktree-project-target' +import { RuntimeClientError } from '../runtime/types' +import type { RuntimeClient } from '../runtime/client' +import type { CliRepoTarget } from './worktree-project-target' export async function assertGitLabLinkFlagProjectsMatch( flags: Map, diff --git a/src/cli/handlers/worktree-gitlab-link.ts b/src/cli/workspaces/worktree-gitlab-link.ts similarity index 97% rename from src/cli/handlers/worktree-gitlab-link.ts rename to src/cli/workspaces/worktree-gitlab-link.ts index 033ad4ef030..b4f6fc55550 100644 --- a/src/cli/handlers/worktree-gitlab-link.ts +++ b/src/cli/workspaces/worktree-gitlab-link.ts @@ -1,5 +1,5 @@ import { parseGitLabIssueOrMRLink } from '../../shared/new-workspace/gitlab-links' -import { RuntimeClientError } from '../runtime-client' +import { RuntimeClientError } from '../runtime/types' import { getOptionalWorktreeLinkFlagValue } from './worktree-link-flag-value' export type GitLabLinkKind = 'issue' | 'mr' diff --git a/src/cli/worktree-handler-groups.ts b/src/cli/workspaces/worktree-handler-groups.ts similarity index 59% rename from src/cli/worktree-handler-groups.ts rename to src/cli/workspaces/worktree-handler-groups.ts index 8e6ce90a7a8..d9a699e4dee 100644 --- a/src/cli/worktree-handler-groups.ts +++ b/src/cli/workspaces/worktree-handler-groups.ts @@ -1,4 +1,4 @@ -import type { HandlerGroup } from './handler-group-manifest' +import type { HandlerGroup } from '../handler-group-manifest' export const WORKTREE_HANDLER_GROUPS: readonly HandlerGroup[] = [ { @@ -12,11 +12,11 @@ export const WORKTREE_HANDLER_GROUPS: readonly HandlerGroup[] = [ 'worktree set', 'worktree rm' ], - load: async () => (await import('./handlers/worktree.js')).WORKTREE_HANDLERS + load: async () => (await import('./worktree.js')).WORKTREE_HANDLERS }, { name: 'worktree-activate', keys: ['worktree activate'], - load: async () => (await import('./handlers/worktree-activate.js')).WORKTREE_ACTIVATE_HANDLERS + load: async () => (await import('./worktree-activate.js')).WORKTREE_ACTIVATE_HANDLERS } ] diff --git a/src/cli/handlers/worktree-lineage-summary.ts b/src/cli/workspaces/worktree-lineage-summary.ts similarity index 95% rename from src/cli/handlers/worktree-lineage-summary.ts rename to src/cli/workspaces/worktree-lineage-summary.ts index b3e88e82698..5e62f4ee543 100644 --- a/src/cli/handlers/worktree-lineage-summary.ts +++ b/src/cli/workspaces/worktree-lineage-summary.ts @@ -1,4 +1,7 @@ -import type { RuntimeWorktreeCreateResult, RuntimeWorktreeRecord } from '../../shared/runtime-types' +import type { + RuntimeWorktreeCreateResult, + RuntimeWorktreeRecord +} from '../../shared/runtime-worktree-contracts' function getLineageSourceLabel(source: string): string { switch (source) { diff --git a/src/cli/handlers/worktree-linear-issue-link.ts b/src/cli/workspaces/worktree-linear-issue-link.ts similarity index 95% rename from src/cli/handlers/worktree-linear-issue-link.ts rename to src/cli/workspaces/worktree-linear-issue-link.ts index a866c16ef8c..0af5a6eae91 100644 --- a/src/cli/handlers/worktree-linear-issue-link.ts +++ b/src/cli/workspaces/worktree-linear-issue-link.ts @@ -3,7 +3,7 @@ import { LINEAR_ISSUE_LINK_CLEARED, type LinearIssueLinkUpdates } from '../../shared/linear/links' -import { RuntimeClientError } from '../runtime-client' +import { RuntimeClientError } from '../runtime/types' import { getOptionalWorktreeLinkFlagValue } from './worktree-link-flag-value' export function getOptionalLinearIssueLinkFlag( diff --git a/src/cli/handlers/worktree-link-flag-value.ts b/src/cli/workspaces/worktree-link-flag-value.ts similarity index 92% rename from src/cli/handlers/worktree-link-flag-value.ts rename to src/cli/workspaces/worktree-link-flag-value.ts index 6d483fd699a..4abe0011e71 100644 --- a/src/cli/handlers/worktree-link-flag-value.ts +++ b/src/cli/workspaces/worktree-link-flag-value.ts @@ -1,4 +1,4 @@ -import { RuntimeClientError } from '../runtime-client' +import { RuntimeClientError } from '../runtime/types' export function getOptionalWorktreeLinkFlagValue( flags: Map, diff --git a/src/cli/handlers/worktree-parent-environment.ts b/src/cli/workspaces/worktree-parent-environment.ts similarity index 94% rename from src/cli/handlers/worktree-parent-environment.ts rename to src/cli/workspaces/worktree-parent-environment.ts index 73ae5caac22..8c10ad71d1d 100644 --- a/src/cli/handlers/worktree-parent-environment.ts +++ b/src/cli/workspaces/worktree-parent-environment.ts @@ -1,19 +1,22 @@ import { isRecoverableRemoteRuntimeConnectionError } from '../../shared/remote-runtime/remote-runtime-client-error-classification' import { listEnvironments } from '../../shared/remote-runtime/host-store/runtime-environment-store' -import type { RuntimeStatus, RuntimeWorktreeRecord } from '../../shared/runtime-types' +import type { RuntimeStatus } from '../../shared/runtime-session-contracts' +import type { RuntimeWorktreeRecord } from '../../shared/runtime-worktree-contracts' import type { CrossStoreParentRef } from '../../shared/worktree/lineage-types' import { crossStoreParentRefOfRow } from '../../shared/worktree/lineage-row-identity' import { supportsCrossStoreLineage, WORKTREE_CROSS_STORE_LINEAGE_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities' -import { getOptionalParentSelector } from '../caller-folder-workspace' +import { getOptionalParentSelector } from '../workspace-selection/caller-folder-workspace' import { getOptionalStringFlag } from '../flags' -import { mayNameFolderWorkspace } from '../folder-workspace-selector' -import { isLocalEnvironmentSelector, LOCAL_ENVIRONMENT } from '../local-environment-selector' -import { RuntimeClient, RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client' +import { mayNameFolderWorkspace } from '../workspace-selection/folder-workspace-selector' +import { isLocalEnvironmentSelector, LOCAL_ENVIRONMENT } from '../hosts/local-environment-selector' +import { RuntimeClient } from '../runtime/client' +import { RuntimeClientError } from '../runtime/types' +import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' import { quoteCliCommandArgument } from '../shell-command-quote' -import { describeClientEnvironment, environmentLabel } from '../workspace-address' +import { describeClientEnvironment, environmentLabel } from './workspace-address' import { attachCliErrorData } from './worktree-setup-decision-recovery' /** The Orca a parent lives in: `local` or a saved environment's id. */ diff --git a/src/cli/handlers/worktree-parent-fields.ts b/src/cli/workspaces/worktree-parent-fields.ts similarity index 94% rename from src/cli/handlers/worktree-parent-fields.ts rename to src/cli/workspaces/worktree-parent-fields.ts index 02c82850d5a..94cf3f39aa3 100644 --- a/src/cli/handlers/worktree-parent-fields.ts +++ b/src/cli/workspaces/worktree-parent-fields.ts @@ -1,4 +1,4 @@ -import type { RuntimeStatus } from '../../shared/runtime-types' +import type { RuntimeStatus } from '../../shared/runtime-session-contracts' import { parseWorkspaceKey } from '../../shared/workspace-scope' import type { CrossStoreInferredSource, @@ -9,11 +9,12 @@ import { supportsCrossStoreLineage } from '../../shared/worktree-runtime-capabilities' import { getOptionalStringFlag } from '../flags' -import { RuntimeClient, RuntimeClientError } from '../runtime-client' -import { resolveWorktreeCreateCwdContext } from '../selectors' -import { mayNameFolderWorkspace } from '../folder-workspace-selector' -import { parentCwdNextSteps, withWorktreeSelectorRecovery } from '../worktree-selector-recovery' -import { getOptionalParentSelector } from '../caller-folder-workspace' +import { RuntimeClient } from '../runtime/client' +import { RuntimeClientError } from '../runtime/types' +import { resolveWorktreeCreateCwdContext } from '../workspace-selection/workspace-selector' +import { mayNameFolderWorkspace } from '../workspace-selection/folder-workspace-selector' +import { parentCwdNextSteps, withWorktreeSelectorRecovery } from './worktree-selector-recovery' +import { getOptionalParentSelector } from '../workspace-selection/caller-folder-workspace' import type { CreateParentSelector } from './worktree-create-parent-selector' import { resolveCrossEnvironmentParent, diff --git a/src/cli/worktree-project-target.ts b/src/cli/workspaces/worktree-project-target.ts similarity index 93% rename from src/cli/worktree-project-target.ts rename to src/cli/workspaces/worktree-project-target.ts index c538b0c9482..c48e28bcc79 100644 --- a/src/cli/worktree-project-target.ts +++ b/src/cli/workspaces/worktree-project-target.ts @@ -1,11 +1,11 @@ -import { normalizeExecutionHostId, type ParsedExecutionHost } from '../shared/execution-host' -import type { ProjectHostSetup } from '../shared/project-types' -import { hostFilterMatchesHostId, resolveHostFlagTarget } from './execution-host-flag' -import { findProjectSetups, setupHostId } from './project-selector' -import type { RuntimeClient } from './runtime-client' -import { RuntimeClientError } from './runtime-client' -import { getPresentStringFlag } from './flags' -import { getFolderWorkspaceMissingRepoError } from './caller-folder-workspace' +import { normalizeExecutionHostId, type ParsedExecutionHost } from '../../shared/execution-host' +import type { ProjectHostSetup } from '../../shared/project-types' +import { hostFilterMatchesHostId, resolveHostFlagTarget } from '../hosts/execution-host-flag' +import { findProjectSetups, setupHostId } from '../projects/project-selector' +import type { RuntimeClient } from '../runtime/client' +import { RuntimeClientError } from '../runtime/types' +import { getPresentStringFlag } from '../flags' +import { getFolderWorkspaceMissingRepoError } from '../workspace-selection/caller-folder-workspace' export type ProjectCreateTarget = { repoSelector: string diff --git a/src/cli/worktree-ps-program-status.ts b/src/cli/workspaces/worktree-ps-program-status.ts similarity index 83% rename from src/cli/worktree-ps-program-status.ts rename to src/cli/workspaces/worktree-ps-program-status.ts index 6a9a1798b2c..17bd7d793b5 100644 --- a/src/cli/worktree-ps-program-status.ts +++ b/src/cli/workspaces/worktree-ps-program-status.ts @@ -1,8 +1,8 @@ -import type { RuntimeWorktreeAgentRow } from '../shared/runtime-types' +import type { RuntimeWorktreeAgentRow } from '../../shared/runtime-worktree-contracts' import { programStatusAttentionLabel, resolveProgramStatusPresentation -} from '../shared/program-status/presentation' +} from '../../shared/program-status/presentation' /** A block takes precedence over progress. */ export function formatWorktreePsProgramStatus( diff --git a/src/cli/worktree-ps-terminal-verdict.ts b/src/cli/workspaces/worktree-ps-terminal-verdict.ts similarity index 94% rename from src/cli/worktree-ps-terminal-verdict.ts rename to src/cli/workspaces/worktree-ps-terminal-verdict.ts index 80487ed8d1f..b9f4786ae22 100644 --- a/src/cli/worktree-ps-terminal-verdict.ts +++ b/src/cli/workspaces/worktree-ps-terminal-verdict.ts @@ -1,4 +1,4 @@ -import type { RuntimeWorktreePsSummary } from '../shared/runtime-types' +import type { RuntimeWorktreePsSummary } from '../../shared/runtime-worktree-contracts' type TerminalCounts = Pick< RuntimeWorktreePsSummary, diff --git a/src/cli/handlers/worktree-removal-current-refusal.ts b/src/cli/workspaces/worktree-removal-current-refusal.ts similarity index 90% rename from src/cli/handlers/worktree-removal-current-refusal.ts rename to src/cli/workspaces/worktree-removal-current-refusal.ts index c210fa5f8c7..a1ecc882d78 100644 --- a/src/cli/handlers/worktree-removal-current-refusal.ts +++ b/src/cli/workspaces/worktree-removal-current-refusal.ts @@ -1,7 +1,8 @@ import { getOptionalStringFlag } from '../flags' -import { assertLocalCwdWorktreeSelector } from '../local-environment-selector' -import { RuntimeClientError, type RuntimeClient } from '../runtime-client' -import { resolveCurrentWorktreeSelector } from '../selectors' +import { assertLocalCwdWorktreeSelector } from '../hosts/local-environment-selector' +import { RuntimeClientError } from '../runtime/types' +import type { RuntimeClient } from '../runtime/client' +import { resolveCurrentWorktreeSelector } from '../workspace-selection/workspace-selector' import { quoteCliCommandArgument } from '../shell-command-quote' /** What current/active names right now: one selector, the ambiguous choices, or nothing. */ diff --git a/src/cli/handlers/worktree-removal-request.ts b/src/cli/workspaces/worktree-removal-request.ts similarity index 92% rename from src/cli/handlers/worktree-removal-request.ts rename to src/cli/workspaces/worktree-removal-request.ts index bc1cb0c2f73..cc840323ae2 100644 --- a/src/cli/handlers/worktree-removal-request.ts +++ b/src/cli/workspaces/worktree-removal-request.ts @@ -1,8 +1,10 @@ import { z } from 'zod' import { WORKTREE_REMOVE_BRANCH_POLICY_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities' -import type { RuntimeWorktreeRemoveResult } from '../../shared/runtime-types' +import type { RuntimeWorktreeRemoveResult } from '../../shared/runtime-worktree-contracts' import { worktreeRemovalReplyTimeoutMs } from '../../shared/worktree/archive-hook-removal-gate' -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' export type WorktreeRemovalRequest = { worktree: string diff --git a/src/cli/handlers/worktree-removal-warnings.ts b/src/cli/workspaces/worktree-removal-warnings.ts similarity index 100% rename from src/cli/handlers/worktree-removal-warnings.ts rename to src/cli/workspaces/worktree-removal-warnings.ts diff --git a/src/cli/handlers/worktree-review-link-flags.ts b/src/cli/workspaces/worktree-review-link-flags.ts similarity index 96% rename from src/cli/handlers/worktree-review-link-flags.ts rename to src/cli/workspaces/worktree-review-link-flags.ts index 928e5b3ed3a..8f3da03a244 100644 --- a/src/cli/handlers/worktree-review-link-flags.ts +++ b/src/cli/workspaces/worktree-review-link-flags.ts @@ -1,5 +1,5 @@ import { getOptionalNullableNumberFlag, getOptionalNumberFlag } from '../flags' -import { RuntimeClientError } from '../runtime-client' +import { RuntimeClientError } from '../runtime/types' import { getOptionalWorktreeLinkFlagValue } from './worktree-link-flag-value' import { getOptionalGitLabLinkFlag } from './worktree-gitlab-link' diff --git a/src/cli/worktree-selector-recovery.ts b/src/cli/workspaces/worktree-selector-recovery.ts similarity index 94% rename from src/cli/worktree-selector-recovery.ts rename to src/cli/workspaces/worktree-selector-recovery.ts index c67a0b4e658..8ab88b10503 100644 --- a/src/cli/worktree-selector-recovery.ts +++ b/src/cli/workspaces/worktree-selector-recovery.ts @@ -1,6 +1,6 @@ -import { parseWorkspaceKey } from '../shared/workspace-scope' -import { RuntimeClientError } from './runtime/types' -import { attachCliErrorData } from './handlers/worktree-setup-decision-recovery' +import { parseWorkspaceKey } from '../../shared/workspace-scope' +import { RuntimeClientError } from '../runtime/types' +import { attachCliErrorData } from './worktree-setup-decision-recovery' // The runtime omits the typed selector from not-found errors; add it and its grammar at the CLI boundary. diff --git a/src/cli/handlers/worktree-setup-decision-recovery.ts b/src/cli/workspaces/worktree-setup-decision-recovery.ts similarity index 100% rename from src/cli/handlers/worktree-setup-decision-recovery.ts rename to src/cli/workspaces/worktree-setup-decision-recovery.ts diff --git a/src/cli/handlers/worktree-unread-flag.ts b/src/cli/workspaces/worktree-unread-flag.ts similarity index 93% rename from src/cli/handlers/worktree-unread-flag.ts rename to src/cli/workspaces/worktree-unread-flag.ts index 1aad3b1238d..797927ac496 100644 --- a/src/cli/handlers/worktree-unread-flag.ts +++ b/src/cli/workspaces/worktree-unread-flag.ts @@ -1,4 +1,4 @@ -import { RuntimeClientError } from '../runtime-client' +import { RuntimeClientError } from '../runtime/types' export function getWorktreeReadFlags(flags: Map): { isUnread?: boolean diff --git a/src/cli/handlers/worktree.ts b/src/cli/workspaces/worktree.ts similarity index 96% rename from src/cli/handlers/worktree.ts rename to src/cli/workspaces/worktree.ts index dffc06352ec..18947b019b6 100644 --- a/src/cli/handlers/worktree.ts +++ b/src/cli/workspaces/worktree.ts @@ -1,23 +1,23 @@ import { withFolderSetupSupportWarning } from './folder-setup-support-warning' -import { withWorktreeSelectorRecovery } from '../worktree-selector-recovery' +import { withWorktreeSelectorRecovery } from './worktree-selector-recovery' import type { RuntimeWorktreeListResult, RuntimeWorktreePsResult, RuntimeWorktreeRecord, RuntimeWorktreeSetResult, RuntimeWorktreeCreateResult -} from '../../shared/runtime-types' +} from '../../shared/runtime-worktree-contracts' import type { CommandHandler } from '../dispatch' import { printHookWarning, printPreservedBranchWarning } from './worktree-removal-warnings' import { requestWorktreeRemoval } from './worktree-removal-request' import { removeIfFolderWorkspace, setIfFolderWorkspace } from './folder-workspace-mutations' -import { formatWorktreeList, formatWorktreePs, formatWorktreeShow } from '../workspace-format' +import { formatWorktreeList, formatWorktreePs, formatWorktreeShow } from './workspace-format' import { printResult } from '../command-result-output' 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 { getOptionalPositiveIntegerFlag, getOptionalStringFlag, @@ -29,7 +29,7 @@ import { getRequiredWorktreeSelector, resolveWorktreeCreateCwdContext, resolveCurrentWorktreeSelector -} from '../selectors' +} from '../workspace-selection/workspace-selector' import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' import { parseCliAgent, readCliAgentLaunch } from '../agents/agent-launch-request' import { createWorktreeWithAgent } from './worktree-create-agent-launch' @@ -38,13 +38,13 @@ import { resolveCreateParentFields, resolveSetParentFields } from './worktree-pa import { callNamingParentEnvironment } from './worktree-parent-environment' import { annotatePsRows, annotateShown } from './worktree-address-annotation' import { refuseCurrentForRemoval } from './worktree-removal-current-refusal' -import { projectWorktreePsTerminalVerdict } from '../worktree-ps-terminal-verdict' +import { projectWorktreePsTerminalVerdict } from './worktree-ps-terminal-verdict' import { assertWorkspaceTargetFlagsCompatible, hasWorkspaceProjectTarget, getCreateRepoTarget, type CliRepoTarget -} from '../worktree-project-target' +} from './worktree-project-target' import { assertWorktreeParentFlagsCompatible, getEnvParentWorkspace, diff --git a/tests/e2e/agent-launch-cli.unit.test.ts b/tests/e2e/agent-launch-cli.unit.test.ts index eb346bd9904..23782ef3aba 100644 --- a/tests/e2e/agent-launch-cli.unit.test.ts +++ b/tests/e2e/agent-launch-cli.unit.test.ts @@ -10,7 +10,7 @@ import { RuntimeClient, RuntimeClientError } from '../../src/cli/runtime-client' import { callAgentLaunch, readCliAgentLaunch } from '../../src/cli/agents/agent-launch-request' import { parseArgs } from '../../src/cli/args' import { AGENT_LAUNCH_HANDLERS } from '../../src/cli/agents/agent-launch' -import { createWorktreeWithAgent } from '../../src/cli/handlers/worktree-create-agent-launch' +import { createWorktreeWithAgent } from '../../src/cli/workspaces/worktree-create-agent-launch' import { methodNamed, rpcContext, @@ -226,48 +226,6 @@ describe('CLI launch through host surface creation and replay admission', () => } ) - it('refuses replay on an older replacement host without sending any launch', async () => { - const client = hostClient(runtimeStub()) - const operationId = `${Date.now()}-${'a'.repeat(32)}` - await expect( - callAgentLaunch(client, { agent: 'codex', operationId }, { target: existing }, [ - 'agent.launch.v2', - 'agent.launch.local-presentation.v1' - ]) - ).rejects.toThrow('do not retry without --retry-launch') - expect(client.call).not.toHaveBeenCalled() - }) - - it.each([existing, create])( - 'refuses a v2-only prompted launch before creating anything: %j', - async (target) => { - const runtime = runtimeStub() - await expect( - callAgentLaunch( - hostClient(runtime), - { agent: 'codex', prompt: { text: 'Long\nMultiline', delivery: 'submit' } }, - { target }, - ['agent.launch.v2'] - ) - ).rejects.toThrow('cannot safely carry launch prompts') - expect(chatCreate).not.toHaveBeenCalled() - expect(runtime.createTerminal).not.toHaveBeenCalled() - } - ) - - it('refuses hosts without local presentation before creating anything', async () => { - const client = hostClient(runtimeStub()) - await expect( - callAgentLaunch( - client, - { agent: 'codex' }, - { target: existing, presentation: 'background' }, - ['agent.launch.v2'] - ) - ).rejects.toThrow('cannot honor CLI launch focus or background') - expect(client.call).not.toHaveBeenCalled() - }) - it('gives inspection-only recovery after an ambiguous legacy create and never falls back again', async () => { const client = new RuntimeClient(directory, 60_000, null, null) const call = vi