From 5a47d4ced8edbb7ccd7449f1bedb29ffd10cdd62 Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 9 Nov 2026 23:24:59 -0800 Subject: [PATCH] refactor(renderer): group workspace creation and launch owners --- config/flaky-test-pattern-baseline.txt | 1 - config/react-compiler-bailout-baseline.txt | 2 +- .../scripts/ci/sharding/ci-shard-timings.json | 21 +- .../vitest-shared-worker-setup-runner.mjs | 16 + config/tsconfig.node.json | 2 +- config/vitest.config.ts | 3 + ...reated-worktree-setup-trust-parity.test.ts | 2 +- .../components/NewWorkspaceComposerCard.tsx | 2 +- .../components/NewWorkspaceComposerModal.tsx | 12 +- .../AgentSessionContinuationDialog.tsx | 2 +- .../authoring/AutomationEditorDialog.tsx | 2 +- .../authoring/automation-orca-save.ts | 2 +- .../authoring/automation-setup-review.ts | 2 +- .../automations-page-test-harness.tsx | 2 +- .../cmd-j/task-search-activation.ts | 7 +- .../dashboard-chat-program-acquisition.ts | 4 +- .../dashboard-worktree-launch-options.ts | 2 +- .../dashboard/useDashboardPopoutBridge.ts | 2 +- .../dashboard/useLiveDashboardSnapshot.ts | 2 +- ...orkspaceComposerProjectSection.fixture.tsx | 4 +- .../NewWorkspaceComposerProjectSection.tsx | 2 +- .../new-workspace/ProjectCombobox.test.tsx | 171 ------- .../new-workspace/ProjectCombobox.tsx | 2 +- .../new-workspace/ProjectComboboxRow.test.tsx | 52 --- .../new-workspace/ProjectComboboxRow.tsx | 2 +- .../RunTargetCombobox.fixture.tsx | 2 +- .../new-workspace/RunTargetCombobox.tsx | 2 +- .../new-workspace/RunTargetRowList.tsx | 2 +- .../SetProjectLocationDialog.test.tsx | 85 +--- .../SetProjectLocationDialog.tsx | 2 +- .../new-workspace/composer-modal-data.ts | 4 +- .../new-workspace-composer-card-props.ts | 6 +- .../project-combobox-matching.ts | 4 +- .../new-workspace/run-target-options.ts | 2 +- .../new-workspace/use-recent-project-ids.ts | 2 +- .../onboarding-folder-agent-launch.ts | 12 +- .../onboarding-folder-agent-startup.ts | 21 +- .../onboarding-project-checklist.ts | 2 +- .../use-onboarding-agent-surface.ts | 7 +- .../use-onboarding-flow-actions.test.tsx | 306 ------------- .../pull-request-page/checks/tab.tsx | 2 +- .../use-ai-vault-panel-session-resume.ts | 2 +- .../folder-workspace-repo-worktree-create.ts | 2 +- .../source-control/ai/recovery-launch.ts | 4 +- ...saved-source-control-action-start.test.tsx | 68 --- .../use-saved-source-control-action-start.ts | 4 +- .../use-source-control-launchable-agents.ts | 7 +- .../launch/AgentLaunchSettingsCatalog.tsx | 4 +- .../settings/chat/ChatAgentLaunchSettings.tsx | 7 +- .../ChatSettingsSection.navigation.test.tsx | 133 ------ .../chat/ChatSettingsSection.test.tsx | 4 +- .../hosts/repository-host-setup-options.ts | 2 +- .../worktrees/SparsePresetSettingsSection.tsx | 5 +- .../recipes/EphemeralVmsPane.tsx | 2 +- .../runtimes/EphemeralVmRuntimeRow.tsx | 2 +- .../runtimes/EphemeralVmRuntimesSection.tsx | 2 +- .../setup-guide/use-setup-guide-progress.ts | 2 +- .../sidebar/OrcaYamlTrustDialog.test.tsx | 2 +- .../sidebar/OrcaYamlTrustDialog.tsx | 4 +- .../components/sidebar/RemoveFolderDialog.tsx | 2 +- .../sidebar/SetupScriptPromptCard.tsx | 2 +- .../sidebar/SetupScriptPromptCardShell.tsx | 2 +- .../project-added-default-checkout.ts | 2 +- .../project-admission/create/useCreateRepo.ts | 2 +- .../dialog/NonGitFolderDialog.tsx | 4 +- .../use-add-repo-hosted-controller.ts | 2 +- .../useAddRepoNestedImportFlow.ts | 2 +- .../setup-script-prompt-render-state.ts | 2 +- .../useRenderedSetupScriptPromptState.ts | 2 +- .../sidebar/useSetupScriptPromptInspection.ts | 2 +- .../use-worktree-context-menu-commands.ts | 2 +- .../worktree-context-menu-policy.ts | 5 +- .../surface/WorktreeCardVmStateBadge.tsx | 2 +- .../folder/folder-workspace-agent-startup.ts | 2 +- .../folder-workspace-composer-submit-input.ts | 2 +- .../folder-workspace-composer-submit.test.ts | 56 +-- .../folder-workspace-composer-submit.ts | 9 +- .../folder-workspace-source-selection.ts | 2 +- .../listing/use-main-list-model.ts | 2 +- .../worktree-list/listing/use-section-rows.ts | 5 +- .../listing/use-visible-worktrees.ts | 2 +- .../rows/header-create-workspace-target.ts | 7 +- .../rows/repo-header-create-state.ts | 2 +- .../sparse/SparseCheckoutPresetDraftForm.tsx | 2 +- .../sparse/SparseCheckoutPresetSelect.tsx | 5 +- .../sparse}/sparse-preset-draft.ts | 0 .../components/tab-bar/QuickLaunchButton.tsx | 5 +- .../tab-bar/use-new-tab-agent-menu-rows.ts | 4 +- .../src/components/task-page/jira/Filters.tsx | 2 +- .../components/task-page/linear/Filters.tsx | 2 +- .../use-task-page-composer-actions.ts | 4 +- .../task-page/use-task-page-search-actions.ts | 2 +- .../use-task-page-workspace-actions.ts | 2 +- .../components/terminal-agent-tab-shortcut.ts | 2 +- .../file-drop/terminal-drop-handler.test.ts | 221 --------- .../terminal-drop-internal-handler.test.ts | 2 +- .../file-drop/terminal-drop-local-wsl.ts | 2 +- .../parked-terminal-command-status.ts | 2 +- .../command-code-pane-status.ts | 2 +- .../renderer-owned-pane-status.ts | 2 +- .../deferred-cold-restore-and-snapshot.ts | 2 +- .../emulation/native-windows-pane-policy.ts | 2 +- .../output/write-pty-output-to-xterm.ts | 2 +- .../startup/initial-agent-status.ts | 2 +- .../pty-connection-test-environment.ts | 2 +- .../remote-runtime-pty-transport.ts | 4 +- .../terminal-agent-session-fork.ts | 2 +- .../worktree-creation/VmBuildSheet.tsx | 4 +- .../WorktreeJumpPalette.linear-url.test.tsx | 135 +----- ...use-worktree-jump-palette-quick-actions.ts | 12 +- .../use-worktree-jump-palette-store-state.ts | 2 +- .../use-worktree-jump-palette-task-url.ts | 10 +- .../worktree-jump-palette-create-worktree.ts | 2 +- .../composer-state/async-composer-state.ts | 2 +- .../src/hooks/composer-state/async-model.ts | 2 +- .../composer-agent-rows-target.ts | 5 +- .../composer-state/composer-card-props.ts | 4 +- .../composer-state/composer-decisions.ts | 4 +- .../composer-state/composer-submit-model.ts | 4 +- .../composer-state/composer-target-store.ts | 12 +- .../composer-state/derived-composer-state.ts | 2 +- .../folder-submit-orchestration.ts | 4 +- .../github-source-application.ts | 6 +- .../composer-state/host-runtime-effects.ts | 7 +- .../composer-state/initial-target-model.ts | 2 +- .../composer-state/initial-target-state.ts | 4 +- .../composer-state/issue-source-actions.ts | 7 +- .../linked-item-lookup-effects.ts | 2 +- .../composer-state/project-target-actions.ts | 4 +- .../quick-creation-execution.ts | 4 +- .../composer-state/quick-creation-request.ts | 2 +- .../composer-state/quick-submit-action.ts | 8 +- .../quick-submit-preparation.ts | 4 +- .../quick-submit-source-preparation.ts | 3 +- .../composer-state/runtime-target-model.ts | 6 +- .../runtime-target-selection.ts | 10 +- .../composer-state/source-context-model.ts | 2 +- .../composer-state/source-context-state.ts | 2 +- .../composer-state/source-identity-actions.ts | 6 +- .../source-selection-decisions.ts | 2 +- .../composer-state/target-change-actions.ts | 7 +- .../composer-state/target-store-model.ts | 4 +- .../hooks/ipc-events/new-workspace-command.ts | 2 +- src/renderer/src/hooks/useComposerState.ts | 6 +- .../src/hooks/useEphemeralVmRecipeOptions.ts | 2 +- ...-agent-session-continuation-toast.test.tsx | 2 +- .../launch-agent-session-continuation.ts | 4 +- .../launch}/environment-setup-agent-launch.ts | 10 +- .../host-chat-program-acquisition.ts | 12 +- .../launch/inventory}/host-chat-program.ts | 22 +- .../native-chat-provider-choice.test.tsx | 189 -------- ...ent-launch-caller-prompt-transport.test.ts | 2 +- .../agent-launch-caller-routing.test.ts | 2 +- ...unch-agent-in-new-tab-main-surface.test.ts | 2 +- .../new-tab/launch-agent-web-host-tab.ts | 4 +- .../web-host-agent-launch-completion.ts | 10 +- .../prompt/launch-agent-tab-prompt-paste.ts | 2 +- .../prompt}/new-agent-prompt-outcome.ts | 4 +- .../routing}/paired-agent-launch-inputs.ts | 28 +- .../launch/shortcuts/agent-tab-shortcuts.ts | 4 +- .../resume/agent-resume-launch-target.ts | 2 +- ...i-vault-antigravity-reference-host.test.ts | 139 +----- ...ai-vault-resume-command.drop-repin.test.ts | 2 +- .../history/ai-vault-resume-command.test.ts | 113 +---- .../history/ai-vault-resume-platform.test.ts | 2 +- .../history/ai-vault-resume-platform.ts | 2 +- .../resume/history/ai-vault-resume-shell.ts | 2 +- .../command-code-prompt-status-seed.ts | 8 +- .../renderer-agent-status-observations.ts | 2 +- .../lib/hook-command-delayed-delivery.test.ts | 67 --- .../src/lib/host-chat-program.test.ts | 178 -------- src/renderer/src/lib/new-workspace.test.ts | 324 ------------- .../non-secure-context-crypto.repro.test.ts | 32 -- .../onboarding-folder-cancellation.test.ts | 227 --------- ...ca-yaml-trust-prompt-slot-eviction.test.ts | 75 --- .../src/lib/run-target-host-visibility.ts | 2 +- ...ent-session-launch-windows-quoting.test.ts | 228 ---------- ...ource-control-agent-action-launch-check.ts | 2 +- .../ai/source-control-agent-picker.ts | 2 +- .../checks/fix-checks-agent-launch.ts | 2 +- .../work-items/github/smart-github-submit.ts | 2 +- .../linear/linear-linked-work-item.ts | 2 +- .../empty-workspace-default-agent-chat.ts | 7 +- .../worktree-initial-terminal-seeding.ts | 2 +- .../worktree-setup-issue-command-queue.ts | 2 +- .../activation/sidebar-worktree-activation.ts | 2 +- .../worktree-activation.test-fixture.ts | 2 +- .../creation}/composer-create-handoff.ts | 2 +- .../creation}/composer-issue-command.ts | 4 +- .../creation}/composer-submit-cancellation.ts | 0 .../ephemeral-vm-worktree-creation.ts | 16 +- .../creation}/nested-repo-selected-paths.ts | 2 +- .../creation}/new-workspace-composer-repo.ts | 53 +-- .../creation}/new-workspace-create-gates.ts | 0 ...new-workspace-duplicate-project-details.ts | 2 +- .../creation}/new-workspace-enter-guard.ts | 0 .../new-workspace-project-options.ts | 24 +- .../creation}/new-workspace-ssh-gate.ts | 10 +- .../{ => workspace/creation}/new-workspace.ts | 13 +- .../pending-creation-provisioning-log.ts | 2 +- .../project-clone-url-prefill.test.ts | 28 +- .../creation}/project-clone-url-prefill.ts | 6 +- .../creation}/project-host-health-detail.ts | 2 +- .../creation}/project-host-setup-options.ts | 17 +- .../project-host-setup-row-dedupe.ts | 4 +- ...host-workspace-target.jira-mapping.test.ts | 4 +- .../project-host-workspace-target.test.ts | 6 +- .../project-host-workspace-target.ts | 17 +- .../provisioned-root-create-options.ts | 2 +- .../quick-workspace-agent-selection.ts | 8 +- .../setup}/hook-command-delayed-delivery.ts | 2 +- .../creation/setup}/setup-runner.ts | 4 +- .../setup/workspace-setup-preparation.ts | 2 +- .../creation/setup}/workspace-setup-trust.ts | 12 +- .../work-item/direct-work-item-setup.ts | 2 +- .../launch-work-item-direct-accepted.test.tsx | 373 +-------------- .../launch-work-item-direct-agent-routing.ts | 4 +- .../launch-work-item-direct-draft.ts | 2 +- .../launch-work-item-direct-messages.ts | 2 +- .../launch-work-item-direct-preflight.ts | 2 +- ...unch-work-item-direct-route-preparation.ts | 2 +- .../launch-work-item-direct-setup.test.tsx | 82 +--- .../launch-work-item-direct-test-fixture.ts | 4 +- .../workspace-composer-initial-focus.ts | 0 .../workspace-create-error-format.ts | 0 .../creation/worktree-creation-agent-seeds.ts | 2 +- .../creation/worktree-creation-completion.ts | 2 +- .../worktree-creation-flow-execute.ts | 8 +- .../creation/worktree-creation-flow.ts | 2 +- .../worktree-creation-hook-preparation.ts | 6 +- ...ephemeral-vm-environment-check-decision.ts | 0 .../ephemeral-vm-environment-check.test.ts | 2 +- .../ephemeral-vm-environment-check.ts | 6 +- .../ephemeral-vm}/ephemeral-vm-error-copy.ts | 4 +- .../ephemeral-vm-failed-create-cleanup.ts | 2 +- .../ephemeral-vm-runtime-cleanup.ts | 4 +- .../ephemeral-vm-workspace-target.ts | 13 +- .../ephemeral-vm}/recipe-vm-managed-host.ts | 4 +- .../vm-create-hidden-checkouts.test.ts | 4 +- .../vm-create-hidden-checkouts.ts | 29 +- ...ntime-agent-launch-options.test-fixture.ts | 6 +- .../platform/execution-host-facts.test.ts | 2 +- .../hosts/platform/execution-host-facts.ts | 2 +- .../ensure-hooks-confirmed.test.ts | 2 +- .../repo-hooks}/ensure-hooks-confirmed.ts | 19 +- .../issue-command-trust-content.ts | 0 .../repo-hooks}/orca-hook-trust.ts | 6 +- .../repo-hooks}/setup-script-prompt.ts | 10 +- .../repo-hooks}/setup-script-status.ts | 4 +- .../repo-hooks}/vm-recipe-trust-content.ts | 2 +- .../repos/all-host-repo-catalog-actions.ts | 2 +- .../store/repos/recipe-vm-project-removal.ts | 4 +- .../src/store/repos/repo-add-actions.ts | 4 +- .../src/store/repos/repo-catalog-actions.ts | 2 +- .../src/store/repos/repos-all-hosts.test.ts | 55 +-- .../repos/runtime-repo-catalog-actions.ts | 2 +- .../repos/wsl-moved-repo-ui-retention.test.ts | 2 +- .../repos/wsl-moved-repo-ui-retention.ts | 2 +- .../agent-status-authority-actions.ts | 2 +- .../slices/ui/ui-slice-contract-contextual.ts | 4 +- .../slices/ui/ui-slice-hydration-actions.ts | 2 +- .../store/slices/ui/ui-slice-trust-actions.ts | 2 +- .../create/created-worktree-setup-trust.ts | 2 +- .../create/pending-worktree-creation.ts | 6 +- .../host-qualified-worktree-removal.ts | 2 +- .../worktrees/teardown/remove-worktree.ts | 2 +- .../removed-worktree-renderer-teardown.ts | 2 +- ...-agent-in-new-tab-web-runtime.unit.test.ts | 430 +----------------- ...rkspace-linked-item-project-switch.spec.ts | 2 +- ...al-agent-fork-draft-ownership.unit.test.ts | 216 --------- ...gent-fork-retained-prefill.test-fixture.ts | 259 ----------- 271 files changed, 569 insertions(+), 4761 deletions(-) create mode 100644 config/scripts/test-runtime/execution-policy/vitest-shared-worker-setup-runner.mjs delete mode 100644 src/renderer/src/components/new-workspace/ProjectCombobox.test.tsx delete mode 100644 src/renderer/src/components/new-workspace/ProjectComboboxRow.test.tsx rename src/renderer/src/{lib => components/onboarding}/onboarding-folder-agent-launch.ts (91%) rename src/renderer/src/{lib => components/onboarding}/onboarding-folder-agent-startup.ts (66%) rename src/renderer/src/{lib => components/onboarding}/onboarding-project-checklist.ts (91%) delete mode 100644 src/renderer/src/components/onboarding/use-onboarding-flow-actions.test.tsx delete mode 100644 src/renderer/src/components/right-sidebar/source-control/ai/use-saved-source-control-action-start.test.tsx delete mode 100644 src/renderer/src/components/settings/chat/ChatSettingsSection.navigation.test.tsx rename src/renderer/src/{lib => components/sparse}/sparse-preset-draft.ts (100%) delete mode 100644 src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-handler.test.ts rename src/renderer/src/lib/{ => agent-session/launch}/environment-setup-agent-launch.ts (92%) rename src/renderer/src/lib/{ => agent-session/launch/inventory}/host-chat-program-acquisition.ts (93%) rename src/renderer/src/lib/{ => agent-session/launch/inventory}/host-chat-program.ts (89%) delete mode 100644 src/renderer/src/lib/agent-session/launch/native-chat-provider-choice.test.tsx rename src/renderer/src/lib/{ => agent-session/launch/new-tab}/web-host-agent-launch-completion.ts (78%) rename src/renderer/src/lib/{ => agent-session/launch/prompt}/new-agent-prompt-outcome.ts (84%) rename src/renderer/src/lib/{ => agent-session/launch/routing}/paired-agent-launch-inputs.ts (80%) rename src/renderer/src/lib/{ => agent-status/evidence}/command-code-prompt-status-seed.ts (80%) rename src/renderer/src/lib/{ => agent-status/evidence}/renderer-agent-status-observations.ts (85%) delete mode 100644 src/renderer/src/lib/hook-command-delayed-delivery.test.ts delete mode 100644 src/renderer/src/lib/host-chat-program.test.ts delete mode 100644 src/renderer/src/lib/new-workspace.test.ts delete mode 100644 src/renderer/src/lib/non-secure-context-crypto.repro.test.ts delete mode 100644 src/renderer/src/lib/onboarding-folder-cancellation.test.ts delete mode 100644 src/renderer/src/lib/orca-yaml-trust-prompt-slot-eviction.test.ts delete mode 100644 src/renderer/src/lib/sleeping-agent-session-launch-windows-quoting.test.ts rename src/renderer/src/lib/{ => workspace/creation}/composer-create-handoff.ts (99%) rename src/renderer/src/lib/{ => workspace/creation}/composer-issue-command.ts (92%) rename src/renderer/src/lib/{ => workspace/creation}/composer-submit-cancellation.ts (100%) rename src/renderer/src/lib/{ => workspace/creation}/ephemeral-vm-worktree-creation.ts (92%) rename src/renderer/src/lib/{ => workspace/creation}/nested-repo-selected-paths.ts (74%) rename src/renderer/src/lib/{ => workspace/creation}/new-workspace-composer-repo.ts (55%) rename src/renderer/src/lib/{ => workspace/creation}/new-workspace-create-gates.ts (100%) rename src/renderer/src/lib/{ => workspace/creation}/new-workspace-duplicate-project-details.ts (99%) rename src/renderer/src/lib/{ => workspace/creation}/new-workspace-enter-guard.ts (100%) rename src/renderer/src/lib/{ => workspace/creation}/new-workspace-project-options.ts (91%) rename src/renderer/src/lib/{ => workspace/creation}/new-workspace-ssh-gate.ts (79%) rename src/renderer/src/lib/{ => workspace/creation}/new-workspace.ts (92%) rename src/renderer/src/lib/{ => workspace/creation}/pending-creation-provisioning-log.ts (95%) rename src/renderer/src/lib/{ => workspace/creation}/project-clone-url-prefill.test.ts (57%) rename src/renderer/src/lib/{ => workspace/creation}/project-clone-url-prefill.ts (83%) rename src/renderer/src/lib/{ => workspace/creation}/project-host-health-detail.ts (86%) rename src/renderer/src/lib/{ => workspace/creation}/project-host-setup-options.ts (93%) rename src/renderer/src/lib/{ => workspace/creation}/project-host-setup-row-dedupe.ts (93%) rename src/renderer/src/lib/{ => workspace/creation}/project-host-workspace-target.jira-mapping.test.ts (95%) rename src/renderer/src/lib/{ => workspace/creation}/project-host-workspace-target.test.ts (95%) rename src/renderer/src/lib/{ => workspace/creation}/project-host-workspace-target.ts (93%) rename src/renderer/src/lib/{ => workspace/creation}/provisioned-root-create-options.ts (90%) rename src/renderer/src/lib/{ => workspace/creation}/quick-workspace-agent-selection.ts (92%) rename src/renderer/src/lib/{ => workspace/creation/setup}/hook-command-delayed-delivery.ts (98%) rename src/renderer/src/lib/{ => workspace/creation/setup}/setup-runner.ts (74%) rename src/renderer/src/lib/{ => workspace/creation/setup}/workspace-setup-trust.ts (73%) rename src/renderer/src/lib/{ => workspace/creation}/workspace-composer-initial-focus.ts (100%) rename src/renderer/src/lib/{ => workspace/creation}/workspace-create-error-format.ts (100%) rename src/renderer/src/{lib => runtime/ephemeral-vm}/ephemeral-vm-environment-check-decision.ts (100%) rename src/renderer/src/{lib => runtime/ephemeral-vm}/ephemeral-vm-environment-check.test.ts (97%) rename src/renderer/src/{lib => runtime/ephemeral-vm}/ephemeral-vm-environment-check.ts (96%) rename src/renderer/src/{lib => runtime/ephemeral-vm}/ephemeral-vm-error-copy.ts (97%) rename src/renderer/src/{lib => runtime/ephemeral-vm}/ephemeral-vm-failed-create-cleanup.ts (95%) rename src/renderer/src/{lib => runtime/ephemeral-vm}/ephemeral-vm-runtime-cleanup.ts (96%) rename src/renderer/src/{lib => runtime/ephemeral-vm}/ephemeral-vm-workspace-target.ts (92%) rename src/renderer/src/{lib => runtime/ephemeral-vm}/recipe-vm-managed-host.ts (87%) rename src/renderer/src/{lib => runtime/ephemeral-vm}/vm-create-hidden-checkouts.test.ts (94%) rename src/renderer/src/{lib => runtime/ephemeral-vm}/vm-create-hidden-checkouts.ts (87%) rename src/renderer/src/{lib => runtime/repo-hooks}/ensure-hooks-confirmed.test.ts (98%) rename src/renderer/src/{lib => runtime/repo-hooks}/ensure-hooks-confirmed.ts (95%) rename src/renderer/src/{lib => runtime/repo-hooks}/issue-command-trust-content.ts (100%) rename src/renderer/src/{lib => runtime/repo-hooks}/orca-hook-trust.ts (85%) rename src/renderer/src/{lib => runtime/repo-hooks}/setup-script-prompt.ts (95%) rename src/renderer/src/{lib => runtime/repo-hooks}/setup-script-status.ts (81%) rename src/renderer/src/{lib => runtime/repo-hooks}/vm-recipe-trust-content.ts (91%) delete mode 100644 tests/e2e/terminal-agent-fork-draft-ownership.unit.test.ts delete mode 100644 tests/e2e/terminal-agent-fork-retained-prefill.test-fixture.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 764a84020c1..b984f4ad50b 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -272,7 +272,6 @@ 1 test-no-real-time-wait:src/renderer/src/components/terminal-pane/viewport/terminal-fit-restore.test.ts 1 test-no-real-time-wait:src/renderer/src/hooks/runtime-project-refresh-scheduler.test.ts 1 test-no-real-time-wait:src/renderer/src/lib/agent-session/resume/cli-fork/native-chat-cli-fork-preparation.test.ts -1 test-no-real-time-wait:src/renderer/src/lib/orca-yaml-trust-prompt-slot-eviction.test.ts 2 test-no-real-time-wait:src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-removal-preflight.test.ts 2 test-no-real-time-wait:src/shared/__tests__/process-host/windows-tree-kill-late-taskkill.win32.test.ts 1 test-no-real-time-wait:src/shared/darwin-process-table-capture.test.ts diff --git a/config/react-compiler-bailout-baseline.txt b/config/react-compiler-bailout-baseline.txt index d5333975431..3dae37fc31e 100644 --- a/config/react-compiler-bailout-baseline.txt +++ b/config/react-compiler-bailout-baseline.txt @@ -705,7 +705,7 @@ 4 src/renderer/src/hooks/skills/freshness/useSkillFreshness.ts 1 src/renderer/src/hooks/useTaskPageGitHubWorkItemMutation.ts 6 src/renderer/src/hooks/useVirtualizedScrollAnchor.ts -1 src/renderer/src/lib/host-chat-program-acquisition.ts +1 src/renderer/src/lib/agent-session/launch/inventory/host-chat-program-acquisition.ts 1 src/renderer/src/lib/quick-open-file-history.ts 2 src/renderer/src/lib/worker-auto-close.ts 1 src/renderer/src/runtime/native-chat/naming/structured-chat-name-observation.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index aaa18a61795..78ecb4e14e3 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -5318,8 +5318,6 @@ "src/renderer/src/components/new-workspace/DirectWorkItemSetupDialog.test.tsx": 5296, "src/renderer/src/components/new-workspace/NewWorkspaceComposerNameSection.test.tsx": 2493, "src/renderer/src/components/new-workspace/ProjectCombobox.dialog-handoff.test.tsx": 1043, - "src/renderer/src/components/new-workspace/ProjectCombobox.test.tsx": 848, - "src/renderer/src/components/new-workspace/ProjectComboboxRow.test.tsx": 415, "src/renderer/src/components/new-workspace/RunTargetCombobox.host-identity.test.tsx": 856, "src/renderer/src/components/new-workspace/SetProjectLocationDialog.host-identity.test.tsx": 1094, "src/renderer/src/components/new-workspace/SetProjectLocationDialog.test.tsx": 1387, @@ -5482,7 +5480,6 @@ "src/renderer/src/components/settings/browser/BrowserUserAgentSetting.test.tsx": 2325, "src/renderer/src/components/settings/chat/ChatNamingSetting.test.tsx": 2454, "src/renderer/src/components/settings/chat/ChatPermissionSetting.test.tsx": 834, - "src/renderer/src/components/settings/chat/ChatSettingsSection.navigation.test.tsx": 2540, "src/renderer/src/components/settings/chat/ChatSettingsSection.test.tsx": 2718, "src/renderer/src/lib/skills/runtime/skill-runtime-command.test.ts": 1670, "src/renderer/src/components/settings/virtual-machines/recipes/EphemeralVmsPane.test.tsx": 1025, @@ -5524,7 +5521,6 @@ "src/renderer/src/components/settings/developer-permissions/developer-permissions-search.test.ts": 308, "src/renderer/src/components/settings/shortcuts/keybinding-diagnostic-text.test.ts": 522, "src/renderer/src/components/settings/shortcuts/keybinding-title-copy.test.ts": 227, - "src/renderer/src/lib/agent-session/launch/native-chat-provider-choice.test.tsx": 3738, "src/renderer/src/components/settings/notifications/notification-host-pending-save.test.tsx": 2029, "src/renderer/src/components/settings/repository/RepositoryJiraProjectSection.test.tsx": 463, "src/renderer/src/components/settings/repository/RepositoryPaneDraftInput.test.tsx": 314, @@ -5957,7 +5953,6 @@ "src/renderer/src/components/terminal-pane/emulation/terminal-capability-replies.test.ts": 131, "src/renderer/src/components/terminal-pane/clipboard/terminal-clipboard-paste.test.ts": 76, "src/renderer/src/components/terminal-pane/parking/retention/terminal-cold-park-timer-rearm.test.tsx": 701, - "src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-handler.test.ts": 638, "src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-image-path.test.ts": 61, "src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-internal-handler.test.ts": 800, "src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-path-writer.test.ts": 245, @@ -6342,7 +6337,7 @@ "src/renderer/src/lib/browser/documents/doc-preview-grants.test.ts": 2094, "src/renderer/src/lib/editor/file-operations/editor-file-operation-owner.test.ts": 2848, "src/renderer/src/lib/emulator-error-copy.test.ts": 415, - "src/renderer/src/lib/ensure-hooks-confirmed.test.ts": 799, + "src/renderer/src/runtime/repo-hooks/ensure-hooks-confirmed.test.ts": 799, "src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts": 3601, "src/renderer/src/runtime/hosts/platform/execution-host-facts.test.ts": 1796, "src/renderer/src/lib/feature-education-telemetry.test.ts": 52, @@ -6353,8 +6348,6 @@ "src/renderer/src/lib/focus-terminal-tab-surface.split-focus.test.ts": 331, "src/renderer/src/lib/foreground-terminal-tabs.test.ts": 55, "src/renderer/src/lib/work-items/github/github-source-runtime-context.test.ts": 62, - "src/renderer/src/lib/hook-command-delayed-delivery.test.ts": 1904, - "src/renderer/src/lib/host-chat-program.test.ts": 2419, "src/renderer/src/lib/host-mirror-handle-gap-drain.test.ts": 1706, "src/renderer/src/lib/host-mirror-handle-gap-resume.test.ts": 1811, "src/renderer/src/lib/host-mirrored-pane-resume-replay.test.ts": 1814, @@ -6399,12 +6392,8 @@ "src/renderer/src/lib/monaco-languages/textmate-token-provider.test.ts": 245, "src/renderer/src/lib/monaco-languages/zig-highlighting.test.ts": 7984, "src/renderer/src/lib/agent-session/resume/cli-fork/native-chat-cli-fork-preparation.test.ts": 2773, - "src/renderer/src/lib/new-workspace.test.ts": 4534, - "src/renderer/src/lib/non-secure-context-crypto.repro.test.ts": 1691, - "src/renderer/src/lib/onboarding-folder-cancellation.test.ts": 2486, "src/renderer/src/lib/open-agent-message-sender.test.ts": 1497, "src/renderer/src/lib/simulator/launch/open-mobile-emulator-tab.test.ts": 545, - "src/renderer/src/lib/orca-yaml-trust-prompt-slot-eviction.test.ts": 884, "src/renderer/src/lib/order-empty-query-worktrees.test.ts": 62, "src/renderer/src/lib/os-file-drop-cancellation-guard.test.ts": 204, "src/renderer/src/lib/os-file-drop-preload-integration.test.tsx": 353, @@ -6476,9 +6465,9 @@ "src/renderer/src/lib/plugin-monaco-token-rules.test.ts": 51, "src/renderer/src/lib/source-control/review/pr-bot-author-overrides.test.ts": 349, "src/renderer/src/lib/source-control/review/comments/pr-comment-thread-resolution.test.ts": 48, - "src/renderer/src/lib/project-clone-url-prefill.test.ts": 61, - "src/renderer/src/lib/project-host-workspace-target.jira-mapping.test.ts": 76, - "src/renderer/src/lib/project-host-workspace-target.test.ts": 92, + "src/renderer/src/lib/workspace/creation/project-clone-url-prefill.test.ts": 61, + "src/renderer/src/lib/workspace/creation/project-host-workspace-target.jira-mapping.test.ts": 76, + "src/renderer/src/lib/workspace/creation/project-host-workspace-target.test.ts": 92, "src/renderer/src/lib/react-commit-cascade-observer.react185.test.tsx": 285, "src/renderer/src/lib/react-commit-cascade-observer.test.ts": 189, "src/renderer/src/lib/react-commit-cascade-telemetry.test.ts": 159, @@ -6519,7 +6508,6 @@ "src/renderer/src/lib/simulator/tabs/simulator-pane-shutdown-scheduler.test.ts": 1679, "src/renderer/src/lib/simulator/tabs/simulator-tab-layout-owner.test.ts": 2398, "src/renderer/src/lib/simulator/tabs/simulator-tab-palette-activation.test.ts": 1903, - "src/renderer/src/lib/sleeping-agent-session-launch-windows-quoting.test.ts": 547, "src/renderer/src/lib/source-control/remote/source-control-remote-error.test.ts": 340, "src/renderer/src/lib/ssh-config-passive-sync.test.ts": 1513, "src/renderer/src/lib/state-collection-byte-estimate.test.ts": 86, @@ -8045,7 +8033,6 @@ "tests/e2e/sustained-agent-typing-load-scripts.unit.test.ts": 2169, "tests/e2e/task-page-linear-refresh-authority.unit.test.ts": 5548, "tests/e2e/task-page-linear-refresh-transport.unit.test.ts": 2019, - "tests/e2e/terminal-agent-fork-draft-ownership.unit.test.ts": 30195, "tests/e2e/terminal-binding-crash-hydration.unit.test.ts": 1769, "tests/e2e/terminal-foreground-confirmation.unit.test.ts": 644, "tests/e2e/terminal-perf-presentation.unit.test.ts": 60, diff --git a/config/scripts/test-runtime/execution-policy/vitest-shared-worker-setup-runner.mjs b/config/scripts/test-runtime/execution-policy/vitest-shared-worker-setup-runner.mjs new file mode 100644 index 00000000000..1b41d2349cc --- /dev/null +++ b/config/scripts/test-runtime/execution-policy/vitest-shared-worker-setup-runner.mjs @@ -0,0 +1,16 @@ +import { TestRunner } from 'vitest' + +export default class SharedWorkerSetupRunner extends TestRunner { + importFile(filepath, source) { + if (source === 'setup') { + // Warm transforms can key setup roots by a different URL than Vitest invalidates. + const modules = this.moduleRunner.evaluatedModules + for (const node of modules.getModulesByFile(filepath) ?? []) { + if (node.evaluated) { + modules.invalidateModule(node) + } + } + } + return super.importFile(filepath, source) + } +} diff --git a/config/tsconfig.node.json b/config/tsconfig.node.json index 563748d8a33..5702c01cc47 100644 --- a/config/tsconfig.node.json +++ b/config/tsconfig.node.json @@ -23,7 +23,7 @@ "../src/cli/runtime/runtime-access-denied.ts", "../src/cli/runtime/runtime-pid-liveness.ts", "../src/renderer/src/store/slices/worktrees/create/worktree-create-payload.ts", - "../src/renderer/src/lib/orca-hook-trust.ts", + "../src/renderer/src/runtime/repo-hooks/orca-hook-trust.ts", "../src/renderer/src/lib/sha256.ts", "../src/renderer/src/components/native-chat/native-chat-resolution-receipt.ts", "../src/renderer/src/components/native-chat/structured-agent-question-projection.ts", diff --git a/config/vitest.config.ts b/config/vitest.config.ts index eab54372357..bfed0dadfdd 100644 --- a/config/vitest.config.ts +++ b/config/vitest.config.ts @@ -153,6 +153,9 @@ const sharedProjects = name: `${runtimeProject.test.name}-shared`, include: sharedWorkerFiles, isolate: false, + runner: resolve( + 'config/scripts/test-runtime/execution-policy/vitest-shared-worker-setup-runner.mjs' + ), setupFiles: [ ...runtimeProject.test.setupFiles, resolve('config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.mjs') diff --git a/src/main/workspace-hooks/created-worktree-setup-trust-parity.test.ts b/src/main/workspace-hooks/created-worktree-setup-trust-parity.test.ts index 8a52338b972..5be81369820 100644 --- a/src/main/workspace-hooks/created-worktree-setup-trust-parity.test.ts +++ b/src/main/workspace-hooks/created-worktree-setup-trust-parity.test.ts @@ -4,7 +4,7 @@ import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { getSetupTrustContent } from '../../shared/orca-hook-setup-config' -import '../../renderer/src/lib/orca-hook-trust' +import '../../renderer/src/runtime/repo-hooks/orca-hook-trust' import '../runtime/repositories/runtime-repository-hooks-commands' import { loadHooks } from './hooks' import { hashOrcaHookTrustContent } from './created-worktree-setup-trust' diff --git a/src/renderer/src/components/NewWorkspaceComposerCard.tsx b/src/renderer/src/components/NewWorkspaceComposerCard.tsx index 514a3b90408..3a898de67f3 100644 --- a/src/renderer/src/components/NewWorkspaceComposerCard.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerCard.tsx @@ -5,7 +5,7 @@ import { useAppStore } from '@/store' import { cn } from '@/lib/utils' import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' import { getScreenSubmitModifierLabel } from '@/lib/screen-submit-shortcut' -import { resolveProjectCloneUrlPrefill } from '@/lib/project-clone-url-prefill' +import { resolveProjectCloneUrlPrefill } from '@/lib/workspace/creation/project-clone-url-prefill' import { useContextualTour } from '@/components/contextual-tours/use-contextual-tour' import { AddRemoteHostDialog, diff --git a/src/renderer/src/components/NewWorkspaceComposerModal.tsx b/src/renderer/src/components/NewWorkspaceComposerModal.tsx index 1c0169e1b1b..c0a27c4122c 100644 --- a/src/renderer/src/components/NewWorkspaceComposerModal.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerModal.tsx @@ -3,13 +3,13 @@ import { toast } from 'sonner' import { formatWorkspaceCreateError, getWorkspaceCreateErrorToastMessage -} from '@/lib/workspace-create-error-format' +} from '@/lib/workspace/creation/workspace-create-error-format' import type { AgentPickerDraft, AgentPickerEntry } from '../../../shared/agent-launch/picker/agent-launch-picker' import { DirectWorkItemSetupDialog } from './new-workspace/DirectWorkItemSetupDialog' -import { agentChoicePending } from '@/lib/host-chat-program' +import { agentChoicePending } from '@/lib/agent-session/launch/inventory/host-chat-program' import type { AgentLaunchSurface } from '@/lib/agent-session/launch/routing/agent-session-launch-plan' import React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useAppStore } from '@/store/index' @@ -32,14 +32,14 @@ import { quickWorkspacePickerInputs, pickQuickWorkspaceAgent, resolveQuickWorkspaceAgentSelection -} from '@/lib/quick-workspace-agent-selection' -import { useAgentsOfferedForLaunch } from '@/lib/host-chat-program-acquisition' -import { shouldAllowComposerEnterSubmitTarget } from '@/lib/new-workspace-enter-guard' +} from '@/lib/workspace/creation/quick-workspace-agent-selection' +import { useAgentsOfferedForLaunch } from '@/lib/agent-session/launch/inventory/host-chat-program-acquisition' +import { shouldAllowComposerEnterSubmitTarget } from '@/lib/workspace/creation/new-workspace-enter-guard' import { isScreenSubmitShortcut } from '@/lib/screen-submit-shortcut' import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' -import { getWorkspaceComposerInitialFocusTarget } from '@/lib/workspace-composer-initial-focus' +import { getWorkspaceComposerInitialFocusTarget } from '@/lib/workspace/creation/workspace-composer-initial-focus' import '@/components/sidebar/workspace-creation/folder/folder-workspace-source-repos' import { getFolderWorkspacePrimaryActionLabel } from '@/components/sidebar/workspace-creation/folder/folder-workspace-source-selection' import { useAgentMenuObservation } from '@/components/tab-bar/use-new-tab-agent-menu-rows' diff --git a/src/renderer/src/components/agent-session-continuation/AgentSessionContinuationDialog.tsx b/src/renderer/src/components/agent-session-continuation/AgentSessionContinuationDialog.tsx index 73eae33015f..8af089829b8 100644 --- a/src/renderer/src/components/agent-session-continuation/AgentSessionContinuationDialog.tsx +++ b/src/renderer/src/components/agent-session-continuation/AgentSessionContinuationDialog.tsx @@ -1,5 +1,5 @@ import { useAgentPickerDraftScope } from '../agent/AgentLaunchSetupButton' -import { agentsOfferedForLaunch } from '@/lib/host-chat-program' +import { agentsOfferedForLaunch } from '@/lib/agent-session/launch/inventory/host-chat-program' import { worktreeLaunchWorkspace } from '@/lib/agent-session/launch/routing/agent-launch-route-input' import { useEffect, useRef, useState } from 'react' import { Loader2, MessageSquarePlus } from 'lucide-react' diff --git a/src/renderer/src/components/automations/authoring/AutomationEditorDialog.tsx b/src/renderer/src/components/automations/authoring/AutomationEditorDialog.tsx index 55e3087582b..45e34130a12 100644 --- a/src/renderer/src/components/automations/authoring/AutomationEditorDialog.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationEditorDialog.tsx @@ -2,7 +2,7 @@ import type { AutomationAuthorityRef } from '../../../../../shared/automations/o import React from 'react' import { useAppStore } from '@/store/index' import { selectAgentLaunchRouteView } from '@/lib/agent-session/launch/routing/agent-launch-route-input' -import { useChatProgramFacts } from '@/lib/host-chat-program-acquisition' +import { useChatProgramFacts } from '@/lib/agent-session/launch/inventory/host-chat-program-acquisition' import { automationChatSupport, automationDraftSurface, diff --git a/src/renderer/src/components/automations/authoring/automation-orca-save.ts b/src/renderer/src/components/automations/authoring/automation-orca-save.ts index eb6de9e658b..e2dd43ee641 100644 --- a/src/renderer/src/components/automations/authoring/automation-orca-save.ts +++ b/src/renderer/src/components/automations/authoring/automation-orca-save.ts @@ -17,7 +17,7 @@ import type { AutomationUpdateInput } from '../../../../../shared/automations/automation-definition' import { getRepoExecutionHostId } from '../../../../../shared/execution-host' -import { ensureHooksApproved } from '@/lib/ensure-hooks-confirmed' +import { ensureHooksApproved } from '@/runtime/repo-hooks/ensure-hooks-confirmed' import { translate } from '@/i18n/i18n' import { useAppStore } from '@/store/index' import { listAutomationsForTarget } from '../hosts/automation-host-client' diff --git a/src/renderer/src/components/automations/authoring/automation-setup-review.ts b/src/renderer/src/components/automations/authoring/automation-setup-review.ts index f93f37175cb..280510157b4 100644 --- a/src/renderer/src/components/automations/authoring/automation-setup-review.ts +++ b/src/renderer/src/components/automations/authoring/automation-setup-review.ts @@ -5,7 +5,7 @@ import { confirmCreatedWorktreeSetupContent, ensureHooksApproved, type HookTrustApproval -} from '@/lib/ensure-hooks-confirmed' +} from '@/runtime/repo-hooks/ensure-hooks-confirmed' import type { AutomationSaveContext } from './automation-save-context' import type { Automation } from '../../../../../shared/automations/automation-definition' import type { AutomationUsageSummary } from '../../../../../shared/automations/history/automation-usage-summary' diff --git a/src/renderer/src/components/automations/automations-page-test-harness.tsx b/src/renderer/src/components/automations/automations-page-test-harness.tsx index 309adc4fed9..cab3577d27c 100644 --- a/src/renderer/src/components/automations/automations-page-test-harness.tsx +++ b/src/renderer/src/components/automations/automations-page-test-harness.tsx @@ -113,7 +113,7 @@ vi.mock('@/runtime/repo-hooks/runtime-hooks-client', () => ({ checkRuntimeHooks: vi.fn(async () => ({ hooks: null, ok: true })) })) -vi.mock('@/lib/ensure-hooks-confirmed', () => ({ +vi.mock('@/runtime/repo-hooks/ensure-hooks-confirmed', () => ({ ensureHooksConfirmed: vi.fn(async () => 'inherit'), ensureHooksApproved: vi.fn(async () => ({ decision: 'run' })) })) diff --git a/src/renderer/src/components/cmd-j/task-search-activation.ts b/src/renderer/src/components/cmd-j/task-search-activation.ts index 2b7989e3d56..09b8445c942 100644 --- a/src/renderer/src/components/cmd-j/task-search-activation.ts +++ b/src/renderer/src/components/cmd-j/task-search-activation.ts @@ -6,11 +6,12 @@ import { parseWorkspaceReferenceUrl } from '../../../../shared/workspace-attachments/workspace-reference-identity' import { getLinearIssueWorkspaceName } from '../../../../shared/workspace-name' +import '@/lib/workspace/creation/new-workspace' import { getLinkedWorkItemWorkspaceName, - getLinkedWorkItemSuggestedName, - type LinkedWorkItemSummary -} from '@/lib/new-workspace' + getLinkedWorkItemSuggestedName +} from '../../../../shared/workspace-name' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' import { buildLinearIssueLinkedWorkItem } from '@/lib/work-items/linear/linear-linked-work-item' import type { Worktree } from '../../../../shared/worktree/types' import { diff --git a/src/renderer/src/components/dashboard/dashboard-chat-program-acquisition.ts b/src/renderer/src/components/dashboard/dashboard-chat-program-acquisition.ts index b3f8308d39c..a6f29976a82 100644 --- a/src/renderer/src/components/dashboard/dashboard-chat-program-acquisition.ts +++ b/src/renderer/src/components/dashboard/dashboard-chat-program-acquisition.ts @@ -1,6 +1,6 @@ import type { AppState } from '@/store/types' -import { holdChatProgramFacts } from '@/lib/host-chat-program-acquisition' -import { resolveChatProgramContext } from '@/lib/host-chat-program' +import { holdChatProgramFacts } from '@/lib/agent-session/launch/inventory/host-chat-program-acquisition' +import { resolveChatProgramContext } from '@/lib/agent-session/launch/inventory/host-chat-program' import { selectAgentLaunchRouteView, worktreeLaunchWorkspace diff --git a/src/renderer/src/components/dashboard/dashboard-worktree-launch-options.ts b/src/renderer/src/components/dashboard/dashboard-worktree-launch-options.ts index 76eaa73c76e..7e6e7dab48b 100644 --- a/src/renderer/src/components/dashboard/dashboard-worktree-launch-options.ts +++ b/src/renderer/src/components/dashboard/dashboard-worktree-launch-options.ts @@ -17,7 +17,7 @@ import { worktreeLaunchWorkspace, type AgentLaunchRouteView } from '@/lib/agent-session/launch/routing/agent-launch-route-input' -import { agentsOfferedForLaunch } from '@/lib/host-chat-program' +import { agentsOfferedForLaunch } from '@/lib/agent-session/launch/inventory/host-chat-program' import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' export type DashboardLaunchDetectionState = Pick< diff --git a/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts index 17247a60c28..73539bed721 100644 --- a/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts +++ b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts @@ -6,7 +6,7 @@ import { subscribeStructuredChatTabNames, getStructuredChatTabNames } from '@/runtime/native-chat/naming/structured-chat-name-observation' -import { subscribeChatProgramFacts } from '@/lib/host-chat-program' +import { subscribeChatProgramFacts } from '@/lib/agent-session/launch/inventory/host-chat-program' import { type AgentLaunchRouteView, agentLaunchRouteInputsChanged, diff --git a/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts b/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts index bb2225f0e39..548b3ed1f8a 100644 --- a/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts +++ b/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts @@ -5,7 +5,7 @@ import { useAppStore } from '@/store' import { useStructuredChatTabNames } from '@/runtime/native-chat/naming/structured-chat-name-observation' import type { DashboardSnapshot } from '../../../../shared/dashboard-snapshot' import { buildDashboardSnapshot } from './build-dashboard-snapshot' -import { useChatProgramFactsVersion } from '@/lib/host-chat-program-acquisition' +import { useChatProgramFactsVersion } from '@/lib/agent-session/launch/inventory/host-chat-program-acquisition' import { createWorktreeAgentRowsCache } from './worktree-agent-rows-cache' import { selectAgentLaunchRouteView } from '@/lib/agent-session/launch/routing/agent-launch-route-input' import { diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.fixture.tsx b/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.fixture.tsx index b4b91dc4cd5..66ba61079d7 100644 --- a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.fixture.tsx +++ b/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.fixture.tsx @@ -1,10 +1,10 @@ import { useState } from 'react' import { defineFixture } from '../../component-fixtures/component-fixture' -import type { NewWorkspaceProjectOption } from '@/lib/new-workspace-project-options' +import type { NewWorkspaceProjectOption } from '@/lib/workspace/creation/new-workspace-project-options' import { getProjectHostSetupSelectionKey, type ProjectHostSetupOption -} from '@/lib/project-host-setup-options' +} from '@/lib/workspace/creation/project-host-setup-options' import { NewWorkspaceComposerProjectSection } from './NewWorkspaceComposerProjectSection' const projects: NewWorkspaceProjectOption[] = [ diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx b/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx index 66053fe642a..b4896ecbffe 100644 --- a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx +++ b/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx @@ -6,7 +6,7 @@ import ProjectCombobox from '@/components/new-workspace/ProjectCombobox' import RunTargetCombobox from '@/components/new-workspace/RunTargetCombobox' import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' -import { getSelectedNewWorkspaceProjectOptionId } from '@/lib/new-workspace-project-options' +import { getSelectedNewWorkspaceProjectOptionId } from '@/lib/workspace/creation/new-workspace-project-options' import type { EphemeralVmRecipeOption, NeedsProjectHostOption, diff --git a/src/renderer/src/components/new-workspace/ProjectCombobox.test.tsx b/src/renderer/src/components/new-workspace/ProjectCombobox.test.tsx deleted file mode 100644 index 80833845fcd..00000000000 --- a/src/renderer/src/components/new-workspace/ProjectCombobox.test.tsx +++ /dev/null @@ -1,171 +0,0 @@ -// @vitest-environment happy-dom - -import React, { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { NewWorkspaceProjectOption } from '@/lib/new-workspace-project-options' -import ProjectCombobox from './ProjectCombobox' -import { TooltipProvider } from '@/components/ui/tooltip' - -// Render inline and expose Radix-style close independently of the component key handler. -vi.mock('@/components/ui/popover', () => ({ - Popover: ({ - children, - onOpenChange - }: { - children: React.ReactNode - onOpenChange?: (open: boolean) => void - }) => ( -
-
- ), - PopoverAnchor: ({ children }: { children: React.ReactNode }) => <>{children}, - PopoverContent: ({ children }: { children: React.ReactNode }) =>
{children}
-})) - -vi.mock('./use-recent-project-ids', () => ({ useRecentProjectIds: () => [] })) - -let container: HTMLDivElement -let root: Root - -function renderField(element: React.ReactNode): void { - root.render({element}) -} - -const projects: NewWorkspaceProjectOption[] = [ - { - kind: 'project', - id: 'github:stablyai/orca', - projectId: 'github:stablyai/orca', - displayName: 'orca', - badgeColor: '#111111', - detail: 'stablyai/orca' - }, - { - kind: 'project', - id: 'github:stablyai/noqa', - projectId: 'github:stablyai/noqa', - displayName: 'noqa', - badgeColor: '#222222', - detail: 'stablyai/noqa' - }, - { - kind: 'project-group', - id: 'project-group:folder-group', - projectGroupId: 'folder-group', - displayName: 'Platform', - badgeColor: '#333333', - detail: '/tmp/platform', - parentPath: '/tmp/platform', - connectionId: null - } -] - -function field(): HTMLInputElement { - const node = container.querySelector( - 'input[data-project-combobox-root="true"][role="combobox"]' - ) - if (!node) { - throw new Error('project combobox field not found') - } - return node -} - -function openList(): void { - act(() => { - field().focus() - }) -} - -function type(value: string): void { - const input = field() - act(() => { - const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set - setter?.call(input, value) - input.dispatchEvent(new Event('input', { bubbles: true })) - }) -} - -beforeEach(() => { - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) -}) - -afterEach(() => { - act(() => { - root.unmount() - }) - container.remove() -}) - -describe('ProjectCombobox', () => { - it('arms "Add project" when a query matches nothing, so Enter is never a wrong guess', () => { - const onAddProject = vi.fn() - const onValueChange = vi.fn() - - act(() => { - renderField( - - ) - }) - openList() - type('zzzznomatch') - act(() => { - field().dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })) - }) - - expect(onAddProject).toHaveBeenCalledTimes(1) - expect(onValueChange).not.toHaveBeenCalled() - }) - - // Sectioning sinks folders below projects; raw rank would arm the bottom row and Enter would choose the wrong project. - const sectionedOptions: NewWorkspaceProjectOption[] = [ - ...Array.from({ length: 5 }, (_, index) => ({ - kind: 'project' as const, - id: `project-${index}`, - projectId: `project-${index}`, - displayName: `svc-${index}`, - badgeColor: '#111111', - detail: `stablyai/svc-${index}` - })), - { - kind: 'project-group', - id: 'project-group:apps', - projectGroupId: 'apps', - displayName: 'Apps', - badgeColor: '#333333', - detail: '/tmp/apps', - parentPath: '/tmp/apps', - connectionId: null - } - ] - - it('commits the top row on Enter rather than the folder group sectioned to the bottom', () => { - const onValueChange = vi.fn() - - act(() => { - renderField( - - ) - }) - act(() => { - container - .querySelector('[data-project-combobox-root="true"]') - ?.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) - act(() => { - field().dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })) - }) - - expect(onValueChange).toHaveBeenCalledWith('project-0') - expect(onValueChange).not.toHaveBeenCalledWith('project-group:apps') - }) -}) diff --git a/src/renderer/src/components/new-workspace/ProjectCombobox.tsx b/src/renderer/src/components/new-workspace/ProjectCombobox.tsx index f89e9096d50..43a1272ac13 100644 --- a/src/renderer/src/components/new-workspace/ProjectCombobox.tsx +++ b/src/renderer/src/components/new-workspace/ProjectCombobox.tsx @@ -4,7 +4,7 @@ import { ChevronDown, FolderPlus } from 'lucide-react' import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover' import { cn } from '@/lib/utils' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import type { NewWorkspaceProjectOption } from '@/lib/new-workspace-project-options' +import type { NewWorkspaceProjectOption } from '@/lib/workspace/creation/new-workspace-project-options' import { useTranslate } from '@/i18n/use-translate' import { getAmbiguousProjectOptionIds, diff --git a/src/renderer/src/components/new-workspace/ProjectComboboxRow.test.tsx b/src/renderer/src/components/new-workspace/ProjectComboboxRow.test.tsx deleted file mode 100644 index 7b3850dce98..00000000000 --- a/src/renderer/src/components/new-workspace/ProjectComboboxRow.test.tsx +++ /dev/null @@ -1,52 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { MatchedText } from './ProjectComboboxRow' -import { rankProjectOptions } from './project-combobox-matching' -import type { NewWorkspaceProjectOption } from '@/lib/new-workspace-project-options' - -let container: HTMLDivElement -let root: Root - -beforeEach(() => { - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) -}) - -afterEach(() => { - act(() => { - root.unmount() - }) - container.remove() -}) - -function markedText(): string { - return Array.from(container.querySelectorAll('mark')) - .map((mark) => mark.textContent ?? '') - .join('') -} - -describe('MatchedText', () => { - // UTF-16 hit offsets and code-point rendering differ for emoji; marks must stay on the matched glyphs. - it('aligns marks with the query when the name starts with an emoji', () => { - const option: NewWorkspaceProjectOption = { - kind: 'project', - id: 'p1', - projectId: 'p1', - displayName: '🚀 orca', - badgeColor: '#111111', - detail: '~/dev/orca' - } - const [match] = rankProjectOptions([option], 'orca', []) - expect(match).toBeDefined() - - act(() => { - root.render() - }) - - expect(markedText()).toBe('orca') - }) -}) diff --git a/src/renderer/src/components/new-workspace/ProjectComboboxRow.tsx b/src/renderer/src/components/new-workspace/ProjectComboboxRow.tsx index 9cf579f7669..07f084687f7 100644 --- a/src/renderer/src/components/new-workspace/ProjectComboboxRow.tsx +++ b/src/renderer/src/components/new-workspace/ProjectComboboxRow.tsx @@ -2,7 +2,7 @@ import React from 'react' import { FolderOpen } from 'lucide-react' import { RepoBadgeMark } from '@/components/repo/RepoBadgeLabel' import { cn } from '@/lib/utils' -import type { NewWorkspaceProjectOption } from '@/lib/new-workspace-project-options' +import type { NewWorkspaceProjectOption } from '@/lib/workspace/creation/new-workspace-project-options' import { splitPathHeadForElision } from '@/lib/path-head-elision' /** Identity mark shared by the field and every row, so a project reads the same in both. */ diff --git a/src/renderer/src/components/new-workspace/RunTargetCombobox.fixture.tsx b/src/renderer/src/components/new-workspace/RunTargetCombobox.fixture.tsx index 9dc75e7c7d9..84fd7478975 100644 --- a/src/renderer/src/components/new-workspace/RunTargetCombobox.fixture.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetCombobox.fixture.tsx @@ -1,5 +1,5 @@ import { defineFixture } from '../../component-fixtures/component-fixture' -import type { ProjectHostSetupOption } from '@/lib/project-host-setup-options' +import type { ProjectHostSetupOption } from '@/lib/workspace/creation/project-host-setup-options' import RunTargetCombobox from './RunTargetCombobox' // Shape produced by buildProjectHostSetupOptions with local + ephemeral VM setups and SSH hosts: diff --git a/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx b/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx index a655c4c9e1f..3703c5253dc 100644 --- a/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx @@ -7,7 +7,7 @@ import { type NeedsSetupProjectHostOption, type ProjectHostSetupOption, type ReadyProjectHostSetupOption -} from '@/lib/project-host-setup-options' +} from '@/lib/workspace/creation/project-host-setup-options' import type { ExecutionHostId } from '../../../../shared/execution-host' import { isWithinComboboxRoot, useTypeAheadCombobox } from './use-type-ahead-combobox' import { COMBOBOX_POPOVER_SURFACE } from './type-ahead-combobox-styles' diff --git a/src/renderer/src/components/new-workspace/RunTargetRowList.tsx b/src/renderer/src/components/new-workspace/RunTargetRowList.tsx index 355fd0439cc..b2b7d7d4195 100644 --- a/src/renderer/src/components/new-workspace/RunTargetRowList.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetRowList.tsx @@ -2,7 +2,7 @@ import React from 'react' import type { NeedsSetupProjectHostOption, ReadyProjectHostSetupOption -} from '@/lib/project-host-setup-options' +} from '@/lib/workspace/creation/project-host-setup-options' import { HostRowIcon, RunTargetRow } from './RunTargetComboboxRow' import { ConnectHostButton, NeedsSetupHostIcon, SetLocationButton } from './RunTargetRowActions' import { RecipesSubmenuRow } from './RunTargetSubmenus' diff --git a/src/renderer/src/components/new-workspace/SetProjectLocationDialog.test.tsx b/src/renderer/src/components/new-workspace/SetProjectLocationDialog.test.tsx index e9b7564e596..b0f0c919da5 100644 --- a/src/renderer/src/components/new-workspace/SetProjectLocationDialog.test.tsx +++ b/src/renderer/src/components/new-workspace/SetProjectLocationDialog.test.tsx @@ -1,10 +1,10 @@ // @vitest-environment happy-dom -import { act, cleanup, render, screen } from '@testing-library/react' +import { cleanup, render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' -import { StrictMode, type ComponentProps } from 'react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { NeedsSetupProjectHostOption } from '@/lib/project-host-setup-options' +import type { ComponentProps } from 'react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { NeedsSetupProjectHostOption } from '@/lib/workspace/creation/project-host-setup-options' const storeMocks = vi.hoisted(() => ({ setupProjectExistingFolder: vi.fn(), @@ -68,17 +68,6 @@ function renderDialog( return user } -beforeEach(() => { - storeMocks.setupProjectExistingFolder.mockReset() - storeMocks.setupProjectClone.mockReset() - storeMocks.setupProjectExistingFolder.mockResolvedValue({ - setup: { id: 'setup-openclaw' } - }) - storeMocks.setupProjectClone.mockResolvedValue({ - setup: { id: 'setup-openclaw-clone' } - }) -}) - afterEach(() => { cleanup() }) @@ -101,70 +90,4 @@ describe('SetProjectLocationDialog', () => { await user.keyboard('{Escape}') expect(onClose).toHaveBeenCalled() }) - - it('does not retarget the composer when a slow clone lands after dismissal', async () => { - // An SSH clone is unbounded and the dialog stays dismissable while it runs. - let finishClone: (result: { setup: { id: string } }) => void = () => {} - storeMocks.setupProjectClone.mockReturnValue( - new Promise((resolve) => { - finishClone = resolve - }) - ) - const onReady = vi.fn() - const onClose = vi.fn() - const { rerender } = render( - - ) - const user = userEvent.setup() - - await user.click(screen.getByRole('button', { name: /Clone from URL/ })) - await user.type(screen.getByPlaceholderText('/destination/on/host'), '/remote/orca') - await user.click(screen.getByRole('button', { name: 'Clone' })) - - rerender( - - ) - await act(async () => { - finishClone({ setup: { id: 'setup-openclaw-clone' } }) - }) - - expect(onReady).not.toHaveBeenCalled() - }) - - it('still reports success under StrictMode double-invoked effects', async () => { - const onReady = vi.fn() - render( - - - - ) - const user = userEvent.setup() - - await user.click(screen.getByRole('button', { name: /Browse folder/ })) - await user.type(screen.getByPlaceholderText('/path/to/project/on/host'), '/remote/orca') - await user.click(screen.getByRole('button', { name: 'Set location' })) - - expect(onReady).toHaveBeenCalledWith(JSON.stringify(['setup-openclaw', 'ssh:openclaw'])) - }) }) diff --git a/src/renderer/src/components/new-workspace/SetProjectLocationDialog.tsx b/src/renderer/src/components/new-workspace/SetProjectLocationDialog.tsx index 1fc7424bee0..34567bbe71a 100644 --- a/src/renderer/src/components/new-workspace/SetProjectLocationDialog.tsx +++ b/src/renderer/src/components/new-workspace/SetProjectLocationDialog.tsx @@ -15,7 +15,7 @@ import { CreateProjectParentBrowser } from '@/components/sidebar/project-admissi import { getProjectHostSetupSelectionKey, type NeedsSetupProjectHostOption -} from '@/lib/project-host-setup-options' +} from '@/lib/workspace/creation/project-host-setup-options' import { parseExecutionHostId } from '../../../../shared/execution-host' import type { RepoKind } from '../../../../shared/repo-types' import { pickLocalProjectLocationFolder } from './pick-local-project-folder' diff --git a/src/renderer/src/components/new-workspace/composer-modal-data.ts b/src/renderer/src/components/new-workspace/composer-modal-data.ts index 482ac94c762..f81fdbf4d6b 100644 --- a/src/renderer/src/components/new-workspace/composer-modal-data.ts +++ b/src/renderer/src/components/new-workspace/composer-modal-data.ts @@ -4,13 +4,13 @@ import type { } from '../../../../shared/agent-launch/picker/agent-launch-picker' import type { AgentLaunchSurface } from '@/lib/agent-session/launch/routing/agent-session-launch-plan' import type { DirectWorkItemSetupRequest } from '@/lib/workspace/creation/work-item/direct-work-item-setup' -import type { LinkedWorkItemSummary } from '@/lib/new-workspace' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' import type { GitHubWorkItem } from '../../../../shared/github/work-item-types' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' import type { WorkspaceSource as WorkspaceCreateTelemetrySource } from '../../../../shared/workspace-source' import type { WorkspaceStatus } from '../../../../shared/worktree/types' import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context' -import type { WorkspaceCreationTargetHint } from '@/lib/project-host-workspace-target' +import type { WorkspaceCreationTargetHint } from '@/lib/workspace/creation/project-host-workspace-target' export type ComposerModalData = { recovery?: { diff --git a/src/renderer/src/components/new-workspace/new-workspace-composer-card-props.ts b/src/renderer/src/components/new-workspace/new-workspace-composer-card-props.ts index e0224f81fa8..303035685fd 100644 --- a/src/renderer/src/components/new-workspace/new-workspace-composer-card-props.ts +++ b/src/renderer/src/components/new-workspace/new-workspace-composer-card-props.ts @@ -5,13 +5,13 @@ import type { import type { AgentComboboxSurfaceRows } from '@/components/agent/agent-combobox-surface-items' import type { ComposerAgentRows } from '@/hooks/composer-state/composer-agent-rows-target' import type RepoCombobox from '@/components/repo/RepoCombobox' -import type { NewWorkspaceProjectOption } from '@/lib/new-workspace-project-options' +import type { NewWorkspaceProjectOption } from '@/lib/workspace/creation/new-workspace-project-options' import type { NeedsSetupProjectHostOption, ProjectHostSetupOption -} from '@/lib/project-host-setup-options' +} from '@/lib/workspace/creation/project-host-setup-options' import type { SetupConfig } from '../../../../shared/orca-hook-setup-config' -import type { WorkspaceCreateErrorDisplay } from '@/lib/workspace-create-error-format' +import type { WorkspaceCreateErrorDisplay } from '@/lib/workspace/creation/workspace-create-error-format' import type { SmartNameMode } from '../../../../shared/new-workspace/smart-workspace-source-results' import type SmartWorkspaceNameField from './SmartWorkspaceNameField' import type { SmartWorkspaceNameSelection } from '@/components/new-workspace/smart-workspace-name-field-model' diff --git a/src/renderer/src/components/new-workspace/project-combobox-matching.ts b/src/renderer/src/components/new-workspace/project-combobox-matching.ts index 4d50f15f0fb..5fe4974610f 100644 --- a/src/renderer/src/components/new-workspace/project-combobox-matching.ts +++ b/src/renderer/src/components/new-workspace/project-combobox-matching.ts @@ -1,5 +1,5 @@ -import type { NewWorkspaceProjectOption } from '@/lib/new-workspace-project-options' -import { isNewWorkspaceProjectOptionQueryTooLarge } from '@/lib/new-workspace-project-options' +import type { NewWorkspaceProjectOption } from '@/lib/workspace/creation/new-workspace-project-options' +import { isNewWorkspaceProjectOptionQueryTooLarge } from '@/lib/workspace/creation/new-workspace-project-options' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/new-workspace/run-target-options.ts b/src/renderer/src/components/new-workspace/run-target-options.ts index 47a65e5f79d..620b0da9f32 100644 --- a/src/renderer/src/components/new-workspace/run-target-options.ts +++ b/src/renderer/src/components/new-workspace/run-target-options.ts @@ -4,7 +4,7 @@ import { type NeedsSetupProjectHostOption, type ProjectHostSetupOption, type ReadyProjectHostSetupOption -} from '@/lib/project-host-setup-options' +} from '@/lib/workspace/creation/project-host-setup-options' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import { boundHostList } from '@/components/host-picker/bounded-host-list' diff --git a/src/renderer/src/components/new-workspace/use-recent-project-ids.ts b/src/renderer/src/components/new-workspace/use-recent-project-ids.ts index fd282fe17c9..b444193e79a 100644 --- a/src/renderer/src/components/new-workspace/use-recent-project-ids.ts +++ b/src/renderer/src/components/new-workspace/use-recent-project-ids.ts @@ -1,7 +1,7 @@ import { useMemo } from 'react' import type { Worktree } from '../../../../shared/worktree/types' import { useAllWorktrees } from '@/store/slices/worktrees/listing/use-worktree-catalog' -import { NEW_WORKSPACE_PROJECT_GROUP_OPTION_PREFIX } from '@/lib/new-workspace-project-options' +import { NEW_WORKSPACE_PROJECT_GROUP_OPTION_PREFIX } from '@/lib/workspace/creation/new-workspace-project-options' /** Use each project’s newest workspace creation as recency; it matches this picker’s action without separate persisted state. */ export function orderProjectIdsByRecency(worktrees: readonly Worktree[]): string[] { diff --git a/src/renderer/src/lib/onboarding-folder-agent-launch.ts b/src/renderer/src/components/onboarding/onboarding-folder-agent-launch.ts similarity index 91% rename from src/renderer/src/lib/onboarding-folder-agent-launch.ts rename to src/renderer/src/components/onboarding/onboarding-folder-agent-launch.ts index d3a58472c16..de29bc59a32 100644 --- a/src/renderer/src/lib/onboarding-folder-agent-launch.ts +++ b/src/renderer/src/components/onboarding/onboarding-folder-agent-launch.ts @@ -1,13 +1,13 @@ import { ensureAgentLaunchPreferences } from '@/runtime/agent-launch-settings/use-host-agent-launch-preferences' import type { AgentLaunchPreferences } from '@/runtime/agent-launch-settings/host-agent-launch-preferences-resource' -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { OnboardingState } from '../../../shared/onboarding-state-types' -import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' -import type { useAppStore } from '@/store' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { OnboardingState } from '../../../../shared/onboarding-state-types' +import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' +import type { useAppStore } from '@/store/index' import { notifyAgentLaunchFailure, agentLaunchRecoveryMessage -} from './agent-session/launch/failure/agent-launch-failure' +} from '../../lib/agent-session/launch/failure/agent-launch-failure' import { resolveAgentLaunchExecutionContext } from '@/lib/agent-session/launch/new-tab/launch-agent-execution-context' import { planAgentSessionLaunch, @@ -19,7 +19,7 @@ import { onboardingFolderDefaultAgent, shouldSeedFolderAgentAfterDismissedOnboarding, type OnboardingFolderAgentStartup -} from '@/lib/onboarding-folder-agent-startup' +} from '@/components/onboarding/onboarding-folder-agent-startup' import { activateAndRevealWorktree } from '@/lib/workspace/activation/worktree-activation' import { beginStructuredAgentSessionProvisionalLaunch } from '@/lib/agent-session/structured-agent-session-provisional-tab' diff --git a/src/renderer/src/lib/onboarding-folder-agent-startup.ts b/src/renderer/src/components/onboarding/onboarding-folder-agent-startup.ts similarity index 66% rename from src/renderer/src/lib/onboarding-folder-agent-startup.ts rename to src/renderer/src/components/onboarding/onboarding-folder-agent-startup.ts index b2190f61b99..daadfacd053 100644 --- a/src/renderer/src/lib/onboarding-folder-agent-startup.ts +++ b/src/renderer/src/components/onboarding/onboarding-folder-agent-startup.ts @@ -1,14 +1,15 @@ -import { buildAgentStartupPlan } from '../../../shared/agent-launch/startup/tui-agent-startup' -import { tuiAgentToAgentKind } from '@/lib/telemetry' -import { isTuiAgentEnabled } from '../../../shared/agent-launch/catalog/tui-agent-selection' -import { resolveAgentStartupPlanInputs } from '../../../shared/agent-launch/startup/agent-startup-plan-inputs' +import { buildAgentStartupPlan } from '../../../../shared/agent-launch/startup/tui-agent-startup' +import '@/lib/telemetry' +import { tuiAgentToAgentKind } from '../../../../shared/agent-kind' +import { isTuiAgentEnabled } from '../../../../shared/agent-launch/catalog/tui-agent-selection' +import { resolveAgentStartupPlanInputs } from '../../../../shared/agent-launch/startup/agent-startup-plan-inputs' import type { AgentStartedTelemetry } from '@/lib/workspace/creation/worktree-startup-payload' -import type { StartupCommandDelivery } from '../../../shared/agent-launch/startup/codex-startup-delivery' -import type { SleepingAgentLaunchConfig } from '../../../shared/agent-session/lifecycle/agent-session-resume' -import type { GlobalSettings } from '../../../shared/global-settings-types' -import type { OnboardingState } from '../../../shared/onboarding-state-types' -import type { AgentStartupShell } from '../../../shared/agent-launch/startup/tui-agent-startup-shell' -import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' +import type { StartupCommandDelivery } from '../../../../shared/agent-launch/startup/codex-startup-delivery' +import type { SleepingAgentLaunchConfig } from '../../../../shared/agent-session/lifecycle/agent-session-resume' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import type { OnboardingState } from '../../../../shared/onboarding-state-types' +import type { AgentStartupShell } from '../../../../shared/agent-launch/startup/tui-agent-startup-shell' +import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' export type OnboardingFolderAgentStartup = { command: string diff --git a/src/renderer/src/lib/onboarding-project-checklist.ts b/src/renderer/src/components/onboarding/onboarding-project-checklist.ts similarity index 91% rename from src/renderer/src/lib/onboarding-project-checklist.ts rename to src/renderer/src/components/onboarding/onboarding-project-checklist.ts index 07cbfa72acc..db7ee5bf2f7 100644 --- a/src/renderer/src/lib/onboarding-project-checklist.ts +++ b/src/renderer/src/components/onboarding/onboarding-project-checklist.ts @@ -1,5 +1,5 @@ import { track } from '@/lib/telemetry' -import type { OnboardingState } from '../../../shared/onboarding-state-types' +import type { OnboardingState } from '../../../../shared/onboarding-state-types' export type OnboardingProjectChecklistItem = 'addedRepo' | 'addedFolder' diff --git a/src/renderer/src/components/onboarding/use-onboarding-agent-surface.ts b/src/renderer/src/components/onboarding/use-onboarding-agent-surface.ts index a7058d3b74f..d0fd8d00ae7 100644 --- a/src/renderer/src/components/onboarding/use-onboarding-agent-surface.ts +++ b/src/renderer/src/components/onboarding/use-onboarding-agent-surface.ts @@ -9,8 +9,11 @@ import { } from '@/runtime/native-chat/agent-catalogs/chat-provider-agents' import { recomputeOn } from '@/lib/recompute-on' import type { ProspectiveWorkspace } from '@/lib/agent-session/launch/routing/agent-launch-route-input' -import { readChatProgram, resolveChatProgramContext } from '@/lib/host-chat-program' -import { useChatProgramFacts } from '@/lib/host-chat-program-acquisition' +import { + readChatProgram, + resolveChatProgramContext +} from '@/lib/agent-session/launch/inventory/host-chat-program' +import { useChatProgramFacts } from '@/lib/agent-session/launch/inventory/host-chat-program-acquisition' import { relearnHostStructuredAgents } from '@/runtime/native-chat/agent-catalogs/host-structured-agents' import { useAppStore } from '@/store' import { readNativeDetectedAgents } from '@/store/slices/agent-inventory/local-detected-agent-store-state' diff --git a/src/renderer/src/components/onboarding/use-onboarding-flow-actions.test.tsx b/src/renderer/src/components/onboarding/use-onboarding-flow-actions.test.tsx deleted file mode 100644 index b72da1b96bd..00000000000 --- a/src/renderer/src/components/onboarding/use-onboarding-flow-actions.test.tsx +++ /dev/null @@ -1,306 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, renderHook } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { GlobalSettings } from '../../../../shared/global-settings-types' -import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' -import { getDefaultSettings } from '../../../../shared/constants' -import { useOnboardingFlowActions } from './use-onboarding-flow-actions' -import { useCloseWith } from './use-onboarding-flow-persistence' -import { getDefaultOnboardingState } from '../../../../shared/onboarding-defaults' -import { STEPS } from './use-onboarding-flow-types' -import type { WorkspaceActivationOutcome } from '@/lib/workspace/activation/worktree-activation-outcome' - -const { - track, - launch, - reveal, - state, - toastError, - focusIntent, - detect, - acquireChoices, - preferences -} = vi.hoisted(() => { - const state: { activeWorkspaceExecutionHostId: string; settings: GlobalSettings | null } = { - activeWorkspaceExecutionHostId: 'runtime:chosen', - settings: null - } - return { - track: vi.fn(), - launch: vi.fn(), - reveal: vi.fn<(...args: unknown[]) => WorkspaceActivationOutcome>(() => ({ - opened: { primaryTabId: null } - })), - state, - detect: vi.fn(), - acquireChoices: vi.fn(), - preferences: vi.fn(), - toastError: vi.fn(), - focusIntent: { cancel: vi.fn() } - } -}) -vi.mock('sonner', () => ({ toast: { error: toastError } })) -vi.mock('@/store', () => ({ useAppStore: { getState: () => state } })) -vi.mock('@/lib/workspace/ownership/worktree-runtime-owner', () => ({ - getExecutionHostIdForWorktree: () => state.activeWorkspaceExecutionHostId -})) -vi.mock('@/lib/agent-session/launch/new-tab/launch-agent-in-new-tab', () => ({ - launchAgentInNewTabWithOutcome: launch -})) -vi.mock('@/lib/workspace/activation/worktree-activation', () => ({ - activateAndRevealWorkspaceWithOutcome: reveal -})) -vi.mock('@/components/agent-tab-launch-context', () => ({ - captureAgentTabLaunchContext: () => ({ groupId: 'group', focusIntent }) -})) -vi.mock('@/lib/telemetry', () => ({ track })) -vi.mock('@/lib/agent-session/launch/inventory/agent-detection-target-inventory', () => ({ - loadDetectedAgentsForWorktree: detect -})) -vi.mock('@/lib/host-chat-program-acquisition', () => ({ - acquireAgentLaunchChoices: acquireChoices -})) -vi.mock('@/runtime/agent-launch-settings/use-host-agent-launch-preferences', () => ({ - ensureAgentLaunchPreferences: preferences -})) -beforeEach(() => { - state.settings = getDefaultSettings('/tmp') - detect.mockResolvedValue(['claude', 'codex']) - preferences.mockImplementation(async (store) => store.settings) - acquireChoices.mockImplementation(async (_workspace, load) => ({ detected: await load() })) -}) - -afterEach(() => { - cleanup() - vi.clearAllMocks() - state.activeWorkspaceExecutionHostId = 'runtime:chosen' -}) - -function renderActions( - hasSelectedWorkspace: boolean, - stepIndex = STEPS.length - 1, - selectedAgent: TuiAgent | null = 'codex', - options: { surface?: 'chat' | 'terminal'; defaultAgent?: GlobalSettings['defaultTuiAgent'] } = {} -) { - const openModal = vi.fn() - const update = vi.fn().mockResolvedValue({ - ...getDefaultOnboardingState(), - outcome: 'completed', - closedAt: 1 - }) - Object.defineProperty(window, 'api', { - configurable: true, - value: { - onboarding: { update }, - starNag: { onboardingCompleted: vi.fn() } - } - }) - const onOnboardingChange = vi.fn() - const persistCurrentStep = vi.fn().mockResolvedValue({ ok: true }) - state.settings = { - ...getDefaultSettings('/tmp'), - defaultTuiAgent: options.defaultAgent ?? null - } - const updateSettings = vi.fn(async (updates: Partial) => { - state.settings = { ...state.settings!, ...updates } - }) - const { result } = renderHook(() => { - const closeWith = useCloseWith({ - onOnboardingChange, - startTimeRef: { current: 1 }, - setError: vi.fn() - }) - return useOnboardingFlowActions({ - busyLabel: null, - setBusyLabel: vi.fn(), - setError: vi.fn(), - currentStep: STEPS[stepIndex], - consumeStepDurationMs: () => 10, - trackTaskSourcesSnapshot: vi.fn(), - settings: state.settings, - persistCurrentStep, - selectedWorkspaceId: hasSelectedWorkspace ? 'folder:home' : null, - closeWith, - openModal, - getNextStepIndex: (index) => index + 1, - onOnboardingChange, - stepIndex, - setStepIndex: vi.fn(), - selectedAgent, - agentSurface: options.surface ?? 'terminal', - themeLookBaseline: null, - setTheme: vi.fn(), - updateSettings, - skipOptions: { skipIntegrations: true, skipWindowsTerminal: true } - }) - }) - return { result, openModal, update, persistCurrentStep, onOnboardingChange, updateSettings } -} - -describe('onboarding completion destination', () => { - it('reports a captured workspace disappearing while completion is saved, without opening a surface', async () => { - const { result, persistCurrentStep } = renderActions(true, STEPS.length - 1, 'claude') - const saved = Promise.withResolvers<{ ok: boolean }>() - persistCurrentStep.mockReturnValueOnce(saved.promise) - let finishing: Promise - act(() => { - finishing = result.current.next() - }) - expect(launch).not.toHaveBeenCalled() - reveal.mockReturnValueOnce({ refused: { reason: 'workspace-missing', failureNotified: false } }) - await act(async () => { - saved.resolve({ ok: true }) - await finishing - }) - const createSurface = vi.fn() - if (launch.mock.calls[0][0].beforeSurfaceOpen()) { - createSurface() - } - expect(createSurface).not.toHaveBeenCalled() - expect(toastError).toHaveBeenCalledOnce() - }) - - it('keeps onboarding open for retry when setting up later cannot save completion', async () => { - const { result, update, onOnboardingChange, openModal } = renderActions( - true, - STEPS.findIndex((step) => step.id === 'agent') - ) - update.mockRejectedValueOnce(new Error('save failed')) - await act(() => result.current.setUpLater()) - expect(onOnboardingChange).not.toHaveBeenCalled() - expect(openModal).not.toHaveBeenCalled() - expect(launch).not.toHaveBeenCalled() - await act(() => result.current.setUpLater()) - expect(openModal).not.toHaveBeenCalled() - expect(launch).toHaveBeenCalledWith(expect.objectContaining({ agent: 'codex' })) - }) - - it('does not leave onboarding when the skipped agent preference cannot be saved', async () => { - const { result, updateSettings, update, onOnboardingChange, openModal } = renderActions( - true, - STEPS.findIndex((step) => step.id === 'agent') - ) - updateSettings.mockRejectedValueOnce(new Error('settings save failed')) - await act(() => result.current.setUpLater()) - expect(update).not.toHaveBeenCalled() - expect(onOnboardingChange).not.toHaveBeenCalled() - expect(openModal).not.toHaveBeenCalled() - expect(launch).not.toHaveBeenCalled() - await act(() => result.current.setUpLater()) - expect(launch).toHaveBeenCalledWith(expect.objectContaining({ agent: 'codex' })) - }) - - it('keeps onboarding open when completion cannot be saved', async () => { - const { result, openModal, update, onOnboardingChange } = renderActions(true) - update.mockRejectedValueOnce(new Error('save failed')) - await act(() => result.current.next()) - expect(openModal).not.toHaveBeenCalled() - expect(onOnboardingChange).not.toHaveBeenCalled() - expect(launch).not.toHaveBeenCalled() - expect(track).not.toHaveBeenCalledWith('onboarding_completed', expect.anything()) - await act(() => result.current.next()) - expect(launch).toHaveBeenCalledWith(expect.objectContaining({ agent: 'codex' })) - }) - it('keeps the captured target and owner through saving, dispatching once after unmount', async () => { - const { result, persistCurrentStep } = renderActions(true) - const saved = Promise.withResolvers<{ ok: boolean }>() - persistCurrentStep.mockReturnValueOnce(saved.promise) - let finishing: Promise - act(() => { - finishing = result.current.next() - }) - await act(() => result.current.next()) - state.activeWorkspaceExecutionHostId = 'runtime:other' - cleanup() - await act(async () => { - saved.resolve({ ok: true }) - await finishing - }) - expect(launch).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ - worktreeId: 'folder:home', - workspaceExecutionHostId: 'runtime:chosen' - }) - ) - }) - - it('retains the clicked workspace owner through deferred save and post-close discovery', async () => { - const { result, updateSettings, onOnboardingChange } = renderActions(true, 0, 'claude', { - surface: 'chat', - defaultAgent: 'codex' - }) - const saved = Promise.withResolvers() - const detected = Promise.withResolvers() - updateSettings.mockImplementationOnce(async (updates) => { - await saved.promise - state.settings = { ...state.settings!, ...updates } - }) - detect.mockReturnValueOnce(detected.promise) - const owners: string[] = [] - acquireChoices.mockImplementationOnce( - async (_workspace, load, _signal, _deadline, getState) => { - owners.push(getState().activeWorkspaceExecutionHostId) - const ids = await load() - owners.push(getState().activeWorkspaceExecutionHostId) - return { detected: ids } - } - ) - let finishing: Promise - act(() => { - finishing = result.current.setUpLater() - }) - await act(() => result.current.next()) - await act(() => result.current.setUpLater()) - state.activeWorkspaceExecutionHostId = 'runtime:other' - await act(async () => { - saved.resolve() - await saved.promise - }) - expect(onOnboardingChange).toHaveBeenCalled() - expect(launch).not.toHaveBeenCalled() - cleanup() - await act(async () => { - detected.resolve(['codex']) - await finishing - }) - expect(owners).toEqual(['runtime:chosen', 'runtime:chosen']) - expect(preferences).toHaveBeenCalledWith( - expect.objectContaining({ activeWorkspaceExecutionHostId: 'runtime:chosen' }), - expect.anything() - ) - expect(launch).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ - agent: 'codex', - worktreeId: 'folder:home', - workspaceExecutionHostId: 'runtime:chosen' - }) - ) - }) - - it('settles a failed default lookup after closing without launching or reporting twice', async () => { - const { result, onOnboardingChange } = renderActions(true, 0, 'claude') - detect.mockRejectedValueOnce(new Error('owner retired')) - await act(() => result.current.setUpLater()) - expect(onOnboardingChange).toHaveBeenCalledWith( - expect.objectContaining({ outcome: 'completed' }) - ) - expect(launch).not.toHaveBeenCalled() - expect(toastError).not.toHaveBeenCalled() - }) - - it('does not launch for an unselected agent, dismissal or failed step persistence', async () => { - const blank = renderActions(true, STEPS.length - 1, null) - await act(() => blank.result.current.next()) - expect(launch).not.toHaveBeenCalled() - cleanup() - const dismissed = renderActions(true) - await act(() => dismissed.result.current.dismissOnboarding()) - expect(launch).not.toHaveBeenCalled() - cleanup() - const failed = renderActions(true) - failed.persistCurrentStep.mockResolvedValueOnce({ ok: false }) - await act(() => failed.result.current.next()) - expect(failed.update).not.toHaveBeenCalled() - expect(launch).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/pull-request-page/checks/tab.tsx b/src/renderer/src/components/pull-request-page/checks/tab.tsx index 6b87113606e..b87c3675e4d 100644 --- a/src/renderer/src/components/pull-request-page/checks/tab.tsx +++ b/src/renderer/src/components/pull-request-page/checks/tab.tsx @@ -27,7 +27,7 @@ import { getGitHubSourceRuntimeHost } from '@/lib/work-items/github/github-source-runtime-context' import { getLocalRepoProjectExecutionRuntimeContext } from '@/lib/local-preflight-context' -import { CLIENT_PLATFORM } from '@/lib/new-workspace' +import { CLIENT_PLATFORM } from '@/lib/workspace/creation/new-workspace' import { resolveRepoExecutionHostPlatform } from '@/runtime/hosts/platform/execution-host-facts' import { resolveSourceControlActionRecipe } from '../../../../../shared/source-control/ai/source-control-ai-operation-policy' import type { diff --git a/src/renderer/src/components/right-sidebar/ai-vault/session-actions/use-ai-vault-panel-session-resume.ts b/src/renderer/src/components/right-sidebar/ai-vault/session-actions/use-ai-vault-panel-session-resume.ts index eff01a998ea..455792578ae 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault/session-actions/use-ai-vault-panel-session-resume.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault/session-actions/use-ai-vault-panel-session-resume.ts @@ -4,7 +4,7 @@ import type { Repo } from '../../../../../../shared/repo-types' import type { Worktree } from '../../../../../../shared/worktree/types' import { useAppStore } from '@/store/index' import { selectAgentLaunchRouteView } from '@/lib/agent-session/launch/routing/agent-launch-route-input' -import { useChatProgramFactsVersion } from '@/lib/host-chat-program-acquisition' +import { useChatProgramFactsVersion } from '@/lib/agent-session/launch/inventory/host-chat-program-acquisition' import { recomputeOn } from '@/lib/recompute-on' import { resolveAiVaultHistorySessionResumeState, diff --git a/src/renderer/src/components/right-sidebar/folder-workspace-repo-worktree-create.ts b/src/renderer/src/components/right-sidebar/folder-workspace-repo-worktree-create.ts index c73bfbaea85..ca9ded39707 100644 --- a/src/renderer/src/components/right-sidebar/folder-workspace-repo-worktree-create.ts +++ b/src/renderer/src/components/right-sidebar/folder-workspace-repo-worktree-create.ts @@ -1,7 +1,7 @@ import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import { readIpcErrorDetail } from '@/lib/ipc-error' -import { getRepoWorkspaceCreationTargetHint } from '@/lib/project-host-workspace-target' +import { getRepoWorkspaceCreationTargetHint } from '@/lib/workspace/creation/project-host-workspace-target' import { runtimeTargetSupportsCapability } from '@/runtime/rpc/compatibility/runtime-target-capability' import { runtimeRpcTargetForAuthorityKey } from '@/runtime/rpc/targets/runtime-client-target' import { useAppStore } from '@/store' diff --git a/src/renderer/src/components/right-sidebar/source-control/ai/recovery-launch.ts b/src/renderer/src/components/right-sidebar/source-control/ai/recovery-launch.ts index 1fbb3965fc6..f5521649691 100644 --- a/src/renderer/src/components/right-sidebar/source-control/ai/recovery-launch.ts +++ b/src/renderer/src/components/right-sidebar/source-control/ai/recovery-launch.ts @@ -8,7 +8,7 @@ import { ensureAgentLaunchPreferences } from '@/runtime/agent-launch-settings/us import { AgentLaunchChoiceCancelled, acquireAgentLaunchChoices -} from '@/lib/host-chat-program-acquisition' +} from '@/lib/agent-session/launch/inventory/host-chat-program-acquisition' import { toast } from 'sonner' import { useAppStore } from '@/store' import type { AppState } from '@/store/types' @@ -35,7 +35,7 @@ import { import type { SourceControlLaunchActionId } from '../../../../../../shared/source-control/ai/recipes/source-control-ai-actions' import { buildSourceControlRecoveryAgentCommandInput } from '../../../../../../shared/source-control/recovery/source-control-recovery-agent-command' import { translate } from '@/i18n/i18n' -import { agentChoiceMayOpenAsChat } from '@/lib/host-chat-program' +import { agentChoiceMayOpenAsChat } from '@/lib/agent-session/launch/inventory/host-chat-program' import { worktreeLaunchWorkspace } from '@/lib/agent-session/launch/routing/agent-launch-route-input' type SourceControlAiLaunchStoreSnapshot = Pick & WorktreeAgentInventoryState diff --git a/src/renderer/src/components/right-sidebar/source-control/ai/use-saved-source-control-action-start.test.tsx b/src/renderer/src/components/right-sidebar/source-control/ai/use-saved-source-control-action-start.test.tsx deleted file mode 100644 index ea8fd2fce47..00000000000 --- a/src/renderer/src/components/right-sidebar/source-control/ai/use-saved-source-control-action-start.test.tsx +++ /dev/null @@ -1,68 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, renderHook } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store' -import { getDefaultSettings } from '../../../../../../shared/constants' -import { canonicalSourceControlActionSelection } from '../../../../../../shared/source-control/ai/recipes/source-control-action-selection' -import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' -import { TEST_REPO } from '@/store/repos/repo.test-fixture' -import { useSavedSourceControlActionStart } from './use-saved-source-control-action-start' - -const { launch } = vi.hoisted(() => ({ launch: vi.fn() })) -vi.mock('@/lib/agent-session/launch/new-tab/launch-agent-in-new-tab', () => ({ - launchAgentInNewTab: launch -})) -vi.mock('@/lib/focus-terminal-tab-surface', () => ({ focusTerminalTabSurface: vi.fn() })) -vi.mock('@/lib/host-chat-program-acquisition', () => ({ - AgentLaunchChoiceCancelled: class extends Error {}, - acquireAgentLaunchChoices: async () => ({ detected: ['claude'] }) -})) -vi.mock('@/runtime/agent-launch-settings/use-host-agent-launch-preferences', () => ({ - ensureAgentLaunchPreferences: async () => undefined -})) -const initial = useAppStore.getState() -afterEach(() => { - cleanup() - useAppStore.setState(initial, true) -}) - -it('uses the current Claude permission default when a saved action launches after render', async () => { - const settings = { ...getDefaultSettings('/tmp'), agentPermissionDefault: 'full-access' as const } - useAppStore.setState({ - settings, - repos: [TEST_REPO], - worktreesByRepo: { [TEST_REPO.id]: [makeWorktree({ id: 'child', repoId: TEST_REPO.id })] } - }) - launch.mockReturnValue({ surface: { kind: 'local-terminal', tabId: 'agent' } }) - const { result } = renderHook(() => { - const saved = useSavedSourceControlActionStart() - return () => - saved.start({ - selection: canonicalSourceControlActionSelection({ - agentId: 'claude', - surface: 'terminal', - agentArgs: '--model opus' - }), - basePrompt: 'Fix the failed commit', - actionId: 'fixCommitFailure', - repo: TEST_REPO, - repoId: TEST_REPO.id, - worktreeId: 'child', - connectionId: null, - promptDelivery: 'auto-submit', - launchPlatform: 'linux', - launchSource: 'source_control_recovery', - onClose: () => {}, - onFallback: () => { - throw new Error('Unexpected fallback') - } - }) - }) - useAppStore.setState({ settings: { ...settings, agentPermissionDefault: 'ask' } }) - await act(async () => { - await result.current() - }) - expect(launch).toHaveBeenCalledWith( - expect.objectContaining({ agentArgs: '--permission-mode default --model opus' }) - ) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control/ai/use-saved-source-control-action-start.ts b/src/renderer/src/components/right-sidebar/source-control/ai/use-saved-source-control-action-start.ts index 12ce5c77466..264cbf7028f 100644 --- a/src/renderer/src/components/right-sidebar/source-control/ai/use-saved-source-control-action-start.ts +++ b/src/renderer/src/components/right-sidebar/source-control/ai/use-saved-source-control-action-start.ts @@ -5,8 +5,8 @@ import { import { AgentLaunchChoiceCancelled, acquireAgentLaunchChoices -} from '@/lib/host-chat-program-acquisition' -import { agentsOfferedForLaunch } from '@/lib/host-chat-program' +} from '@/lib/agent-session/launch/inventory/host-chat-program-acquisition' +import { agentsOfferedForLaunch } from '@/lib/agent-session/launch/inventory/host-chat-program' import { ensureAgentLaunchPreferences } from '@/runtime/agent-launch-settings/use-host-agent-launch-preferences' import { buildAgentLaunchRouteInput } from '@/lib/agent-session/launch/routing/agent-launch-route-input' import { workspaceKindForWorktreeId } from '../../../../../../shared/agent-launch/contracts/workspace-launch-kind' diff --git a/src/renderer/src/components/right-sidebar/source-control/ai/use-source-control-launchable-agents.ts b/src/renderer/src/components/right-sidebar/source-control/ai/use-source-control-launchable-agents.ts index c845afccedd..cf6b3d81307 100644 --- a/src/renderer/src/components/right-sidebar/source-control/ai/use-source-control-launchable-agents.ts +++ b/src/renderer/src/components/right-sidebar/source-control/ai/use-source-control-launchable-agents.ts @@ -8,8 +8,11 @@ import { } from '@/lib/agent-session/launch/inventory/agent-detection-target-inventory' import type { TuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent' import { sourceControlLaunchWorkspace } from './source-control-launch-agent-args-applicability' -import { acquireAgentLaunchChoices, useChatProgramFacts } from '@/lib/host-chat-program-acquisition' -import { agentsOfferedForLaunch } from '@/lib/host-chat-program' +import { + acquireAgentLaunchChoices, + useChatProgramFacts +} from '@/lib/agent-session/launch/inventory/host-chat-program-acquisition' +import { agentsOfferedForLaunch } from '@/lib/agent-session/launch/inventory/host-chat-program' type LaunchTarget = Parameters[0] diff --git a/src/renderer/src/components/settings/agents/launch/AgentLaunchSettingsCatalog.tsx b/src/renderer/src/components/settings/agents/launch/AgentLaunchSettingsCatalog.tsx index 334809388b3..2b47b17351d 100644 --- a/src/renderer/src/components/settings/agents/launch/AgentLaunchSettingsCatalog.tsx +++ b/src/renderer/src/components/settings/agents/launch/AgentLaunchSettingsCatalog.tsx @@ -2,7 +2,7 @@ import { useAppStateValue } from '@/store/retained-views/app-state-view' import { AgentLaunchChoiceEditor } from '@/components/agent/launch-settings/AgentLaunchChoiceEditor' import { agentChatPermissionModes } from '../../../../../../shared/agent-launch/permissions/agent-chat-permission-support' import { savedChatPermissionMode } from '../../../../../../shared/agent-launch/permissions/agent-chat-permission-mode' -import { useChatProgramFacts } from '@/lib/host-chat-program-acquisition' +import { useChatProgramFacts } from '@/lib/agent-session/launch/inventory/host-chat-program-acquisition' import { useMemo } from 'react' import { recomputeOn } from '@/lib/recompute-on' import { toast } from 'sonner' @@ -43,7 +43,7 @@ import { agentChoiceOpensAsChat, readChatProgram, resolveChatProgramContext -} from '@/lib/host-chat-program' +} from '@/lib/agent-session/launch/inventory/host-chat-program' import { readNativeDetectedAgents } from '@/store/slices/agent-inventory/local-detected-agent-store-state' import { useDetectedAgents, type AgentDetectionTarget } from '@/hooks/useDetectedAgents' import { AgentDefaultSetting } from '@/components/settings/agents/launch/AgentDefaultSetting' diff --git a/src/renderer/src/components/settings/chat/ChatAgentLaunchSettings.tsx b/src/renderer/src/components/settings/chat/ChatAgentLaunchSettings.tsx index 328ae92d705..b5d8bd49a51 100644 --- a/src/renderer/src/components/settings/chat/ChatAgentLaunchSettings.tsx +++ b/src/renderer/src/components/settings/chat/ChatAgentLaunchSettings.tsx @@ -8,8 +8,11 @@ import { useHostStructuredAgentsVersion } from '@/runtime/native-chat/agent-catalogs/chat-provider-agents' import { recomputeOn } from '@/lib/recompute-on' -import { readChatProgram, resolveChatProgramContext } from '@/lib/host-chat-program' -import { useChatProgramFacts } from '@/lib/host-chat-program-acquisition' +import { + readChatProgram, + resolveChatProgramContext +} from '@/lib/agent-session/launch/inventory/host-chat-program' +import { useChatProgramFacts } from '@/lib/agent-session/launch/inventory/host-chat-program-acquisition' import { useAppStore } from '@/store/index' import { readNativeDetectedAgents } from '@/store/slices/agent-inventory/local-detected-agent-store-state' import { Card, CardContent } from '../../ui/card' diff --git a/src/renderer/src/components/settings/chat/ChatSettingsSection.navigation.test.tsx b/src/renderer/src/components/settings/chat/ChatSettingsSection.navigation.test.tsx deleted file mode 100644 index 33c97355d59..00000000000 --- a/src/renderer/src/components/settings/chat/ChatSettingsSection.navigation.test.tsx +++ /dev/null @@ -1,133 +0,0 @@ -// @vitest-environment happy-dom -// @vitest-environment happy-dom -import { useRef, useState } from 'react' -import { cleanup, render, screen, waitFor } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getDefaultSettings } from '../../../../../shared/constants' -import { buildSettingsNavigationMetadata } from '@/hooks/useSettingsNavigationMetadata' -import { ChatSettingsSection } from './ChatSettingsSection' -import { TooltipProvider } from '../../ui/tooltip' -import { ActiveSettingsSectionProvider } from '../section-layout/SettingsSection' -import { getChatAppearanceSearchEntries } from '../appearance/chat/chat-appearance-search' -import { getChatNamingSearchEntry } from './chat-naming-search' -import { getChatInlineVisualsSearchEntry } from './chat-inline-visuals-search' -import { useSettingsRepoScrollEffects } from '../navigation/use-settings-repo-scroll-effects' -import type { SettingsStoreModel } from '../page/use-settings-store-model' -import type { SettingsInteractionController } from '../page/use-settings-interaction-controller' -import type { SettingsNavigationModel } from '../navigation/use-settings-navigation-model' -import type { SettingsTerminalModel } from '../page/use-settings-terminal-model' -import { useAppStore } from '@/store/index' - -vi.mock('@/lib/host-chat-program-acquisition', () => ({ useChatProgramFacts: () => {} })) -beforeEach(() => { - useAppStore.setState(useAppStore.getInitialState(), true) - useAppStore.setState({ ensureNativeDetectedAgents: vi.fn(async () => []) }) -}) - -afterEach(() => { - cleanup() - vi.restoreAllMocks() -}) - -function NavigationHarness({ - initialSection, - targetSection = 'chat-code-text-size' -}: { - initialSection: string - targetSection?: string -}) { - const [activeSectionId, setActiveSectionId] = useState(initialSection) - const settings = getDefaultSettings('/tmp') - const sections = buildSettingsNavigationMetadata({ - isMac: false, - isWindows: false, - isWebClient: false, - repos: [] - }) - const pendingNavSectionRef = useRef('chat') - const pendingScrollTargetRef = useRef(targetSection) - const contentScrollRef = useRef(null) - const pendingScrollTargetWatchRef = useRef(null) - const pendingSubsectionScrollFrameRef = useRef(null) - const repoHooksRequestSeqRef = useRef(0) - const model: Pick< - SettingsStoreModel, - | 'activeSectionId' - | 'setActiveSectionId' - | 'pendingNavRequestTick' - | 'setPendingNavRequestTick' - | 'repos' - | 'setRepoHooksMap' - | 'settingsSearchQuery' - | 'setSettingsSearchQuery' - > = { - activeSectionId, - setActiveSectionId, - pendingNavRequestTick: 0, - setPendingNavRequestTick: vi.fn(), - repos: [], - setRepoHooksMap: vi.fn(), - settingsSearchQuery: '', - setSettingsSearchQuery: vi.fn() - } - const interactions = { - contentScrollRef, - pendingNavSectionRef, - pendingScrollTargetRef, - pendingScrollTargetWatchRef, - pendingSubsectionScrollFrameRef, - repoHooksRequestSeqRef - } - const terminal: Pick = { neededRepos: [] } - useSettingsRepoScrollEffects( - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Supplies every model field read by this hook; no repos need loading. - model as SettingsStoreModel, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Supplies every interaction ref read by this hook. - interactions as SettingsInteractionController, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This hook only reads the visible navigation sections and IDs. - { - visibleNavSections: sections, - visibleSectionIds: new Set(sections.map((s) => s.id)) - } as SettingsNavigationModel, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This hook only reads neededRepos; an empty list skips remote loading. - terminal as SettingsTerminalModel - ) - return ( - - - {activeSectionId} - {}} - searchEntries={[ - ...getChatAppearanceSearchEntries(), - getChatNamingSearchEntry(), - getChatInlineVisualsSearchEntry() - ]} - showDesktopOnlySettings - isMounted - /> - - - ) -} - -describe('Chat settings deep links', () => { - it('activates Chat and scrolls to Inline visuals from another settings page', async () => { - const scrollIntoView = vi.spyOn(HTMLElement.prototype, 'scrollIntoView') - const { container } = render( - - ) - await waitFor(() => { - expect(screen.getByRole('status', { name: 'Selected settings page' }).textContent).toBe( - 'chat' - ) - }) - const visuals = container.querySelector('#chat-inline-visuals') - expect(visuals?.querySelector('[role="switch"]')).toBe( - screen.getByRole('switch', { name: 'Toggle inline visuals' }) - ) - await waitFor(() => expect(scrollIntoView.mock.contexts).toContain(visuals)) - }) -}) diff --git a/src/renderer/src/components/settings/chat/ChatSettingsSection.test.tsx b/src/renderer/src/components/settings/chat/ChatSettingsSection.test.tsx index 07a2539eaa2..cfce100e9eb 100644 --- a/src/renderer/src/components/settings/chat/ChatSettingsSection.test.tsx +++ b/src/renderer/src/components/settings/chat/ChatSettingsSection.test.tsx @@ -18,7 +18,9 @@ import { i18n } from '@/i18n/i18n' import { useAppStore } from '@/store/index' import { getChatLaunchSearchEntries } from './chat-launch-search' -vi.mock('@/lib/host-chat-program-acquisition', () => ({ useChatProgramFacts: () => {} })) +vi.mock('@/lib/agent-session/launch/inventory/host-chat-program-acquisition', () => ({ + useChatProgramFacts: () => {} +})) afterEach(async () => { cleanup() diff --git a/src/renderer/src/components/settings/repository/hosts/repository-host-setup-options.ts b/src/renderer/src/components/settings/repository/hosts/repository-host-setup-options.ts index 86f138791cb..55c3b8a2721 100644 --- a/src/renderer/src/components/settings/repository/hosts/repository-host-setup-options.ts +++ b/src/renderer/src/components/settings/repository/hosts/repository-host-setup-options.ts @@ -9,7 +9,7 @@ import type { } from '../../../../../../shared/project-types' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' -import { getHostSetupUnavailableDetail } from '@/lib/project-host-setup-options' +import { getHostSetupUnavailableDetail } from '@/lib/workspace/creation/project-host-setup-options' import { pickerExecutionHosts } from '../../../../../../shared/execution-host/managed-orcad-execution-host' export type SetupHostOption = { diff --git a/src/renderer/src/components/settings/repository/worktrees/SparsePresetSettingsSection.tsx b/src/renderer/src/components/settings/repository/worktrees/SparsePresetSettingsSection.tsx index fdc7ecc46fb..4eb92f07ca1 100644 --- a/src/renderer/src/components/settings/repository/worktrees/SparsePresetSettingsSection.tsx +++ b/src/renderer/src/components/settings/repository/worktrees/SparsePresetSettingsSection.tsx @@ -2,7 +2,10 @@ import { useEffect, useRef, useState } from 'react' import { Plus, RefreshCcw } from 'lucide-react' import type { SparsePreset } from '../../../../../../shared/worktree/create-types' import { useAppStore } from '../../../../store/index' -import { parseSparsePresetDirectories, validateSparsePresetName } from '@/lib/sparse-preset-draft' +import { + parseSparsePresetDirectories, + validateSparsePresetName +} from '@/components/sparse/sparse-preset-draft' import { useMountedRef } from '@/hooks/useMountedRef' import { Button } from '../../../ui/button' import { getSparsePresetOperationErrorMessage } from './sparse-preset-operation-error' diff --git a/src/renderer/src/components/settings/virtual-machines/recipes/EphemeralVmsPane.tsx b/src/renderer/src/components/settings/virtual-machines/recipes/EphemeralVmsPane.tsx index e7145d8b0c0..9e670dff931 100644 --- a/src/renderer/src/components/settings/virtual-machines/recipes/EphemeralVmsPane.tsx +++ b/src/renderer/src/components/settings/virtual-machines/recipes/EphemeralVmsPane.tsx @@ -18,7 +18,7 @@ import { useActiveProjectSkillRuntime } from '@/hooks/skills/runtime/useActivePr import { launchEnvironmentSetupAgent, pickEnvironmentSetupRepo -} from '@/lib/environment-setup-agent-launch' +} from '@/lib/agent-session/launch/environment-setup-agent-launch' type RecipeCatalogEntry = Awaited< ReturnType diff --git a/src/renderer/src/components/settings/virtual-machines/runtimes/EphemeralVmRuntimeRow.tsx b/src/renderer/src/components/settings/virtual-machines/runtimes/EphemeralVmRuntimeRow.tsx index f2887f5ab4d..90d21d77094 100644 --- a/src/renderer/src/components/settings/virtual-machines/runtimes/EphemeralVmRuntimeRow.tsx +++ b/src/renderer/src/components/settings/virtual-machines/runtimes/EphemeralVmRuntimeRow.tsx @@ -2,7 +2,7 @@ import { AlertTriangle, Copy, Loader2, Square, Trash2, X } from 'lucide-react' import type { EphemeralVmRuntimeRecord } from '../../../../../../shared/ephemeral-vm-runtimes' import { getEphemeralVmRecipeResultProjectRoot } from '../../../../../../shared/ephemeral-vm-recipes' import { useTranslate } from '@/i18n/use-translate' -import { ephemeralVmCleanupErrorText } from '@/lib/ephemeral-vm-error-copy' +import { ephemeralVmCleanupErrorText } from '@/runtime/ephemeral-vm/ephemeral-vm-error-copy' import { cn } from '@/lib/utils' import { Button } from '../../../ui/button' diff --git a/src/renderer/src/components/settings/virtual-machines/runtimes/EphemeralVmRuntimesSection.tsx b/src/renderer/src/components/settings/virtual-machines/runtimes/EphemeralVmRuntimesSection.tsx index e31cd055e30..5ebef221cb7 100644 --- a/src/renderer/src/components/settings/virtual-machines/runtimes/EphemeralVmRuntimesSection.tsx +++ b/src/renderer/src/components/settings/virtual-machines/runtimes/EphemeralVmRuntimesSection.tsx @@ -7,7 +7,7 @@ import { EPHEMERAL_VM_CLEANUP_STOPPED_ERROR } from '../../../../../../shared/eph import { useMountedRef } from '@/hooks/useMountedRef' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { ephemeralVmCleanupErrorText } from '@/lib/ephemeral-vm-error-copy' +import { ephemeralVmCleanupErrorText } from '@/runtime/ephemeral-vm/ephemeral-vm-error-copy' import { Button } from '../../../ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '../../../ui/tooltip' import { EphemeralVmCleanupStopDialog } from './EphemeralVmCleanupStopDialog' diff --git a/src/renderer/src/components/setup-guide/use-setup-guide-progress.ts b/src/renderer/src/components/setup-guide/use-setup-guide-progress.ts index 6922a1fb708..d1d61a59c13 100644 --- a/src/renderer/src/components/setup-guide/use-setup-guide-progress.ts +++ b/src/renderer/src/components/setup-guide/use-setup-guide-progress.ts @@ -4,7 +4,7 @@ import { isGitRepoKind } from '../../../../shared/repo-kind' import { getRepoExecutionHostId } from '../../../../shared/execution-host' import { checkRuntimeHooks } from '@/runtime/repo-hooks/runtime-hooks-client' import { getLocalPreflightContext, localPreflightContextKey } from '@/lib/local-preflight-context' -import { hasEffectiveSetupCommand } from '@/lib/setup-script-status' +import { hasEffectiveSetupCommand } from '@/runtime/repo-hooks/setup-script-status' import { getProviderRuntimeContextKey } from '@/runtime/hosts/observations/provider-runtime-context' import { COMPUTER_USE_SKILL_NAME, diff --git a/src/renderer/src/components/sidebar/OrcaYamlTrustDialog.test.tsx b/src/renderer/src/components/sidebar/OrcaYamlTrustDialog.test.tsx index 43fe3448683..12ab2fe29f0 100644 --- a/src/renderer/src/components/sidebar/OrcaYamlTrustDialog.test.tsx +++ b/src/renderer/src/components/sidebar/OrcaYamlTrustDialog.test.tsx @@ -9,7 +9,7 @@ import { __resetTrustPromptChainForTests, confirmCreatedWorktreeSetupContent, ensureHooksConfirmed -} from '@/lib/ensure-hooks-confirmed' +} from '@/runtime/repo-hooks/ensure-hooks-confirmed' import type { Repo } from '../../../../shared/repo-types' const hooksCheck = vi.fn() diff --git a/src/renderer/src/components/sidebar/OrcaYamlTrustDialog.tsx b/src/renderer/src/components/sidebar/OrcaYamlTrustDialog.tsx index 33d0be38c36..6648d6eea73 100644 --- a/src/renderer/src/components/sidebar/OrcaYamlTrustDialog.tsx +++ b/src/renderer/src/components/sidebar/OrcaYamlTrustDialog.tsx @@ -9,13 +9,13 @@ import { } from '@/components/ui/dialog' import { Button } from '@/components/ui/button' import { useAppStore } from '@/store' -import type { OrcaHookScriptKind } from '@/lib/orca-hook-trust' +import type { OrcaHookTrustKind } from '../../../../shared/orca-hook-trust-entries' import { Trans } from 'react-i18next' import { i18n, translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' -type ScriptKind = OrcaHookScriptKind +type ScriptKind = OrcaHookTrustKind type SkippedSetupReviewCopy = { title: string diff --git a/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx b/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx index 71ef5ed4f99..8db72accfcc 100644 --- a/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx +++ b/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx @@ -17,7 +17,7 @@ import { normalizeExecutionHostId } from '../../../../shared/execution-host' import { countOpenRepoTerminalTabs } from '@/store/repos/repo-removal' -import { getRecipeVmSshTargetForHost } from '@/lib/recipe-vm-managed-host' +import { getRecipeVmSshTargetForHost } from '@/runtime/ephemeral-vm/recipe-vm-managed-host' import { RemovalUnsavedFilesNotice } from './workspace-actions/deletion/RemovalUnsavedFilesNotice' import { confirmUnsavedDiscard } from '@/store/slices/worktrees/teardown/removed-workspace-unsaved-files' import { projectRemovalTargets } from './workspace-actions/deletion/removal-unsaved-files' diff --git a/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx b/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx index 841eac011d4..19fc4b7b786 100644 --- a/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx +++ b/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx @@ -10,7 +10,7 @@ import { getDetectedSetupPreviewContent, isSetupScriptPromptDismissed, isSilentSetupScriptPromptState -} from '@/lib/setup-script-prompt' +} from '@/runtime/repo-hooks/setup-script-prompt' import { isGitRepoKind } from '../../../../shared/repo-kind' import type { SetupScriptImportCandidate } from '../../../../shared/workspace-setup/setup-script-imports' import { buildSetupScriptPromptActionTelemetry } from '../../../../shared/workspace-setup/setup-script-telemetry' diff --git a/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.tsx b/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.tsx index dbedf0b4257..440145e5bfd 100644 --- a/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.tsx +++ b/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.tsx @@ -11,7 +11,7 @@ import { } from './SetupScriptPromptCardViews' import { SetupScriptReviewDialog } from './SetupScriptReviewDialog' import { useTranslate } from '@/i18n/use-translate' -import type { DetectedSetupPreviewContent } from '@/lib/setup-script-prompt' +import type { DetectedSetupPreviewContent } from '@/runtime/repo-hooks/setup-script-prompt' type SetupScriptPromptCardShellProps = { repoBadgeColor: string diff --git a/src/renderer/src/components/sidebar/project-admission/completion/project-added-default-checkout.ts b/src/renderer/src/components/sidebar/project-admission/completion/project-added-default-checkout.ts index fcdbe6e13d3..984e63cb288 100644 --- a/src/renderer/src/components/sidebar/project-admission/completion/project-added-default-checkout.ts +++ b/src/renderer/src/components/sidebar/project-admission/completion/project-added-default-checkout.ts @@ -7,7 +7,7 @@ import type { } from '../../../../../../shared/telemetry-events' import type { DetectedWorktreeListResult, Worktree } from '../../../../../../shared/worktree/types' import { relativePathInsideRoot } from '../../../../../../shared/cross-platform-path' -import { markOnboardingProjectAdded } from '@/lib/onboarding-project-checklist' +import { markOnboardingProjectAdded } from '@/components/onboarding/onboarding-project-checklist' import { finalizeImportedRepoAfterSkip } from './add-repo-skip-finalization' import { parseExecutionHostId, type ExecutionHostId } from '../../../../../../shared/execution-host' import { diff --git a/src/renderer/src/components/sidebar/project-admission/create/useCreateRepo.ts b/src/renderer/src/components/sidebar/project-admission/create/useCreateRepo.ts index 529a5956626..e575494ede5 100644 --- a/src/renderer/src/components/sidebar/project-admission/create/useCreateRepo.ts +++ b/src/renderer/src/components/sidebar/project-admission/create/useCreateRepo.ts @@ -3,7 +3,7 @@ import { toast } from 'sonner' import { useAppStore } from '@/store/index' import { useMountedRef } from '@/hooks/useMountedRef' import { activateAndRevealWorktree } from '@/lib/workspace/activation/worktree-activation' -import { markOnboardingProjectAdded } from '@/lib/onboarding-project-checklist' +import { markOnboardingProjectAdded } from '@/components/onboarding/onboarding-project-checklist' import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' import { isGitRepoKind } from '../../../../../../shared/repo-kind' import type { Repo } from '../../../../../../shared/repo-types' diff --git a/src/renderer/src/components/sidebar/project-admission/dialog/NonGitFolderDialog.tsx b/src/renderer/src/components/sidebar/project-admission/dialog/NonGitFolderDialog.tsx index 5e2e2b72444..8cd46c46d83 100644 --- a/src/renderer/src/components/sidebar/project-admission/dialog/NonGitFolderDialog.tsx +++ b/src/renderer/src/components/sidebar/project-admission/dialog/NonGitFolderDialog.tsx @@ -13,8 +13,8 @@ import { useAppStore } from '@/store/index' import { resolveDismissedOnboardingFolderAgentLaunch, revealOnboardingFolderWithAgentLaunch -} from '@/lib/onboarding-folder-agent-launch' -import { markOnboardingProjectAdded } from '@/lib/onboarding-project-checklist' +} from '@/components/onboarding/onboarding-folder-agent-launch' +import { markOnboardingProjectAdded } from '@/components/onboarding/onboarding-project-checklist' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' diff --git a/src/renderer/src/components/sidebar/project-admission/host-selection/use-add-repo-hosted-controller.ts b/src/renderer/src/components/sidebar/project-admission/host-selection/use-add-repo-hosted-controller.ts index 6118a160278..4b89ec8e330 100644 --- a/src/renderer/src/components/sidebar/project-admission/host-selection/use-add-repo-hosted-controller.ts +++ b/src/renderer/src/components/sidebar/project-admission/host-selection/use-add-repo-hosted-controller.ts @@ -1,7 +1,7 @@ import type { CompleteGitRepoAdd } from '../completion/use-complete-git-repo-add' import { useMemo } from 'react' import { useAppStore } from '@/store/index' -import { markOnboardingProjectAdded } from '@/lib/onboarding-project-checklist' +import { markOnboardingProjectAdded } from '@/components/onboarding/onboarding-project-checklist' /** Nest Add Project in a host surface rather than replacing the store modal. */ export type AddRepoDialogHostedController = { diff --git a/src/renderer/src/components/sidebar/project-admission/nested-import/useAddRepoNestedImportFlow.ts b/src/renderer/src/components/sidebar/project-admission/nested-import/useAddRepoNestedImportFlow.ts index f3215824d22..77a15dae9e0 100644 --- a/src/renderer/src/components/sidebar/project-admission/nested-import/useAddRepoNestedImportFlow.ts +++ b/src/renderer/src/components/sidebar/project-admission/nested-import/useAddRepoNestedImportFlow.ts @@ -2,7 +2,7 @@ import { useCallback, useRef } from 'react' import { toast } from 'sonner' import { track } from '@/lib/telemetry' import { useAppStore } from '@/store/index' -import { getSelectedNestedRepoPathsInScanOrder } from '@/lib/nested-repo-selected-paths' +import { getSelectedNestedRepoPathsInScanOrder } from '@/lib/workspace/creation/nested-repo-selected-paths' import { buildNestedRepoImportActionTelemetry, buildNestedRepoImportResultTelemetry, diff --git a/src/renderer/src/components/sidebar/setup-script-prompt-render-state.ts b/src/renderer/src/components/sidebar/setup-script-prompt-render-state.ts index b5bf06e18a5..2756c0a7f4b 100644 --- a/src/renderer/src/components/sidebar/setup-script-prompt-render-state.ts +++ b/src/renderer/src/components/sidebar/setup-script-prompt-render-state.ts @@ -4,7 +4,7 @@ import type { Worktree } from '../../../../shared/worktree/types' import { ignoresSharedSetupScripts, type SetupScriptPromptInspection -} from '@/lib/setup-script-prompt' +} from '@/runtime/repo-hooks/setup-script-prompt' import { findRepoForHost } from '@/store/repos/repo-host-identity' import { toRuntimeExecutionHostId } from '../../../../shared/execution-host' diff --git a/src/renderer/src/components/sidebar/useRenderedSetupScriptPromptState.ts b/src/renderer/src/components/sidebar/useRenderedSetupScriptPromptState.ts index a6d96dd860a..9621f15b16f 100644 --- a/src/renderer/src/components/sidebar/useRenderedSetupScriptPromptState.ts +++ b/src/renderer/src/components/sidebar/useRenderedSetupScriptPromptState.ts @@ -1,5 +1,5 @@ import { useEffect, useRef } from 'react' -import { isSilentSetupScriptPromptState } from '@/lib/setup-script-prompt' +import { isSilentSetupScriptPromptState } from '@/runtime/repo-hooks/setup-script-prompt' import { getRenderedSetupScriptPromptState, type LastVisibleSetupScriptPrompt, diff --git a/src/renderer/src/components/sidebar/useSetupScriptPromptInspection.ts b/src/renderer/src/components/sidebar/useSetupScriptPromptInspection.ts index e9e8cec5706..92616d9a787 100644 --- a/src/renderer/src/components/sidebar/useSetupScriptPromptInspection.ts +++ b/src/renderer/src/components/sidebar/useSetupScriptPromptInspection.ts @@ -1,5 +1,5 @@ import { useEffect } from 'react' -import { inspectSetupScriptPromptState } from '@/lib/setup-script-prompt' +import { inspectSetupScriptPromptState } from '@/runtime/repo-hooks/setup-script-prompt' import { checkRuntimeHooks, inspectRuntimeSetupScriptImports diff --git a/src/renderer/src/components/sidebar/workspace-actions/context-menu/use-worktree-context-menu-commands.ts b/src/renderer/src/components/sidebar/workspace-actions/context-menu/use-worktree-context-menu-commands.ts index 440a0ba4ceb..32f8ab9f3a3 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/context-menu/use-worktree-context-menu-commands.ts +++ b/src/renderer/src/components/sidebar/workspace-actions/context-menu/use-worktree-context-menu-commands.ts @@ -5,7 +5,7 @@ import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../../../../shared/execution-host' -import { getRepoWorkspaceCreationTargetHint } from '@/lib/project-host-workspace-target' +import { getRepoWorkspaceCreationTargetHint } from '@/lib/workspace/creation/project-host-workspace-target' import { resolveReviewRepository } from '@/lib/review-owner' import type { WorkspaceStatusDefinition, Worktree } from '../../../../../../shared/worktree/types' import { diff --git a/src/renderer/src/components/sidebar/workspace-actions/context-menu/worktree-context-menu-policy.ts b/src/renderer/src/components/sidebar/workspace-actions/context-menu/worktree-context-menu-policy.ts index ec748d32d3c..17fef0348bc 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/context-menu/worktree-context-menu-policy.ts +++ b/src/renderer/src/components/sidebar/workspace-actions/context-menu/worktree-context-menu-policy.ts @@ -1,7 +1,8 @@ import type { AppState } from '@/store/types' import type { Repo } from '../../../../../../shared/repo-types' import { isGitRepoKind } from '../../../../../../shared/repo-kind' -import { getComposerEligibleRepos } from '@/lib/new-workspace-composer-repo' +import '@/lib/workspace/creation/new-workspace-composer-repo' +import { getNewWorkspaceDialogEligibleRepos } from '../../../../../../shared/new-workspace-dialog-repo' import type { WorkspaceStatus, WorkspaceStatusDefinition, @@ -132,7 +133,7 @@ export function canCreateChildWorktree(args: { return ( args.repo != null && isGitRepoKind(args.repo) && - getComposerEligibleRepos([args.repo]).length > 0 && + getNewWorkspaceDialogEligibleRepos([args.repo]).length > 0 && !args.folderWorkspaceId && !args.worktree.isArchived ) diff --git a/src/renderer/src/components/sidebar/workspace-card/surface/WorktreeCardVmStateBadge.tsx b/src/renderer/src/components/sidebar/workspace-card/surface/WorktreeCardVmStateBadge.tsx index 3689e4918bf..949c7629780 100644 --- a/src/renderer/src/components/sidebar/workspace-card/surface/WorktreeCardVmStateBadge.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/surface/WorktreeCardVmStateBadge.tsx @@ -4,7 +4,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' -import { ephemeralVmErrorText } from '@/lib/ephemeral-vm-error-copy' +import { ephemeralVmErrorText } from '@/runtime/ephemeral-vm/ephemeral-vm-error-copy' import type { EphemeralVmFailure } from '../../../../../../shared/ephemeral-vm-failure-copy' import type { ExecutionHostVmState } from '../../../../../../shared/execution-host/execution-host-health' diff --git a/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-agent-startup.ts b/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-agent-startup.ts index a7263c7bb24..421a873b375 100644 --- a/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-agent-startup.ts +++ b/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-agent-startup.ts @@ -2,7 +2,7 @@ import { resolveAgentStartupPlanInputs, type AgentStartupSettings } from '../../../../../../shared/agent-launch/startup/agent-startup-plan-inputs' -import type { LinkedWorkItemSummary } from '@/lib/new-workspace' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' import { resolveRepoExecutionHostPlatform } from '@/runtime/hosts/platform/execution-host-facts' import type { ExecutionHostPlatformFact } from '@/runtime/hosts/platform/execution-host-platform-fact' import type { AppState } from '@/store/types' diff --git a/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit-input.ts b/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit-input.ts index c7d59a529ed..005776440d8 100644 --- a/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit-input.ts +++ b/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit-input.ts @@ -1,5 +1,5 @@ import type { AgentLaunchChoice } from '@/lib/agent-session/launch/routing/agent-menu-selection' -import type { LinkedWorkItemSummary } from '@/lib/new-workspace' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' import type { AgentStartupSettings } from '../../../../../../shared/agent-launch/startup/agent-startup-plan-inputs' import type { AgentLaunchInputViews } from '../../../../../../shared/agent-launch/choices/agent-launch-choices' import type { FolderWorkspace } from '../../../../../../shared/folder-workspaces/folder-workspace-types' diff --git a/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit.test.ts b/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit.test.ts index c476b341e00..adb913d8f80 100644 --- a/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit.test.ts +++ b/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit.test.ts @@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { makeProjectGroup, makeFolderWorkspace } from './folder-workspace-composer-submit-fixtures' -import type * as NewWorkspaceModule from '@/lib/new-workspace' +import type * as NewWorkspaceModule from '@/lib/workspace/creation/new-workspace' const mocks = vi.hoisted(() => ({ activateAndRevealFolderWorkspace: vi.fn(), @@ -15,7 +15,7 @@ vi.mock('@/lib/workspace/activation/worktree-activation', async (importOriginal) return { ...actual, activateAndRevealFolderWorkspace: mocks.activateAndRevealFolderWorkspace } }) -vi.mock('@/lib/new-workspace', async (importOriginal) => { +vi.mock('@/lib/workspace/creation/new-workspace', async (importOriginal) => { const actual = await importOriginal() return { ...actual, @@ -91,55 +91,3 @@ describe('submitFolderWorkspaceCreate native-chat launch draft', () => { expect(seededDraftFor('tab-1')?.text).toBe(ISSUE_URL) }) }) - -it('keeps the folder legacy Arguments projection while carrying the entire non-native draft to the paired pane', async () => { - mocks.activateAndRevealFolderWorkspace.mockReturnValue({ primaryTabId: 'folder-agent' }) - await submitFolderWorkspaceCreate({ - projectGroup: makeProjectGroup(), - name: 'folder', - lastAutoName: '', - linkedWorkItem: linkedIssue, - note: 'keep this note', - quickAgent: 'codex', - autoRenameBranchFromWork: false, - agentCmdOverrides: {}, - launchInputs: { sessionOptions: { model: 'gpt-picked' } }, - legacyLaunchInputs: { - agentArgs: '--add-dir /host/shared', - sessionOptions: { model: 'gpt-picked' } - }, - createFolderWorkspace: vi.fn(async () => makeFolderWorkspace()), - onOpenChange: vi.fn() - }) - const startup = mocks.activateAndRevealFolderWorkspace.mock.calls.at(-1)?.[1].startup - expect(startup.command).toContain("'/host/shared'") - expect(startup.freshAgentLaunch.agentArgs).toBeUndefined() - expect(startup.freshAgentLaunch.prompt).toContain(ISSUE_URL) - expect(startup.freshAgentLaunch.prompt).toContain('keep this note') - expect(startup.freshAgentLaunch.legacy()).toMatchObject({ - pasteDraftAfterLaunch: expect.stringContaining('keep this note'), - submitPastedPrompt: false - }) -}) - -it('delivers an old-host Aider folder note using the plan whose bare command executes', async () => { - mocks.activateAndRevealFolderWorkspace.mockReturnValue({ primaryTabId: 'folder-aider' }) - await submitFolderWorkspaceCreate({ - projectGroup: makeProjectGroup(), - name: 'folder', - lastAutoName: '', - linkedWorkItem: null, - note: 'fix the folder', - quickAgent: 'aider', - autoRenameBranchFromWork: false, - agentCmdOverrides: {}, - createFolderWorkspace: vi.fn(async () => makeFolderWorkspace()), - onOpenChange: vi.fn() - }) - const startup = mocks.activateAndRevealFolderWorkspace.mock.lastCall?.[1].startup - expect(startup.command).toBe('aider') - const compatibility = startup.freshAgentLaunch.legacy() - expect(compatibility.startupPlan.launchCommand).toBe('aider') - expect(compatibility.pasteDraftAfterLaunch).toBe('fix the folder') - expect(compatibility.submitPastedPrompt).toBe(true) -}) diff --git a/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit.ts b/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit.ts index 5df1d7f3bfa..2324c10248d 100644 --- a/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit.ts +++ b/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit.ts @@ -1,6 +1,6 @@ import { ensureAgentLaunchPreferences } from '@/runtime/agent-launch-settings/use-host-agent-launch-preferences' import { resolveAgentStartupPlanInputs } from '../../../../../../shared/agent-launch/startup/agent-startup-plan-inputs' -import { ensureAgentStartupInTerminal } from '@/lib/new-workspace' +import { ensureAgentStartupInTerminal } from '@/lib/workspace/creation/new-workspace' import { seedNativeChatLaunchDraftForAgentTab } from '@/lib/agent-session/launch/prompt/agent-launch-prompt-delivery' import { createNonSecureContextUuid as createBrowserUuid } from '../../../../../../shared/non-secure-context-uuid' import { buildAgentStartupPlan } from '../../../../../../shared/agent-launch/startup/tui-agent-startup' @@ -19,7 +19,8 @@ import { } from '@/lib/agent-session/launch/routing/agent-session-launch-plan' import { newAgentLaunchRequestId } from '@/lib/agent-session/launch/routing/agent-launch-request-id' import { beginStructuredAgentSessionProvisionalLaunch } from '@/lib/agent-session/structured-agent-session-provisional-tab' -import { getNewWorkspaceProjectGroupHostId } from '@/lib/new-workspace-project-options' +import '@/lib/workspace/creation/new-workspace-project-options' +import { getRepoExecutionHostId } from '../../../../../../shared/execution-host' import { useAppStore } from '@/store/index' import { resolveExecutionHostAgentStartupShell } from '@/runtime/hosts/platform/execution-host-facts' import { @@ -91,7 +92,7 @@ export async function submitFolderWorkspaceCreate({ ? await ensureAgentLaunchPreferences(useAppStore.getState(), { kind: 'folder', runtimeEnvironmentId, - executionHostId: getNewWorkspaceProjectGroupHostId(projectGroup) + executionHostId: getRepoExecutionHostId(projectGroup) }) : undefined const effectiveSettings = settings @@ -145,7 +146,7 @@ export async function submitFolderWorkspaceCreate({ workspace: { kind: 'folder' as const, runtimeEnvironmentId, - executionHostId: getNewWorkspaceProjectGroupHostId(projectGroup) + executionHostId: getRepoExecutionHostId(projectGroup) }, prompt: launchDraftPrompt ?? note, promptDelivery: launchDraftPrompt ? ('draft' as const) : ('auto-submit' as const) diff --git a/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-source-selection.ts b/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-source-selection.ts index 21d14333ce0..c694d72f11f 100644 --- a/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-source-selection.ts +++ b/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-source-selection.ts @@ -1,4 +1,4 @@ -import type { LinkedWorkItemSummary } from '@/lib/new-workspace' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' import { buildWorkspaceSourceSelection, getWorkspaceSourceName, diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/use-main-list-model.ts b/src/renderer/src/components/sidebar/worktree-list/listing/use-main-list-model.ts index 6c9fbe9abd5..3c3a7c7d9cd 100644 --- a/src/renderer/src/components/sidebar/worktree-list/listing/use-main-list-model.ts +++ b/src/renderer/src/components/sidebar/worktree-list/listing/use-main-list-model.ts @@ -13,7 +13,7 @@ import { readHiddenVmCheckouts, subscribeHiddenVmCheckouts, withoutHiddenVmCheckouts -} from '@/lib/vm-create-hidden-checkouts' +} from '@/runtime/ephemeral-vm/vm-create-hidden-checkouts' import '../../../../../../shared/folder-workspaces/folder-workspace-execution-host' import { getFolderWorkspaceHostId } from '../../../../../../shared/folder-workspaces/folder-workspace-host-id' import type { FolderWorkspace } from '../../../../../../shared/folder-workspaces/folder-workspace-types' diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/use-section-rows.ts b/src/renderer/src/components/sidebar/worktree-list/listing/use-section-rows.ts index 954b9acaafd..b24d500c95b 100644 --- a/src/renderer/src/components/sidebar/worktree-list/listing/use-section-rows.ts +++ b/src/renderer/src/components/sidebar/worktree-list/listing/use-section-rows.ts @@ -19,7 +19,10 @@ import { useEffectiveCollapsedGroups } from './use-collapsed-groups' import type { Row } from '../../../../../../shared/sidebar-list/row-types' import type { SectionRowsArgs } from './sidebar-list-model' import { getLogicalRepoOrderRankById } from '../../../../../../shared/project-section-order' -import { readHiddenVmCheckouts, subscribeHiddenVmCheckouts } from '@/lib/vm-create-hidden-checkouts' +import { + readHiddenVmCheckouts, + subscribeHiddenVmCheckouts +} from '@/runtime/ephemeral-vm/vm-create-hidden-checkouts' import { getEmptyProjectPlaceholderRepoIds } from '../../../../../../shared/sidebar-list/empty-project-placeholder-repos' import { deferHostSectionCollapse, diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/use-visible-worktrees.ts b/src/renderer/src/components/sidebar/worktree-list/listing/use-visible-worktrees.ts index 9a83fe32d62..68a2647bc88 100644 --- a/src/renderer/src/components/sidebar/worktree-list/listing/use-visible-worktrees.ts +++ b/src/renderer/src/components/sidebar/worktree-list/listing/use-visible-worktrees.ts @@ -28,7 +28,7 @@ import { readHiddenVmCheckouts, subscribeHiddenVmCheckouts, withoutHiddenVmWorktrees -} from '@/lib/vm-create-hidden-checkouts' +} from '@/runtime/ephemeral-vm/vm-create-hidden-checkouts' const EMPTY_WORKTREE_ID_SET: ReadonlySet = new Set() diff --git a/src/renderer/src/components/sidebar/worktree-list/rows/header-create-workspace-target.ts b/src/renderer/src/components/sidebar/worktree-list/rows/header-create-workspace-target.ts index 891e991da69..7a687b40e05 100644 --- a/src/renderer/src/components/sidebar/worktree-list/rows/header-create-workspace-target.ts +++ b/src/renderer/src/components/sidebar/worktree-list/rows/header-create-workspace-target.ts @@ -4,12 +4,13 @@ import { getRepoHostIdentity, getRepoRegistrationHostIds } from '../../../../../../shared/repo-host-identity' -import { getComposerEligibleRepos } from '@/lib/new-workspace-composer-repo' +import '@/lib/workspace/creation/new-workspace-composer-repo' +import { getNewWorkspaceDialogEligibleRepos } from '../../../../../../shared/new-workspace-dialog-repo' import { useAppStore } from '@/store' import { getRepoWorkspaceCreationTargetHint, type WorkspaceCreationTargetHint -} from '@/lib/project-host-workspace-target' +} from '@/lib/workspace/creation/project-host-workspace-target' /** A single-host project header's create target, when its repo id alone can't pick the host. */ export function getHeaderCreateWorkspaceTarget( @@ -23,7 +24,7 @@ export function getHeaderCreateWorkspaceTarget( } const identity = getRepoHostIdentity(repo) // Plumbing repos the composer can't target keep the id path, which maps them to an eligible sibling. - return getComposerEligibleRepos(repos).some( + return getNewWorkspaceDialogEligibleRepos(repos).some( (candidate) => getRepoHostIdentity(candidate) === identity ) ? { initialWorkspaceTarget: getRepoWorkspaceCreationTargetHint(repo, projectHostSetups) } diff --git a/src/renderer/src/components/sidebar/worktree-list/rows/repo-header-create-state.ts b/src/renderer/src/components/sidebar/worktree-list/rows/repo-header-create-state.ts index a579c4fa333..c76c05984b4 100644 --- a/src/renderer/src/components/sidebar/worktree-list/rows/repo-header-create-state.ts +++ b/src/renderer/src/components/sidebar/worktree-list/rows/repo-header-create-state.ts @@ -1,7 +1,7 @@ import type { SshConnectionStatus } from '../../../../../../shared/ssh-types' import type { Repo } from '../../../../../../shared/repo-types' import { isGitRepoKind } from '../../../../../../shared/repo-kind' -import { getSelectedRepoSshGate } from '../../../../lib/new-workspace-ssh-gate' +import { getSelectedRepoSshGate } from '../../../../lib/workspace/creation/new-workspace-ssh-gate' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/sparse/SparseCheckoutPresetDraftForm.tsx b/src/renderer/src/components/sparse/SparseCheckoutPresetDraftForm.tsx index c783e7453d7..70af94523ba 100644 --- a/src/renderer/src/components/sparse/SparseCheckoutPresetDraftForm.tsx +++ b/src/renderer/src/components/sparse/SparseCheckoutPresetDraftForm.tsx @@ -8,7 +8,7 @@ import { SparseSelectedDirectoryList } from './SparseSelectedDirectoryList' import { addSparseDirectoryEntries } from './sparse-directory-entry-input' import { useTranslate } from '@/i18n/use-translate' import { normalizeSparseDirectoryLines } from '@/lib/sparse-paths' -import type { SparsePresetDirectoryParseResult } from '@/lib/sparse-preset-draft' +import type { SparsePresetDirectoryParseResult } from '@/components/sparse/sparse-preset-draft' export type SparsePresetDraft = { mode: 'new' | 'edit' diff --git a/src/renderer/src/components/sparse/SparseCheckoutPresetSelect.tsx b/src/renderer/src/components/sparse/SparseCheckoutPresetSelect.tsx index e10cdf6c722..70085deca83 100644 --- a/src/renderer/src/components/sparse/SparseCheckoutPresetSelect.tsx +++ b/src/renderer/src/components/sparse/SparseCheckoutPresetSelect.tsx @@ -4,7 +4,10 @@ import { Button } from '@/components/ui/button' import { SparsePresetChooser } from './SparsePresetChooser' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { useAppStore } from '@/store' -import { parseSparsePresetDirectories, validateSparsePresetName } from '@/lib/sparse-preset-draft' +import { + parseSparsePresetDirectories, + validateSparsePresetName +} from '@/components/sparse/sparse-preset-draft' import { useMountedRef } from '@/hooks/useMountedRef' import type { SparsePreset } from '../../../../shared/worktree/create-types' import { translate } from '@/i18n/i18n' diff --git a/src/renderer/src/lib/sparse-preset-draft.ts b/src/renderer/src/components/sparse/sparse-preset-draft.ts similarity index 100% rename from src/renderer/src/lib/sparse-preset-draft.ts rename to src/renderer/src/components/sparse/sparse-preset-draft.ts diff --git a/src/renderer/src/components/tab-bar/QuickLaunchButton.tsx b/src/renderer/src/components/tab-bar/QuickLaunchButton.tsx index a99202ec1f2..71398dcd243 100644 --- a/src/renderer/src/components/tab-bar/QuickLaunchButton.tsx +++ b/src/renderer/src/components/tab-bar/QuickLaunchButton.tsx @@ -13,7 +13,10 @@ import { toast } from 'sonner' import { launchAgentInNewTab } from '@/lib/agent-session/launch/new-tab/launch-agent-in-new-tab' import { newAgentLaunchRequestId } from '@/lib/agent-session/launch/routing/agent-launch-request-id' import { captureNativeChatComposerFocusIntent } from '@/components/native-chat/composer/focus/native-chat-composer-focus-intent' -import { agentLaunchPromptOwnership, newAgentPromptOutcome } from '@/lib/new-agent-prompt-outcome' +import { + agentLaunchPromptOwnership, + newAgentPromptOutcome +} from '@/lib/agent-session/launch/prompt/new-agent-prompt-outcome' import { activeAgentNotesSendFailureMessage } from '@/lib/agent-session/messaging/terminal/active-agent-note-send-result' import { AgentSettingsMenuItem } from '@/components/agent/AgentSettingsMenuItem' import { TabAgentSurfaceChoiceRow } from './TabAgentSurfaceChoiceRow' diff --git a/src/renderer/src/components/tab-bar/use-new-tab-agent-menu-rows.ts b/src/renderer/src/components/tab-bar/use-new-tab-agent-menu-rows.ts index f129bb84594..beac6031dbf 100644 --- a/src/renderer/src/components/tab-bar/use-new-tab-agent-menu-rows.ts +++ b/src/renderer/src/components/tab-bar/use-new-tab-agent-menu-rows.ts @@ -37,8 +37,8 @@ import { } from '@/runtime/hosts/capabilities/local-runtime-capabilities' import { useDetectedAgents, type AgentDetectionTarget } from '@/hooks/useDetectedAgents' import { readDetectedAgentsForTarget } from '@/lib/agent-session/launch/inventory/agent-detection-target-inventory' -import { useChatProgramFacts } from '@/lib/host-chat-program-acquisition' -import { readChatProgram } from '@/lib/host-chat-program' +import { useChatProgramFacts } from '@/lib/agent-session/launch/inventory/host-chat-program-acquisition' +import { readChatProgram } from '@/lib/agent-session/launch/inventory/host-chat-program' import { resolveAgentMenuSelection } from '@/lib/agent-session/launch/routing/agent-menu-selection' import { useHostAgentMenuSettings } from '@/runtime/agent-launch-settings/use-host-agent-launch-preferences' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' diff --git a/src/renderer/src/components/task-page/jira/Filters.tsx b/src/renderer/src/components/task-page/jira/Filters.tsx index 30bcaae445c..774acae850a 100644 --- a/src/renderer/src/components/task-page/jira/Filters.tsx +++ b/src/renderer/src/components/task-page/jira/Filters.tsx @@ -10,7 +10,7 @@ import { getJiraProjectSelectionKey } from '@/components/task-page/jira/task-pag import { useTranslate } from '@/i18n/use-translate' import { LoaderCircle, Plus, RefreshCw, Search, X } from 'lucide-react' import { Input } from '@/components/ui/input' -import { shouldSuppressEnterSubmit } from '@/lib/new-workspace-enter-guard' +import { shouldSuppressEnterSubmit } from '@/lib/workspace/creation/new-workspace-enter-guard' import { JiraProjectPicker } from '@/components/jira-project-picker' import { matchesJiraProject } from '../../../../../shared/jira/jira-project-reference' export function TaskPageJiraFilters({ diff --git a/src/renderer/src/components/task-page/linear/Filters.tsx b/src/renderer/src/components/task-page/linear/Filters.tsx index 2477efea984..0985ba41f49 100644 --- a/src/renderer/src/components/task-page/linear/Filters.tsx +++ b/src/renderer/src/components/task-page/linear/Filters.tsx @@ -7,7 +7,7 @@ import { useAppStore } from '@/store' import { Plus, LoaderCircle, RefreshCw, Search, X } from 'lucide-react' import LinearIssueAttributeFilterDropdowns from '@/components/linear-issue-attribute-filter-dropdowns' import { Input } from '@/components/ui/input' -import { shouldSuppressEnterSubmit } from '@/lib/new-workspace-enter-guard' +import { shouldSuppressEnterSubmit } from '@/lib/workspace/creation/new-workspace-enter-guard' import { defaultScopeSource } from '@/runtime/hosts/selection/default-creation-host' export function TaskPageLinearFilters({ model diff --git a/src/renderer/src/components/task-page/use-task-page-composer-actions.ts b/src/renderer/src/components/task-page/use-task-page-composer-actions.ts index 1cc1e63e0c3..254f0452a54 100644 --- a/src/renderer/src/components/task-page/use-task-page-composer-actions.ts +++ b/src/renderer/src/components/task-page/use-task-page-composer-actions.ts @@ -10,11 +10,11 @@ import { openLinearIssueWorkspaceOrStart } from '@/lib/work-items/linear/linear- import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import { bindTaskPageJiraItemSourceContext } from './jira/task-page-jira-item-source-context' -import type { LinkedWorkItemSummary } from '@/lib/new-workspace' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' import { shouldHideTaskPageListChrome } from './task-page-list-chrome-visibility' import { getJiraIssueWorkspaceSeed } from './task-page-source-context' import { findJiraIssueDefaultRepo } from '../../../../shared/jira/jira-project-reference' -import { getRepoWorkspaceCreationTargetHint } from '@/lib/project-host-workspace-target' +import { getRepoWorkspaceCreationTargetHint } from '@/lib/workspace/creation/project-host-workspace-target' export function useTaskPageComposerActions(model: TaskPageJiraListEffectsModel) { const { setTaskResumeState, diff --git a/src/renderer/src/components/task-page/use-task-page-search-actions.ts b/src/renderer/src/components/task-page/use-task-page-search-actions.ts index e029d804be1..ab1cc14a3df 100644 --- a/src/renderer/src/components/task-page/use-task-page-search-actions.ts +++ b/src/renderer/src/components/task-page/use-task-page-search-actions.ts @@ -11,7 +11,7 @@ import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import type { GitHubTaskKind } from '@/components/task-page/task-page-localized-options' import { getTaskPresetQuery } from '../../../../shared/work-items/task-preset-query' -import { shouldSuppressEnterSubmit } from '@/lib/new-workspace-enter-guard' +import { shouldSuppressEnterSubmit } from '@/lib/workspace/creation/new-workspace-enter-guard' import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router' export function useTaskPageSearchActions(model: TaskPageGitHubQuietRefreshModel) { const { diff --git a/src/renderer/src/components/task-page/use-task-page-workspace-actions.ts b/src/renderer/src/components/task-page/use-task-page-workspace-actions.ts index 859366393d8..90b24da2c30 100644 --- a/src/renderer/src/components/task-page/use-task-page-workspace-actions.ts +++ b/src/renderer/src/components/task-page/use-task-page-workspace-actions.ts @@ -2,7 +2,7 @@ import type { TaskPageSearchActionsModel } from './use-task-page-search-actions' import { useCallback } from 'react' import type { GitHubWorkItem } from '../../../../shared/github/work-item-types' import type { GitLabWorkItem } from '../../../../shared/gitlab-types' -import type { LinkedWorkItemSummary } from '@/lib/new-workspace' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' import { useAppStore } from '@/store' import { getWorkItemRepo } from '@/lib/work-items/work-item-repo-row' import { findGithubWorkItemWorkspaceAttachment } from '@/lib/work-items/github/github-work-item-workspace-attachment' diff --git a/src/renderer/src/components/terminal-agent-tab-shortcut.ts b/src/renderer/src/components/terminal-agent-tab-shortcut.ts index cd63dc8e7ec..73baaa50bcd 100644 --- a/src/renderer/src/components/terminal-agent-tab-shortcut.ts +++ b/src/renderer/src/components/terminal-agent-tab-shortcut.ts @@ -9,7 +9,7 @@ import { resolveDefaultAgentForNewTab, resolveDefaultAgentForWorktreeNewTab } from '@/lib/agent-session/launch/shortcuts/agent-tab-shortcuts' -import { chosenAgentChatUnlearned } from '@/lib/host-chat-program' +import { chosenAgentChatUnlearned } from '@/lib/agent-session/launch/inventory/host-chat-program' import { worktreeLaunchWorkspace } from '@/lib/agent-session/launch/routing/agent-launch-route-input' export type TerminalAgentTabShortcut = { diff --git a/src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-handler.test.ts b/src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-handler.test.ts deleted file mode 100644 index 71cd9f1d8b9..00000000000 --- a/src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-handler.test.ts +++ /dev/null @@ -1,221 +0,0 @@ -import { parseExecutionHostId } from '../../../../../../shared/execution-host' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = vi.hoisted(() => { - const worktreesByRepo: Record< - string, - { id: string; repoId: string; path: string; hostId?: string | null }[] - > = { - repo1: [{ id: 'wt-1', repoId: 'repo1', path: '/remote/repo', hostId: 'runtime:env-1' }] - } - const projects: { - id: string - localWindowsRuntimePreference: - | { kind: 'inherit-global' } - | { kind: 'windows-host' } - | { kind: 'wsl'; distro: string | null } - }[] = [ - { - id: 'repo1', - localWindowsRuntimePreference: { kind: 'inherit-global' as const } - } - ] - - return { - toastLoading: vi.fn(() => 'toast-1'), - toastDismiss: vi.fn(), - toastError: vi.fn(), - importExternalPathsToRuntime: vi.fn(), - resolveDroppedPathsForAgent: vi.fn(), - recordTerminalUserInputForLeaf: vi.fn(), - storeState: { - activeRepoId: 'repo1', - activeWorktreeId: 'wt-1', - settings: { activeRuntimeEnvironmentId: 'env-1' as string | null }, - projects, - repos: [ - { - id: 'repo1', - connectionId: null as string | null, - path: '/remote/repo', - executionHostId: 'runtime:env-1' as string | null - } - ], - worktreesByRepo, - sshConnectionStates: new Map< - string, - { remotePlatform?: NodeJS.Platform; connectionGeneration?: number } - >() - } - } -}) - -vi.mock('sonner', () => ({ - toast: { - loading: mocks.toastLoading, - dismiss: mocks.toastDismiss, - error: mocks.toastError, - message: vi.fn() - } -})) - -vi.mock('@/store/index', () => ({ - useAppStore: { - getState: () => mocks.storeState - } -})) - -vi.mock('@/runtime/files/imports/runtime-file-import-client', () => ({ - importExternalPathsToRuntime: mocks.importExternalPathsToRuntime -})) - -vi.mock('@/lib/new-workspace', () => ({ - CLIENT_PLATFORM: 'win32' -})) - -vi.mock('../terminal-input-activity', () => ({ - recordTerminalUserInputForLeaf: mocks.recordTerminalUserInputForLeaf -})) - -import './terminal-drop-handler' -import { handleNativeTerminalFileDrop as handleTerminalFileDrop } from './terminal-native-file-drop-destination' -import '../paste/terminal-bracketed-paste' - -function createTerminalTransport( - sendInput: ReturnType, - ptyId = 'pty-1', - sendInputAccepted?: ReturnType -) { - const host = parseExecutionHostId(mocks.storeState.repos[0]?.executionHostId) - return { - sendInput, - ...(sendInputAccepted ? { sendInputAccepted } : {}), - getPtyId: vi.fn(() => ptyId), - isConnected: vi.fn(() => true), - getExecutionHostId: () => (host?.kind === 'runtime' ? 'local' : (host?.id ?? 'local')), - getRuntimeEnvironmentId: () => (host?.kind === 'runtime' ? host.environmentId : null) - } -} - -describe('handleTerminalFileDrop', () => { - beforeEach(() => { - vi.clearAllMocks() - mocks.storeState.activeRepoId = 'repo1' - mocks.storeState.activeWorktreeId = 'wt-1' - vi.stubGlobal('window', { - api: { - fs: { - resolveDroppedPathsForAgent: mocks.resolveDroppedPathsForAgent - } - } - }) - mocks.storeState.settings = { activeRuntimeEnvironmentId: 'env-1' } - mocks.storeState.projects = [ - { - id: 'repo1', - localWindowsRuntimePreference: { kind: 'inherit-global' } - } - ] - mocks.storeState.repos = [ - { id: 'repo1', connectionId: null, path: '/remote/repo', executionHostId: 'runtime:env-1' } - ] - mocks.storeState.worktreesByRepo = { - repo1: [ - { - id: 'wt-1', - repoId: 'repo1', - path: '/remote/repo', - hostId: parseExecutionHostId(mocks.storeState.repos[0]?.executionHostId)?.id ?? 'local' - } - ] - } - mocks.storeState.sshConnectionStates = new Map() - }) - - it('does not paste runtime-uploaded paths when the target PTY changed', async () => { - let ptyId = 'pty-1' - mocks.importExternalPathsToRuntime.mockImplementation(async () => { - ptyId = 'pty-2' - return { - results: [ - { - sourcePath: '/Users/me/logo.png', - status: 'imported', - destPath: '/remote/repo/.orca/drops/logo.png', - kind: 'file', - renamed: false - } - ] - } - }) - const sendInput = vi.fn(() => true) - const focus = vi.fn() - const pane = { id: 1, leafId: 'leaf-1', terminal: { focus } } - const manager = { getActivePane: () => pane, getPanes: () => [pane] } - const transport = createTerminalTransport(sendInput) - transport.getPtyId.mockImplementation(() => ptyId) - - await handleTerminalFileDrop({ - manager: manager as never, - paneTransports: new Map([[1, transport]]) as never, - worktreeId: 'wt-1', - tabId: 'tab-1', - cwd: undefined, - pane, - paths: ['/Users/me/logo.png'] - }) - - expect(sendInput).not.toHaveBeenCalled() - expect(focus).not.toHaveBeenCalled() - expect(mocks.recordTerminalUserInputForLeaf).not.toHaveBeenCalled() - expect(mocks.toastDismiss).toHaveBeenCalledWith('toast-1') - }) - - it('does not paste local WSL resolved paths when the target PTY changed', async () => { - mocks.storeState.settings = { activeRuntimeEnvironmentId: 'focused-runtime' } - mocks.storeState.repos = [ - { id: 'repo1', connectionId: null, path: '/repo', executionHostId: 'local' } - ] - mocks.storeState.worktreesByRepo = { - repo1: [ - { - id: 'wt-1', - repoId: 'repo1', - path: '\\\\wsl.localhost\\Ubuntu-24.04\\home\\user\\repo' - } - ] - } - let ptyId = 'pty-1' - mocks.resolveDroppedPathsForAgent.mockImplementation(async () => { - ptyId = 'pty-2' - return { - failed: [], - resolvedPaths: ['/mnt/c/Users/Name/My Project/file.txt'], - skipped: [] - } - }) - const sendInput = vi.fn(() => true) - const focus = vi.fn() - const pane = { id: 1, leafId: 'leaf-1', terminal: { focus } } - const manager = { - getActivePane: () => pane, - getPanes: () => [pane] - } - const transport = createTerminalTransport(sendInput) - transport.getPtyId.mockImplementation(() => ptyId) - - await handleTerminalFileDrop({ - manager: manager as never, - paneTransports: new Map([[1, transport]]) as never, - worktreeId: 'wt-1', - tabId: 'tab-1', - cwd: undefined, - pane, - paths: ['C:\\Users\\Name\\My Project\\file.txt'] - }) - - expect(sendInput).not.toHaveBeenCalled() - expect(focus).not.toHaveBeenCalled() - expect(mocks.recordTerminalUserInputForLeaf).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-internal-handler.test.ts b/src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-internal-handler.test.ts index 440d8864e34..3858b5482db 100644 --- a/src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-internal-handler.test.ts +++ b/src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-internal-handler.test.ts @@ -65,7 +65,7 @@ vi.mock('@/runtime/files/imports/runtime-file-import-client', () => ({ importExternalPathsToRuntime: mocks.importExternalPathsToRuntime })) -vi.mock('@/lib/new-workspace', () => ({ +vi.mock('@/lib/workspace/creation/new-workspace', () => ({ CLIENT_PLATFORM: 'win32' })) diff --git a/src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-local-wsl.ts b/src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-local-wsl.ts index 16941accf74..82323057e72 100644 --- a/src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-local-wsl.ts +++ b/src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-local-wsl.ts @@ -1,5 +1,5 @@ import { getLocalProjectExecutionRuntimeContext } from '@/lib/local-preflight-context' -import { CLIENT_PLATFORM } from '@/lib/new-workspace' +import { CLIENT_PLATFORM } from '@/lib/workspace/creation/new-workspace' import type { useAppStore } from '@/store/index' import { isWindowsAbsolutePathLike } from '../../../../../../shared/cross-platform-path' import { parseWslUncPath } from '../../../../../../shared/wsl-paths' diff --git a/src/renderer/src/components/terminal-pane/parking/output-watchers/parked-terminal-command-status.ts b/src/renderer/src/components/terminal-pane/parking/output-watchers/parked-terminal-command-status.ts index 1e38c1ef0fc..3c8dd072f58 100644 --- a/src/renderer/src/components/terminal-pane/parking/output-watchers/parked-terminal-command-status.ts +++ b/src/renderer/src/components/terminal-pane/parking/output-watchers/parked-terminal-command-status.ts @@ -6,7 +6,7 @@ import { isShellProcess } from '../../../../../../shared/agent-status/process/sh import { dispatchTerminalCommandFinishedEvent } from '@/hooks/terminal-command-finished-event' import { resolveLiveAgentStatusConnectionRouting } from '@/lib/agent-status/ownership/agent-status-connection-ownership' import { getConnectionIdFromState } from '@/lib/workspace/ownership/connection-owner-resolution' -import { rendererAgentStatusObservations } from '@/lib/renderer-agent-status-observations' +import { rendererAgentStatusObservations } from '@/lib/agent-status/evidence/renderer-agent-status-observations' import { isRetainedProgramResult } from '@/lib/program-status/row' import { useAppStore } from '@/store/index' import { diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/command-code-pane-status.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/command-code-pane-status.ts index 065c9384ce0..fe4b8141520 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/command-code-pane-status.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/command-code-pane-status.ts @@ -6,7 +6,7 @@ import { setCommandCodeDoneSettleExecutor } from '../../agent-completion/command-code/command-code-done-settle' import { canCommandCodeOutputOwnPane } from '../../agent-completion/command-code/command-code-output-ownership' -import { rendererAgentStatusObservations } from '@/lib/renderer-agent-status-observations' +import { rendererAgentStatusObservations } from '@/lib/agent-status/evidence/renderer-agent-status-observations' export function bindCommandCodeOutputStatus(session: ConnectPanePtySession): void { session.canApplyCommandCodeOutputStatus = (): boolean => { diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/renderer-owned-pane-status.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/renderer-owned-pane-status.ts index 45411a1398c..f606d0df661 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/renderer-owned-pane-status.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/renderer-owned-pane-status.ts @@ -9,7 +9,7 @@ import { registerRendererOwnedAgentStatusPane, resolveRendererOwnedAgentStatusTiming } from '../../agent-status/renderer-owned-agent-status-registry' -import { rendererAgentStatusObservations } from '@/lib/renderer-agent-status-observations' +import { rendererAgentStatusObservations } from '@/lib/agent-status/evidence/renderer-agent-status-observations' import type { ConnectPanePtySession } from '../connect-pane-pty-session' export function installRendererOwnedPaneStatus(session: ConnectPanePtySession): void { diff --git a/src/renderer/src/components/terminal-pane/pty-connection/deferred-cold-restore-and-snapshot.ts b/src/renderer/src/components/terminal-pane/pty-connection/deferred-cold-restore-and-snapshot.ts index 0c22d59bde5..57e4ffc393c 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/deferred-cold-restore-and-snapshot.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/deferred-cold-restore-and-snapshot.ts @@ -5,7 +5,7 @@ import { INITIAL_MODE_2031_REPLY_SCAN_STATE } from '../../../../../shared/termin import { waitForTerminalOutputParsed } from '@/lib/pane-manager/pane-terminal-output-scheduler' import { executeTerminalStartupCommandPaste } from '../input/paste/terminal-startup-command-paste' import { resolveTerminalPasteRuntime } from '../input/paste/terminal-paste-runtime' -import { CLIENT_PLATFORM } from '@/lib/new-workspace' +import { CLIENT_PLATFORM } from '@/lib/workspace/creation/new-workspace' import { recordPaneWakeThroughLayoutOwner } from '@/store/terminals/terminal-sleep-layout-owner' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../shared/layout-owner-switch' diff --git a/src/renderer/src/components/terminal-pane/pty-connection/emulation/native-windows-pane-policy.ts b/src/renderer/src/components/terminal-pane/pty-connection/emulation/native-windows-pane-policy.ts index 5f8e2de582d..b7d81be037a 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/emulation/native-windows-pane-policy.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/emulation/native-windows-pane-policy.ts @@ -3,7 +3,7 @@ import { isLocalNativeWindowsConpty, resolveWindowsShellOverride } from '@/lib/pane-manager/windows-pty-compatibility' -import { CLIENT_PLATFORM } from '@/lib/new-workspace' +import { CLIENT_PLATFORM } from '@/lib/workspace/creation/new-workspace' import { resolveLatestAgentDoneStartedAt } from '../notifications/agent-done-started-at' import type { ConnectPanePtySession } from '../connect-pane-pty-session' diff --git a/src/renderer/src/components/terminal-pane/pty-connection/output/write-pty-output-to-xterm.ts b/src/renderer/src/components/terminal-pane/pty-connection/output/write-pty-output-to-xterm.ts index d422d9382bb..b4a3bade7b4 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/output/write-pty-output-to-xterm.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/output/write-pty-output-to-xterm.ts @@ -4,7 +4,7 @@ import { takeCurrentTerminalDeliveryCredit } from '@/lib/pane-manager/terminal-d import { nativeWindowsRewriteNeedsFollowupRenderRefresh } from '@/lib/pane-manager/terminal-complex-script' import { writeTerminalOutput } from '@/lib/pane-manager/pane-terminal-output-scheduler' import { forceFullViewportPresent } from '@/lib/pane-manager/terminal-render-pause-release' -import { CLIENT_PLATFORM } from '@/lib/new-workspace' +import { CLIENT_PLATFORM } from '@/lib/workspace/creation/new-workspace' import { FOREGROUND_SYNCHRONIZED_FRAME_INTERACTIVE_WINDOW_MS } from './foreground-output-budgets' import { scanSynchronizedOutput } from '../../../../../../shared/terminal/protocol/escape/terminal-synchronized-output-scan' diff --git a/src/renderer/src/components/terminal-pane/pty-connection/startup/initial-agent-status.ts b/src/renderer/src/components/terminal-pane/pty-connection/startup/initial-agent-status.ts index 91fac7a8b19..c13b70f83ad 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/startup/initial-agent-status.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/startup/initial-agent-status.ts @@ -1,6 +1,6 @@ import { useAppStore } from '@/store' import { resolveCompatibleAgentTypeForOwner } from '../../../../../../shared/agent-status/title/agent-title-owner' -import { rendererAgentStatusObservations } from '@/lib/renderer-agent-status-observations' +import { rendererAgentStatusObservations } from '@/lib/agent-status/evidence/renderer-agent-status-observations' import type { ConnectPanePtySession } from '../connect-pane-pty-session' export function bindInitialAgentStatus(session: ConnectPanePtySession): void { diff --git a/src/renderer/src/components/terminal-pane/pty-connection/test-fixtures/pty-connection-test-environment.ts b/src/renderer/src/components/terminal-pane/pty-connection/test-fixtures/pty-connection-test-environment.ts index 2d53abce03a..9a9dae38d5f 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/test-fixtures/pty-connection-test-environment.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/test-fixtures/pty-connection-test-environment.ts @@ -192,7 +192,7 @@ async function resetSharedTerminalModuleState(): Promise { import('@/lib/pane-manager/pane-terminal-output-queue-registry'), import('@/lib/agent-session/launch/startup/agent-startup-delayed-delivery'), import('@/lib/agent-session/launch/startup/agent-startup-delivery-guards'), - import('@/lib/hook-command-delayed-delivery'), + import('@/lib/workspace/creation/setup/hook-command-delayed-delivery'), import('../../agent-completion/agent-completion-identity-store'), import('../../agent-completion/command-code/command-code-done-settle'), import('../../agent-completion/process-inspection/agent-process-inspection-queue'), diff --git a/src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport.ts b/src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport.ts index 84ff3ef267c..faefc6be092 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport.ts @@ -1,7 +1,7 @@ import type { TerminalOutputCadence } from '../../../../../../shared/terminal/stream/terminal-multiplex-flow-control' import { lastVerifiedRuntimeStatus } from '../../../../../../shared/remote-runtime/host-status/runtime-host-status' import { webTerminalPlacementParentTabId } from '@/runtime/hosted-terminals/placement/web-session-terminal-placement' -import { pairedAgentLaunchInputs } from '@/lib/paired-agent-launch-inputs' +import { pairedAgentLaunchInputs } from '@/lib/agent-session/launch/routing/paired-agent-launch-inputs' import { agentSessionCreateCapabilities, agentSessionCreateRequest, @@ -3942,7 +3942,7 @@ export function createRemoteRuntimePtyTransport( .catch(() => false) .then(async (promptDelivered) => { const { completeWebHostAgentLaunch } = - await import('@/lib/web-host-agent-launch-completion') + await import('@/lib/agent-session/launch/new-tab/web-host-agent-launch-completion') completeWebHostAgentLaunch({ agent: launchAgentToSend, worktreeId, diff --git a/src/renderer/src/components/terminal-pane/session-fork/terminal-agent-session-fork.ts b/src/renderer/src/components/terminal-pane/session-fork/terminal-agent-session-fork.ts index fb1282278bc..df5d16cfe1c 100644 --- a/src/renderer/src/components/terminal-pane/session-fork/terminal-agent-session-fork.ts +++ b/src/renderer/src/components/terminal-pane/session-fork/terminal-agent-session-fork.ts @@ -2,7 +2,7 @@ import { toast } from 'sonner' import type { ManagedPane } from '@/lib/pane-manager/pane-manager-types' import { launchAgentInNewTab } from '@/lib/agent-session/launch/new-tab/launch-agent-in-new-tab' import { settleAgentTabLaunch } from '@/lib/agent-session/launch/new-tab/launch-agent-in-new-tab-host-agents' -import { newAgentPromptOutcome } from '@/lib/new-agent-prompt-outcome' +import { newAgentPromptOutcome } from '@/lib/agent-session/launch/prompt/new-agent-prompt-outcome' import { buildAgentSessionForkPrompt } from '@/lib/agent-session/context/agent-session-fork-context' import { activateAndRevealWorktree } from '@/lib/workspace/activation/worktree-activation' import { resolveOwner } from '@/lib/workspace/ownership/resolve-owner' diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx index 7c9f79b5e7d..38d8aecbe46 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx @@ -2,7 +2,7 @@ import React from 'react' import { AlertTriangle, Loader2 } from 'lucide-react' import { cn } from '@/lib/utils' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { resolveVmEnvironmentCheckDecision } from '@/lib/ephemeral-vm-environment-check-decision' +import { resolveVmEnvironmentCheckDecision } from '@/runtime/ephemeral-vm/ephemeral-vm-environment-check-decision' import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' import { toast } from 'sonner' import type { EnvironmentSetupFailureContext } from '../../../../shared/environment-setup-agent-prompt' @@ -45,7 +45,7 @@ function startFixWithAgent(args: { recipeId: string failure: EnvironmentSetupFailureContext }): void { - void import('@/lib/environment-setup-agent-launch') + void import('@/lib/agent-session/launch/environment-setup-agent-launch') .then(({ launchEnvironmentSetupAgent }) => launchEnvironmentSetupAgent(args)) .catch((launchError: unknown) => { toast.error(launchError instanceof Error ? launchError.message : String(launchError)) diff --git a/src/renderer/src/components/worktree-jump/WorktreeJumpPalette.linear-url.test.tsx b/src/renderer/src/components/worktree-jump/WorktreeJumpPalette.linear-url.test.tsx index df237706840..99bf66b8035 100644 --- a/src/renderer/src/components/worktree-jump/WorktreeJumpPalette.linear-url.test.tsx +++ b/src/renderer/src/components/worktree-jump/WorktreeJumpPalette.linear-url.test.tsx @@ -2,7 +2,7 @@ import { linearIssueReadFixture } from '@/store/slices/linear/linear-slice-test- // @vitest-environment happy-dom import { act } from 'react' -import { flushSync } from 'react-dom' + import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as ReactI18Next from 'react-i18next' @@ -10,9 +10,6 @@ import { useAppStore } from '@/store/index' import type { AppState } from '@/store/types' import type { LinearIssue } from '../../../../shared/linear/issue-types' -import type { Repo } from '../../../../shared/repo-types' -import { projectHostSetupProjectionFromRepos } from '../../../../shared/project-host-setup-projection' -import { resolveWorkspaceCreationTarget } from '@/lib/project-host-workspace-target' import WorktreeJumpPalette from './WorktreeJumpPalette' import { makeRecentTabState, makeRepo } from './worktree-jump-palette-test-fixtures' @@ -211,12 +208,6 @@ async function renderPalette(overrides: Partial): Promise { await flushEffects() } -function getCommandValue(): string { - return ( - testContainer.querySelector('[data-command-dialog]')?.dataset.commandValue ?? '' - ) -} - describe('WorktreeJumpPalette Linear URL intent', () => { beforeEach(() => { globalThis.IS_REACT_ACT_ENVIRONMENT = true @@ -283,71 +274,6 @@ describe('WorktreeJumpPalette Linear URL intent', () => { }) }) - it('keeps runtime folder projects as the Linear lookup and composer owner', async () => { - const folderRepo: Repo = { - ...makeRepo(), - id: 'folder-repo', - kind: 'folder' as const, - executionHostId: 'runtime:folder-env' - } - const fetchLinearIssue = vi.fn(() => - linearIssueReadFixture(async () => makeLinearIssue()) - ) - const prefetchWorktreeCreateBase = vi.fn(async () => {}) - await renderPalette({ - activeRepoId: folderRepo.id, - repos: [folderRepo], - fetchLinearIssue, - prefetchWorktreeCreateBase - }) - await act(async () => setCommandQuery?.(LINEAR_URL)) - await flushEffects() - - expect(fetchLinearIssue).toHaveBeenCalledWith( - 'STA-4084', - 'linear-workspace-1', - expect.objectContaining({ - sourceContext: expect.objectContaining({ - provider: 'linear', - projectId: 'repo:folder-repo', - projectHostSetupId: 'folder-repo', - repoId: 'folder-repo', - hostId: 'runtime:folder-env' - }) - }) - ) - - await act(async () => { - testContainer.querySelector('[data-command-item="__create_worktree__"]')?.click() - await Promise.resolve() - }) - await flushEffects() - - expect(useAppStore.getState().modalData).toMatchObject({ - initialRepoId: 'folder-repo', - taskSourceContext: { - provider: 'linear', - projectId: 'repo:folder-repo', - projectHostSetupId: 'folder-repo', - repoId: 'folder-repo', - hostId: 'runtime:folder-env' - } - }) - const projection = projectHostSetupProjectionFromRepos([folderRepo]) - expect( - resolveWorkspaceCreationTarget({ - eligibleRepos: [folderRepo], - projects: projection.projects, - projectHostSetups: projection.setups, - initialRepoId: 'folder-repo', - projectId: 'repo:folder-repo', - hostId: 'runtime:folder-env', - projectHostSetupId: 'folder-repo' - }) - ).toMatchObject({ status: 'ready', target: { repoId: 'folder-repo' } }) - expect(prefetchWorktreeCreateBase).not.toHaveBeenCalled() - }) - it('does not open the composer after the palette closes during lookup', async () => { const issueLookup = deferredValue() await renderPalette({ @@ -409,63 +335,4 @@ describe('WorktreeJumpPalette Linear URL intent', () => { linkedWorkItem: { linearIdentifier: 'STA-4099', title: 'Current second issue' } }) }) - - it('does not let a stale lookup replace a newer URL preview', async () => { - const firstLookup = deferredValue() - const secondLookup = deferredValue() - await renderPalette({ - fetchLinearIssue: vi.fn((identifier: string) => - linearIssueReadFixture(() => - identifier === 'STA-4084' ? firstLookup.promise : secondLookup.promise - ) - ) - }) - - vi.useFakeTimers() - await act(async () => setCommandQuery?.('https://linear.app/stably/issue/STA-4084/first')) - await flushEffects() - await act(async () => { - await vi.advanceTimersByTimeAsync(200) - }) - expect(testContainer.textContent).toContain('Loading Linear issue…') - - await act(async () => { - flushSync(() => setCommandQuery?.('https://linear.app/stably/issue/STA-4099/second')) - const currentPendingRow = testContainer.querySelector( - '[data-cmd-j-linear-issue-preview="true"]' - ) - expect(currentPendingRow?.getAttribute('aria-label')).toBe( - 'Create worktree from Linear issue STA-4099' - ) - expect(currentPendingRow?.textContent).toContain('Create worktree from Linear issue') - expect(currentPendingRow?.textContent).not.toContain('Loading Linear issue…') - }) - await flushEffects() - - await act(async () => { - firstLookup.resolve(makeLinearIssue({ title: 'Stale first issue' })) - await firstLookup.promise - }) - await flushEffects() - - expect(testContainer.textContent).toContain('STA-4099') - expect(testContainer.textContent).not.toContain('Stale first issue') - - await act(async () => { - secondLookup.resolve( - makeLinearIssue({ - id: 'issue-sta-4099', - identifier: 'STA-4099', - title: 'Current second issue', - url: 'https://linear.app/stably/issue/STA-4099/current-second-issue' - }) - ) - await secondLookup.promise - }) - await flushEffects() - - expect(testContainer.textContent).toContain('Current second issue') - expect(testContainer.textContent).not.toContain('Stale first issue') - expect(getCommandValue()).toBe('__create_worktree__') - }) }) diff --git a/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-quick-actions.ts b/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-quick-actions.ts index 74641f3c290..d0ee8be3a8c 100644 --- a/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-quick-actions.ts +++ b/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-quick-actions.ts @@ -13,10 +13,10 @@ import { buildCmdJBrowserNavigationAction } from '@/components/cmd-j/browser-nav import { openWorkspaceBrowserTab } from '@/lib/browser/workspace/workspace-browser-tab-open' import { findGroupAndWorktree } from '@/store/slices/tabs/tab-group-state' import { - getComposerEligibleRepos, - resolveComposerActiveRepoId, - resolveComposerGitRepoId -} from '@/lib/new-workspace-composer-repo' + getNewWorkspaceDialogEligibleRepos, + resolveNewWorkspaceDialogGitRepoId +} from '../../../../shared/new-workspace-dialog-repo' +import { resolveComposerActiveRepoId } from '@/lib/workspace/creation/new-workspace-composer-repo' import type { QuickActionPaletteItem, SettingsPaletteItem } from './worktree-jump-palette-model' import type { WorktreeJumpPaletteLocalState } from './use-worktree-jump-palette-local-state' import type { WorktreeJumpPaletteOpenTabs } from './use-worktree-jump-palette-open-tabs' @@ -30,8 +30,8 @@ function getComposerPrefetchRepoId( state: ReturnType, initialRepoId?: string ): string | null { - const eligibleRepos = getComposerEligibleRepos(state.repos) - return resolveComposerGitRepoId({ + const eligibleRepos = getNewWorkspaceDialogEligibleRepos(state.repos) + return resolveNewWorkspaceDialogGitRepoId({ eligibleRepos, initialRepoId, activeRepoId: resolveComposerActiveRepoId( diff --git a/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-store-state.ts b/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-store-state.ts index fb5113b520b..1e46542fe57 100644 --- a/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-store-state.ts +++ b/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-store-state.ts @@ -10,7 +10,7 @@ import { readHiddenVmCheckouts, subscribeHiddenVmCheckouts, withoutHiddenVmWorktreesByRepo -} from '@/lib/vm-create-hidden-checkouts' +} from '@/runtime/ephemeral-vm/vm-create-hidden-checkouts' import { selectPaletteIndexStatusSnapshot, selectPaletteStatusInputs diff --git a/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-task-url.ts b/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-task-url.ts index 871fd719a28..ea8cb1c2b14 100644 --- a/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-task-url.ts +++ b/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-task-url.ts @@ -7,11 +7,9 @@ import { } from '@/store/slices/linear/linear-issue-read-lifecycle' import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { useAppStore } from '@/store/index' -import { - getComposerEligibleRepos, - resolveComposerActiveRepoId -} from '@/lib/new-workspace-composer-repo' -import { resolveWorkspaceCreationTarget } from '@/lib/project-host-workspace-target' +import { getNewWorkspaceDialogEligibleRepos } from '../../../../shared/new-workspace-dialog-repo' +import { resolveComposerActiveRepoId } from '@/lib/workspace/creation/new-workspace-composer-repo' +import { resolveWorkspaceCreationTarget } from '@/lib/workspace/creation/project-host-workspace-target' import { lookupCmdJGitHubUrlWorkItem } from '@/lib/cmd-j-github-url-lookup' import { lookupLinearIssueUrl } from '@/lib/work-items/linear/linear-issue-url-lookup' import { @@ -43,7 +41,7 @@ export type CmdJGitHubWorkItemPreview = { /** The target New workspace would default to, used to scope task-link lookups to the same checkout. */ function getComposerDefaultWorkspaceTarget(state: ReturnType) { - const eligibleRepos = getComposerEligibleRepos(state.repos) + const eligibleRepos = getNewWorkspaceDialogEligibleRepos(state.repos) const activeRepoId = resolveComposerActiveRepoId( state.repos, eligibleRepos, diff --git a/src/renderer/src/components/worktree-jump/worktree-jump-palette-create-worktree.ts b/src/renderer/src/components/worktree-jump/worktree-jump-palette-create-worktree.ts index b6ac24150d0..8bbe8c86e3c 100644 --- a/src/renderer/src/components/worktree-jump/worktree-jump-palette-create-worktree.ts +++ b/src/renderer/src/components/worktree-jump/worktree-jump-palette-create-worktree.ts @@ -9,7 +9,7 @@ import { getLinkedWorkItemSuggestedName, getLinkedWorkItemWorkspaceName } from '../../../../shared/workspace-name' -import type { LinkedWorkItemSummary } from '@/lib/new-workspace' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' import type { WorktreeJumpPaletteCreateWorktreeInput } from './worktree-jump-palette-create-worktree-input' import { lookupGitHubWorkItemForSource } from '@/lib/work-items/github/github-work-item-source-lookup' import { activateAndRevealWorkspace } from '@/lib/workspace/activation/worktree-activation' diff --git a/src/renderer/src/hooks/composer-state/async-composer-state.ts b/src/renderer/src/hooks/composer-state/async-composer-state.ts index 6f0a3a7b735..e2b6ecf958d 100644 --- a/src/renderer/src/hooks/composer-state/async-composer-state.ts +++ b/src/renderer/src/hooks/composer-state/async-composer-state.ts @@ -25,7 +25,7 @@ type ComposerAsyncStateInput = Pick< import { useState, useRef, useEffect, useCallback } from 'react' import type { OrcaHooks, SetupAgentStartupPolicy } from '../../../../shared/orca-yaml-hook-types' import type { IssueCommandReadResult } from '@/runtime/repo-hooks/runtime-hooks-client' -import type { WorkspaceCreateErrorDisplay } from '@/lib/workspace-create-error-format' +import type { WorkspaceCreateErrorDisplay } from '@/lib/workspace/creation/workspace-create-error-format' import type { GitHubWorkItem } from '../../../../shared/github/work-item-types' import { CONTEXTUAL_TOUR_ENABLE_AUTO_WORKSPACE_NAME_EVENT } from '@/components/contextual-tours/contextual-tour-composer-events' import type { GitHubRepositoryIdentity } from '../../../../shared/github/pull-request-types' diff --git a/src/renderer/src/hooks/composer-state/async-model.ts b/src/renderer/src/hooks/composer-state/async-model.ts index 5cab5e84ad9..46dadb1a029 100644 --- a/src/renderer/src/hooks/composer-state/async-model.ts +++ b/src/renderer/src/hooks/composer-state/async-model.ts @@ -3,7 +3,7 @@ import type { RefObject } from 'react' import type { GitHubWorkItem } from '../../../../shared/github/work-item-types' import type { OrcaHooks, SetupAgentStartupPolicy } from '../../../../shared/orca-yaml-hook-types' import type { GitHubRepositoryIdentity } from '../../../../shared/github/pull-request-types' -import type { WorkspaceCreateErrorDisplay } from '@/lib/workspace-create-error-format' +import type { WorkspaceCreateErrorDisplay } from '@/lib/workspace/creation/workspace-create-error-format' import type { IssueCommandReadResult } from '@/runtime/repo-hooks/runtime-hooks-client' import type { SmartSourceSelection } from './source-selection-decisions' diff --git a/src/renderer/src/hooks/composer-state/composer-agent-rows-target.ts b/src/renderer/src/hooks/composer-state/composer-agent-rows-target.ts index a91bd7e7f47..32d98ece516 100644 --- a/src/renderer/src/hooks/composer-state/composer-agent-rows-target.ts +++ b/src/renderer/src/hooks/composer-state/composer-agent-rows-target.ts @@ -1,4 +1,5 @@ -import { getNewWorkspaceProjectGroupHostId } from '@/lib/new-workspace-project-options' +import '@/lib/workspace/creation/new-workspace-project-options' +import { getRepoExecutionHostId } from '../../../../shared/execution-host' import type { AgentDetectionTarget } from '@/hooks/useDetectedAgents' import type { AgentMenuRowsTarget } from '@/components/tab-bar/use-new-tab-agent-menu-rows' import type { ComposerModel } from './composer-model' @@ -18,7 +19,7 @@ export function resolveComposerAgentRows(state: ComposerModel): ComposerAgentRow workspace: { kind: 'folder', runtimeEnvironmentId: state.folderTargetRuntimeEnvironmentId, - executionHostId: getNewWorkspaceProjectGroupHostId(group) + executionHostId: getRepoExecutionHostId(group) } }, detectionTarget: state.folderTargetAgentDetectionTarget diff --git a/src/renderer/src/hooks/composer-state/composer-card-props.ts b/src/renderer/src/hooks/composer-state/composer-card-props.ts index 4ee1c9bb6d2..61a47093169 100644 --- a/src/renderer/src/hooks/composer-state/composer-card-props.ts +++ b/src/renderer/src/hooks/composer-state/composer-card-props.ts @@ -1,6 +1,6 @@ import { resolveComposerAttachmentTarget } from './composer-attachment-target' -import { getAttachmentLabel } from '@/lib/new-workspace' -import { getQuickComposerCreateDisabled } from '@/lib/new-workspace-create-gates' +import { getAttachmentLabel } from '@/lib/workspace/creation/new-workspace' +import { getQuickComposerCreateDisabled } from '@/lib/workspace/creation/new-workspace-create-gates' import type { ComposerModel } from './composer-model' import { resolveComposerAgentRows } from './composer-agent-rows-target' import type { ComposerCardActionProps, ComposerCardSourceProps } from './composer-card-contract' diff --git a/src/renderer/src/hooks/composer-state/composer-decisions.ts b/src/renderer/src/hooks/composer-state/composer-decisions.ts index 22a77290216..8074d655cd3 100644 --- a/src/renderer/src/hooks/composer-state/composer-decisions.ts +++ b/src/renderer/src/hooks/composer-state/composer-decisions.ts @@ -14,9 +14,9 @@ import type { GitHubWorkItem } from '../../../../shared/github/work-item-types' import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context' import type { JiraIssueKeyCasing } from '../../../../shared/ui-chrome-types' -import type { LinkedWorkItemSummary } from '@/lib/new-workspace' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' -import type { WorkspaceCreationTargetHint } from '@/lib/project-host-workspace-target' +import type { WorkspaceCreationTargetHint } from '@/lib/workspace/creation/project-host-workspace-target' export type ComposerDecisions = { canResolveFolderSmartGitHubSubmit: (input: { hasFolderSourceRepos: boolean }) => boolean diff --git a/src/renderer/src/hooks/composer-state/composer-submit-model.ts b/src/renderer/src/hooks/composer-state/composer-submit-model.ts index 4d699d85f81..3f33a40b973 100644 --- a/src/renderer/src/hooks/composer-state/composer-submit-model.ts +++ b/src/renderer/src/hooks/composer-state/composer-submit-model.ts @@ -3,9 +3,9 @@ import type { QuickSubmitOptions } from './quick-creation-request' import type { GitPushTarget } from '../../../../shared/worktree/types' import type { SetupDecision } from '../../../../shared/worktree/create-types' import type { WorkspaceIntentName } from '../../../../shared/workspace-name' -import type { LinkedWorkItemSummary } from '@/lib/new-workspace' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' import type { WorktreeCreationRequest } from '@/lib/workspace/creation/pending-worktree-creation' -import type { ComposerCreateHandoff } from '@/lib/composer-create-handoff' +import type { ComposerCreateHandoff } from '@/lib/workspace/creation/composer-create-handoff' import type { PendingSmartGitHubSubmitResolution } from './source-selection-decisions' type SmartCreateNames = { diff --git a/src/renderer/src/hooks/composer-state/composer-target-store.ts b/src/renderer/src/hooks/composer-state/composer-target-store.ts index 7379256e081..18e96c7eca6 100644 --- a/src/renderer/src/hooks/composer-state/composer-target-store.ts +++ b/src/renderer/src/hooks/composer-state/composer-target-store.ts @@ -1,19 +1,17 @@ import { useMemo } from 'react' import { useAppStore } from '@/store' import { useShallow } from 'zustand/react/shallow' -import { - getComposerEligibleRepos, - resolveComposerActiveRepoId -} from '@/lib/new-workspace-composer-repo' +import { getNewWorkspaceDialogEligibleRepos } from '../../../../shared/new-workspace-dialog-repo' +import { resolveComposerActiveRepoId } from '@/lib/workspace/creation/new-workspace-composer-repo' import { buildExecutionHostRegistry } from '../../../../shared/execution-host/execution-host-registry' import { getHostDisplayLabelOverrides } from '../../../../shared/host-setting-overrides' import type { GitHubWorkItem } from '../../../../shared/github/work-item-types' import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context' import type { WorkspaceStatus } from '../../../../shared/worktree/types' import type { WorkspaceSource as WorkspaceCreateTelemetrySource } from '../../../../shared/workspace-source' -import type { LinkedWorkItemSummary } from '@/lib/new-workspace' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' import type { ComposerDecisions } from './composer-decisions' -import type { WorkspaceCreationTargetHint } from '@/lib/project-host-workspace-target' +import type { WorkspaceCreationTargetHint } from '@/lib/workspace/creation/project-host-workspace-target' import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' import { selectAllKnownWorkspaceStatuses } from '@/store/workspaces/status/host-workspace-status-columns' @@ -129,7 +127,7 @@ export function useComposerTargetStore(options: ComposerStateInput, decisions: C const workspaceHostScope = useAppStore((s) => s.workspaceHostScope) - const eligibleRepos = useMemo(() => getComposerEligibleRepos(repos), [repos]) + const eligibleRepos = useMemo(() => getNewWorkspaceDialogEligibleRepos(repos), [repos]) const hostOptions = useMemo( () => diff --git a/src/renderer/src/hooks/composer-state/derived-composer-state.ts b/src/renderer/src/hooks/composer-state/derived-composer-state.ts index 1cc8bfba767..fb090a8bb25 100644 --- a/src/renderer/src/hooks/composer-state/derived-composer-state.ts +++ b/src/renderer/src/hooks/composer-state/derived-composer-state.ts @@ -14,7 +14,7 @@ import { getWorkspaceSeedName, DEFAULT_ISSUE_COMMAND_TEMPLATE, renderIssueCommandTemplate -} from '@/lib/new-workspace' +} from '@/lib/workspace/creation/new-workspace' import { getSetupConfig } from '../../../../shared/orca-hook-setup-config' import { deriveWorkspaceSetupState } from '@/lib/workspace/creation/setup/workspace-setup-preparation' import type { SparsePreset } from '../../../../shared/worktree/create-types' diff --git a/src/renderer/src/hooks/composer-state/folder-submit-orchestration.ts b/src/renderer/src/hooks/composer-state/folder-submit-orchestration.ts index 67f16e1d570..6d04c1357c0 100644 --- a/src/renderer/src/hooks/composer-state/folder-submit-orchestration.ts +++ b/src/renderer/src/hooks/composer-state/folder-submit-orchestration.ts @@ -29,14 +29,14 @@ type FolderSubmitOrchestrationInput = Pick< import { useCallback } from 'react' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' -import { settleComposerSubmit } from '@/lib/composer-submit-cancellation' +import { settleComposerSubmit } from '@/lib/workspace/creation/composer-submit-cancellation' import { isTuiAgentEnabled } from '../../../../shared/agent-launch/catalog/tui-agent-selection' import { submitFolderWorkspaceCreate } from '@/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit' import { translate } from '@/i18n/i18n' import { formatWorkspaceCreateError, getWorkspaceCreateErrorToastMessage -} from '@/lib/workspace-create-error-format' +} from '@/lib/workspace/creation/workspace-create-error-format' import { toast } from 'sonner' export function useFolderSubmitOrchestration(input: FolderSubmitOrchestrationInput) { diff --git a/src/renderer/src/hooks/composer-state/github-source-application.ts b/src/renderer/src/hooks/composer-state/github-source-application.ts index 5466ae958a8..0036ab809f0 100644 --- a/src/renderer/src/hooks/composer-state/github-source-application.ts +++ b/src/renderer/src/hooks/composer-state/github-source-application.ts @@ -21,7 +21,11 @@ type GitHubSourceApplicationInput = Pick< import { useCallback } from 'react' import type { GitHubWorkItem } from '../../../../shared/github/work-item-types' import { resolveGitHubWorkItemIdentity } from '../../../../shared/new-workspace/github-work-item-identity' -import { getLinkedWorkItemWorkspaceName, getLinkedWorkItemSuggestedName } from '@/lib/new-workspace' +import '@/lib/workspace/creation/new-workspace' +import { + getLinkedWorkItemWorkspaceName, + getLinkedWorkItemSuggestedName +} from '../../../../shared/workspace-name' import { shouldApplyWorkspaceSourceAutoName } from '../../../../shared/new-workspace/workspace-source' export function useGitHubSourceApplication(input: GitHubSourceApplicationInput) { diff --git a/src/renderer/src/hooks/composer-state/host-runtime-effects.ts b/src/renderer/src/hooks/composer-state/host-runtime-effects.ts index 43c74065ecc..725d9e02ede 100644 --- a/src/renderer/src/hooks/composer-state/host-runtime-effects.ts +++ b/src/renderer/src/hooks/composer-state/host-runtime-effects.ts @@ -37,7 +37,8 @@ import { } from '../../../../shared/agent-launch/catalog/tui-agent-selection' import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' import { useAppStore } from '@/store' -import { isSshConnectInProgress } from '@/lib/new-workspace-ssh-gate' +import '@/lib/workspace/creation/new-workspace-ssh-gate' +import { isConnectingSshStatus } from '@/ssh/ssh-connection-recoverability' import { connectRepoSshConnection, getRepoSshConnection, @@ -160,7 +161,7 @@ export function useHostRuntimeEffects(input: HostRuntimeEffectsInput) { return } const liveStatus = selectRepoSshGateInput(liveState, liveRepo).status - if (liveStatus === 'connected' || isSshConnectInProgress(liveStatus)) { + if (liveStatus === 'connected' || isConnectingSshStatus(liveStatus)) { return } @@ -182,7 +183,7 @@ export function useHostRuntimeEffects(input: HostRuntimeEffectsInput) { const liveStatus = useAppStore .getState() .sshConnectionStates.get(folderTargetConnectionId)?.status - if (liveStatus === 'connected' || isSshConnectInProgress(liveStatus ?? null)) { + if (liveStatus === 'connected' || isConnectingSshStatus(liveStatus ?? null)) { return } try { diff --git a/src/renderer/src/hooks/composer-state/initial-target-model.ts b/src/renderer/src/hooks/composer-state/initial-target-model.ts index 880e583608d..03cf354d843 100644 --- a/src/renderer/src/hooks/composer-state/initial-target-model.ts +++ b/src/renderer/src/hooks/composer-state/initial-target-model.ts @@ -3,7 +3,7 @@ import type { RefObject } from 'react' import type { ExecutionHostId } from '../../../../shared/execution-host' import type { ProjectGroup } from '../../../../shared/project-group-types' import type { WorkspaceStatus } from '../../../../shared/worktree/types' -import type { WorkspaceCreationTargetResolution } from '@/lib/project-host-workspace-target' +import type { WorkspaceCreationTargetResolution } from '@/lib/workspace/creation/project-host-workspace-target' export type ComposerInitialTargetModel = { draftRepoId: string | null diff --git a/src/renderer/src/hooks/composer-state/initial-target-state.ts b/src/renderer/src/hooks/composer-state/initial-target-state.ts index 38eeb80d51e..889ddd33f53 100644 --- a/src/renderer/src/hooks/composer-state/initial-target-state.ts +++ b/src/renderer/src/hooks/composer-state/initial-target-state.ts @@ -24,8 +24,8 @@ type ComposerInitialTargetStateInput = Pick< import { useEffect, useMemo, useRef, useState } from 'react' import { isWorkspaceStatusId } from '../../../../shared/workspace-statuses' -import { resolveWorkspaceCreationTarget } from '@/lib/project-host-workspace-target' -import { findActionableFolderProjectGroup } from '@/lib/new-workspace-project-options' +import { resolveWorkspaceCreationTarget } from '@/lib/workspace/creation/project-host-workspace-target' +import { findActionableFolderProjectGroup } from '@/lib/workspace/creation/new-workspace-project-options' import type { ProjectGroup } from '../../../../shared/project-group-types' export function useComposerInitialTargetState(input: ComposerInitialTargetStateInput) { diff --git a/src/renderer/src/hooks/composer-state/issue-source-actions.ts b/src/renderer/src/hooks/composer-state/issue-source-actions.ts index 184b457bcfd..073656a6438 100644 --- a/src/renderer/src/hooks/composer-state/issue-source-actions.ts +++ b/src/renderer/src/hooks/composer-state/issue-source-actions.ts @@ -51,11 +51,12 @@ import { } from '@/lib/work-items/linear/linear-linked-work-item' import { getLinearIssueWorkspaceName } from '../../../../shared/workspace-name' import { getJiraIssueKeyCasingSeedOptions } from '@/lib/work-items/jira/jira-issue-key-casing' +import '@/lib/workspace/creation/new-workspace' import { getLinkedWorkItemSuggestedName, - getLinkedWorkItemWorkspaceName, - type LinkedWorkItemSummary -} from '@/lib/new-workspace' + getLinkedWorkItemWorkspaceName +} from '../../../../shared/workspace-name' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' import type { SmartWorkspaceNameSelection } from '@/components/new-workspace/smart-workspace-name-field-model' import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context' diff --git a/src/renderer/src/hooks/composer-state/linked-item-lookup-effects.ts b/src/renderer/src/hooks/composer-state/linked-item-lookup-effects.ts index 09193a23314..c398def2c2c 100644 --- a/src/renderer/src/hooks/composer-state/linked-item-lookup-effects.ts +++ b/src/renderer/src/hooks/composer-state/linked-item-lookup-effects.ts @@ -26,7 +26,7 @@ type LinkedItemLookupEffectsInput = Pick< | 'sshConnectedGeneration' > -import { canUseRepoBackedComposerSources } from '@/lib/new-workspace-ssh-gate' +import { canUseRepoBackedComposerSources } from '@/lib/workspace/creation/new-workspace-ssh-gate' import { useEffect } from 'react' import { PER_REPO_FETCH_LIMIT } from '../../../../shared/work-items/work-item-pagination' import { getDefaultSetupDecision } from '../../../../shared/orca-hook-setup-config' diff --git a/src/renderer/src/hooks/composer-state/project-target-actions.ts b/src/renderer/src/hooks/composer-state/project-target-actions.ts index c76f9e9aa41..4e47479087c 100644 --- a/src/renderer/src/hooks/composer-state/project-target-actions.ts +++ b/src/renderer/src/hooks/composer-state/project-target-actions.ts @@ -49,10 +49,10 @@ import { getProjectGroupIdFromNewWorkspaceOptionId, getProjectRowHostSetups, findActionableFolderProjectGroup -} from '@/lib/new-workspace-project-options' +} from '@/lib/workspace/creation/new-workspace-project-options' import { translate } from '@/i18n/i18n' import { getFolderSourceRepos } from '@/components/sidebar/workspace-creation/folder/folder-workspace-source-repos' -import { resolveWorkspaceCreationRepoId } from '@/lib/project-host-workspace-target' +import { resolveWorkspaceCreationRepoId } from '@/lib/workspace/creation/project-host-workspace-target' export function useProjectTargetActions(input: ProjectTargetActionsInput) { const { diff --git a/src/renderer/src/hooks/composer-state/quick-creation-execution.ts b/src/renderer/src/hooks/composer-state/quick-creation-execution.ts index e1bf359ae58..b752a058156 100644 --- a/src/renderer/src/hooks/composer-state/quick-creation-execution.ts +++ b/src/renderer/src/hooks/composer-state/quick-creation-execution.ts @@ -6,9 +6,9 @@ import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent import type { WorktreeCreationRequest } from '@/lib/workspace/creation/pending-worktree-creation' import { useAppStore } from '@/store' import { isWorkspaceStatusAllowedOnHost } from '@/store/workspaces/status/host-workspace-status-columns' -import { settleComposerSubmit } from '@/lib/composer-submit-cancellation' +import { settleComposerSubmit } from '@/lib/workspace/creation/composer-submit-cancellation' import { runBackgroundWorktreeCreation } from '@/lib/workspace/creation/worktree-creation-flow' -import type { ComposerCreateHandoff } from '@/lib/composer-create-handoff' +import type { ComposerCreateHandoff } from '@/lib/workspace/creation/composer-create-handoff' import { translate } from '@/i18n/i18n' import { prepareQuickComposerStartup } from './quick-startup-plan' import { buildQuickCreationRequest, type QuickSubmitOptions } from './quick-creation-request' diff --git a/src/renderer/src/hooks/composer-state/quick-creation-request.ts b/src/renderer/src/hooks/composer-state/quick-creation-request.ts index dbd6c3abfef..6d765c8d668 100644 --- a/src/renderer/src/hooks/composer-state/quick-creation-request.ts +++ b/src/renderer/src/hooks/composer-state/quick-creation-request.ts @@ -1,7 +1,7 @@ import type { AgentStartedTelemetry } from '@/lib/workspace/creation/worktree-startup-payload' import type { WorktreeCreationRequest } from '@/lib/workspace/creation/pending-worktree-creation' import type { AgentStartupPlan } from '../../../../shared/agent-launch/startup/tui-agent-startup' -import type { LinkedWorkItemSummary } from '@/lib/new-workspace' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' import type { AgentLaunchChoice } from '@/lib/agent-session/launch/routing/agent-menu-selection' diff --git a/src/renderer/src/hooks/composer-state/quick-submit-action.ts b/src/renderer/src/hooks/composer-state/quick-submit-action.ts index caa4eb26537..de1f8b57fec 100644 --- a/src/renderer/src/hooks/composer-state/quick-submit-action.ts +++ b/src/renderer/src/hooks/composer-state/quick-submit-action.ts @@ -4,14 +4,14 @@ import type { WorktreeCreationRequest } from '@/lib/workspace/creation/pending-w import type { QuickSubmitOptions } from './quick-creation-request' import { findPendingLinkedWorkItemCreationId } from '@/lib/workspace/creation/pending-worktree-creation' import { useAppStore } from '@/store' -import { getWorkspaceSeedName } from '@/lib/new-workspace' -import { settleComposerSubmit } from '@/lib/composer-submit-cancellation' +import { getWorkspaceSeedName } from '@/lib/workspace/creation/new-workspace' +import { settleComposerSubmit } from '@/lib/workspace/creation/composer-submit-cancellation' import { formatWorkspaceCreateError, getWorkspaceCreateErrorToastMessage -} from '@/lib/workspace-create-error-format' +} from '@/lib/workspace/creation/workspace-create-error-format' import { toast } from 'sonner' -import { scheduleComposerCreateHandoff } from '@/lib/composer-create-handoff' +import { scheduleComposerCreateHandoff } from '@/lib/workspace/creation/composer-create-handoff' import type { ComposerModel } from './composer-model' diff --git a/src/renderer/src/hooks/composer-state/quick-submit-preparation.ts b/src/renderer/src/hooks/composer-state/quick-submit-preparation.ts index 36d9bebbade..c9aaaf2b635 100644 --- a/src/renderer/src/hooks/composer-state/quick-submit-preparation.ts +++ b/src/renderer/src/hooks/composer-state/quick-submit-preparation.ts @@ -1,9 +1,9 @@ import type { QuickSubmitPreparationInput } from './quick-submit-input-contract' import { useCallback } from 'react' -import { settleComposerSubmit } from '@/lib/composer-submit-cancellation' +import { settleComposerSubmit } from '@/lib/workspace/creation/composer-submit-cancellation' import { getWorkspaceSourceProvider } from '../../../../shared/new-workspace/workspace-source' -import { canUseIssueCommandForLinkedItemProvider } from '@/lib/new-workspace' +import { canUseIssueCommandForLinkedItemProvider } from '@/lib/workspace/creation/new-workspace' import { getSetupConfig } from '../../../../shared/orca-hook-setup-config' import { deriveWorkspaceSetupState, diff --git a/src/renderer/src/hooks/composer-state/quick-submit-source-preparation.ts b/src/renderer/src/hooks/composer-state/quick-submit-source-preparation.ts index eba8701beb6..549e7eb2f9b 100644 --- a/src/renderer/src/hooks/composer-state/quick-submit-source-preparation.ts +++ b/src/renderer/src/hooks/composer-state/quick-submit-source-preparation.ts @@ -19,7 +19,8 @@ type QuickSubmitSourcePreparationInput = Pick< import { useCallback } from 'react' import { isTuiAgentEnabled } from '../../../../shared/agent-launch/catalog/tui-agent-selection' -import { getLinkedWorkItemWorkspaceName } from '@/lib/new-workspace' +import '@/lib/workspace/creation/new-workspace' +import { getLinkedWorkItemWorkspaceName } from '../../../../shared/workspace-name' import { getJiraIssueKeyCasingSeedOptions } from '@/lib/work-items/jira/jira-issue-key-casing' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' import type { PendingSmartGitHubSubmitResolution } from './source-selection-decisions' diff --git a/src/renderer/src/hooks/composer-state/runtime-target-model.ts b/src/renderer/src/hooks/composer-state/runtime-target-model.ts index e6a7f51b8b3..28c02dbed08 100644 --- a/src/renderer/src/hooks/composer-state/runtime-target-model.ts +++ b/src/renderer/src/hooks/composer-state/runtime-target-model.ts @@ -7,9 +7,9 @@ import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent import type { OrcaVmRecipe } from '../../../../shared/orca-yaml-hook-types' import type { AgentStartupShell } from '../../../../shared/agent-launch/startup/tui-agent-startup-shell' import type { ExecutionHostPlatformFact } from '@/runtime/hosts/platform/execution-host-platform-fact' -import type { NewWorkspaceProjectOption } from '@/lib/new-workspace-project-options' -import type { ProjectHostSetupOption } from '@/lib/project-host-setup-options' -import type { WorkspaceCreationTargetResolution } from '@/lib/project-host-workspace-target' +import type { NewWorkspaceProjectOption } from '@/lib/workspace/creation/new-workspace-project-options' +import type { ProjectHostSetupOption } from '@/lib/workspace/creation/project-host-setup-options' +import type { WorkspaceCreationTargetResolution } from '@/lib/workspace/creation/project-host-workspace-target' export type ComposerRuntimeTargetModel = { isProjectGroupTarget: boolean diff --git a/src/renderer/src/hooks/composer-state/runtime-target-selection.ts b/src/renderer/src/hooks/composer-state/runtime-target-selection.ts index c2fa25817ac..b7416acee21 100644 --- a/src/renderer/src/hooks/composer-state/runtime-target-selection.ts +++ b/src/renderer/src/hooks/composer-state/runtime-target-selection.ts @@ -4,14 +4,14 @@ import type { ComposerRuntimeTargetSelectionInput } from './composer-target-inpu import { useEffect, useMemo, useRef } from 'react' import { getFolderSourceRepos } from '@/components/sidebar/workspace-creation/folder/folder-workspace-source-repos' import { parseExecutionHostId, getRepoExecutionHostId } from '../../../../shared/execution-host' -import { getSelectedRepoSshGate } from '@/lib/new-workspace-ssh-gate' +import { getSelectedRepoSshGate } from '@/lib/workspace/creation/new-workspace-ssh-gate' import { selectRepoSshGateInput } from '@/lib/repo-ssh-connection' import { useFolderWorkspaceComposerPathStatus } from '@/components/sidebar/workspace-creation/folder/folder-workspace-composer-path-status' import { useDetectedAgents } from '@/hooks/useDetectedAgents' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' -import { resolveWorkspaceCreationTarget } from '@/lib/project-host-workspace-target' +import { resolveWorkspaceCreationTarget } from '@/lib/workspace/creation/project-host-workspace-target' import { isGitRepoKind } from '../../../../shared/repo-kind' -import { CLIENT_PLATFORM } from '@/lib/new-workspace' +import { CLIENT_PLATFORM } from '@/lib/workspace/creation/new-workspace' import { getLocalRepoProjectExecutionRuntimeContext } from '@/lib/local-preflight-context' import { resolveExecutionHostAgentStartupShell, @@ -20,8 +20,8 @@ import { import type { ExecutionHostPlatformFact } from '@/runtime/hosts/platform/execution-host-platform-fact' import { useAppStore } from '@/store' import { repoIsRemote } from '../../../../shared/agent-launch/startup/agent-launch-remote' -import { buildProjectHostSetupOptions } from '@/lib/project-host-setup-options' -import { buildNewWorkspaceCreateTargetOptions } from '@/lib/new-workspace-project-options' +import { buildProjectHostSetupOptions } from '@/lib/workspace/creation/project-host-setup-options' +import { buildNewWorkspaceCreateTargetOptions } from '@/lib/workspace/creation/new-workspace-project-options' import { getRuntimeEnvironmentIdForRepo } from '@/lib/workspace/ownership/repo-runtime-owner' import { useEphemeralVmRecipeOptions } from '@/hooks/useEphemeralVmRecipeOptions' diff --git a/src/renderer/src/hooks/composer-state/source-context-model.ts b/src/renderer/src/hooks/composer-state/source-context-model.ts index 97a7b9219c0..04aea6f26cb 100644 --- a/src/renderer/src/hooks/composer-state/source-context-model.ts +++ b/src/renderer/src/hooks/composer-state/source-context-model.ts @@ -1,7 +1,7 @@ import type * as React from 'react' import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context' import type { GitHubWorkItemIdentity } from '../../../../shared/new-workspace/github-work-item-identity' -import type { LinkedWorkItemSummary } from '@/lib/new-workspace' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' export type ComposerSourceContextModel = { setRepoId: (value: string) => void diff --git a/src/renderer/src/hooks/composer-state/source-context-state.ts b/src/renderer/src/hooks/composer-state/source-context-state.ts index 2bb03cfe719..17e34a84374 100644 --- a/src/renderer/src/hooks/composer-state/source-context-state.ts +++ b/src/renderer/src/hooks/composer-state/source-context-state.ts @@ -27,7 +27,7 @@ type ComposerSourceContextStateInput = Pick< import { useCallback, useMemo, useState } from 'react' import { getWorkspaceSourceProvider } from '../../../../shared/new-workspace/workspace-source' -import type { LinkedWorkItemSummary } from '@/lib/new-workspace' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' import { getLinearLinkedWorkItemBranchName } from '@/lib/work-items/linear/linear-linked-work-item' import { type TaskSourceContext, diff --git a/src/renderer/src/hooks/composer-state/source-identity-actions.ts b/src/renderer/src/hooks/composer-state/source-identity-actions.ts index 5fe6f36db0c..ecfc2b44209 100644 --- a/src/renderer/src/hooks/composer-state/source-identity-actions.ts +++ b/src/renderer/src/hooks/composer-state/source-identity-actions.ts @@ -35,7 +35,11 @@ type SourceIdentityActionsInput = Pick< import { useCallback } from 'react' import type { GitLabWorkItem } from '../../../../shared/gitlab-types' -import { getLinkedWorkItemSuggestedName, getLinkedWorkItemWorkspaceName } from '@/lib/new-workspace' +import '@/lib/workspace/creation/new-workspace' +import { + getLinkedWorkItemSuggestedName, + getLinkedWorkItemWorkspaceName +} from '../../../../shared/workspace-name' import type { GitHubWorkItem } from '../../../../shared/github/work-item-types' import { shouldApplyWorkspaceSourceAutoName } from '../../../../shared/new-workspace/workspace-source' import { isLinearLinkedWorkItem } from '@/lib/work-items/linear/linear-linked-work-item' diff --git a/src/renderer/src/hooks/composer-state/source-selection-decisions.ts b/src/renderer/src/hooks/composer-state/source-selection-decisions.ts index fbec826ed11..ee5e4bf8f0e 100644 --- a/src/renderer/src/hooks/composer-state/source-selection-decisions.ts +++ b/src/renderer/src/hooks/composer-state/source-selection-decisions.ts @@ -2,7 +2,7 @@ import type { GitHubPrStartPoint, GitPushTarget } from '../../../../shared/workt import type { GitHubWorkItem } from '../../../../shared/github/work-item-types' import type { GitLabWorkItem } from '../../../../shared/gitlab-types' import { getWorkspaceSourceProvider } from '../../../../shared/new-workspace/workspace-source' -import type { LinkedWorkItemSummary } from '@/lib/new-workspace' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' import type { SmartGitHubSubmitResolution } from '@/lib/work-items/github/smart-github-submit' import { resolveGitHubWorkItemIdentity, diff --git a/src/renderer/src/hooks/composer-state/target-change-actions.ts b/src/renderer/src/hooks/composer-state/target-change-actions.ts index c0ff8fcb83c..65db2bf7c45 100644 --- a/src/renderer/src/hooks/composer-state/target-change-actions.ts +++ b/src/renderer/src/hooks/composer-state/target-change-actions.ts @@ -47,9 +47,10 @@ import { getProjectHostSetupSelectionKey, type ProjectHostSetupOption, type ReadyProjectHostSetupOption -} from '@/lib/project-host-setup-options' +} from '@/lib/workspace/creation/project-host-setup-options' import { useAppStore } from '@/store' -import { getComposerEligibleRepos } from '@/lib/new-workspace-composer-repo' +import '@/lib/workspace/creation/new-workspace-composer-repo' +import { getNewWorkspaceDialogEligibleRepos } from '../../../../shared/new-workspace-dialog-repo' export function useTargetChangeActions(input: TargetChangeActionsInput) { const { @@ -246,7 +247,7 @@ export function useTargetChangeActions(input: TargetChangeActionsInput) { : buildProjectHostSetupOptions({ projectId: selectedRepoProjectId, projectHostSetups: useAppStore.getState().projectHostSetups, - eligibleRepos: getComposerEligibleRepos(useAppStore.getState().repos), + eligibleRepos: getNewWorkspaceDialogEligibleRepos(useAppStore.getState().repos), hosts: hostOptions }).find( (candidate): candidate is ReadyProjectHostSetupOption => diff --git a/src/renderer/src/hooks/composer-state/target-store-model.ts b/src/renderer/src/hooks/composer-state/target-store-model.ts index 0fe30658078..233b75fab9d 100644 --- a/src/renderer/src/hooks/composer-state/target-store-model.ts +++ b/src/renderer/src/hooks/composer-state/target-store-model.ts @@ -11,7 +11,7 @@ import type { Worktree } from '../../../../shared/worktree/types' import type { ExecutionHostRegistryEntry } from '../../../../shared/execution-host/execution-host-registry-entry' -import type { LinkedWorkItemSummary } from '@/lib/new-workspace' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' import type { ComposerDecisions } from './composer-decisions' import type { ComposerStoreActions } from './composer-store-actions' import type { SparsePreset } from '../../../../shared/worktree/create-types' @@ -21,7 +21,7 @@ import type { RuntimeEnvironmentStatus } from '../../../../shared/remote-runtime import type { GlobalSettings } from '../../../../shared/global-settings-types' import type { WorkspaceHostScope } from '../../../../shared/ui-chrome-types' import type { WorkspaceSource as WorkspaceCreateTelemetrySource } from '../../../../shared/workspace-source' -import type { WorkspaceCreationTargetHint } from '@/lib/project-host-workspace-target' +import type { WorkspaceCreationTargetHint } from '@/lib/workspace/creation/project-host-workspace-target' export type ComposerTargetStoreModel = { initialRepoId: string | undefined diff --git a/src/renderer/src/hooks/ipc-events/new-workspace-command.ts b/src/renderer/src/hooks/ipc-events/new-workspace-command.ts index 0059b95bf18..a8d7f03b60b 100644 --- a/src/renderer/src/hooks/ipc-events/new-workspace-command.ts +++ b/src/renderer/src/hooks/ipc-events/new-workspace-command.ts @@ -1,5 +1,5 @@ import { buildLinearIssueLinkedWorkItem } from '@/lib/work-items/linear/linear-linked-work-item' -import type { LinkedWorkItemSummary } from '@/lib/new-workspace' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' import { getLinearIssueWorkspaceName } from '../../../../shared/workspace-name' import type { AppState } from '../../store/types' diff --git a/src/renderer/src/hooks/useComposerState.ts b/src/renderer/src/hooks/useComposerState.ts index d806d47ab01..2ac5e320549 100644 --- a/src/renderer/src/hooks/useComposerState.ts +++ b/src/renderer/src/hooks/useComposerState.ts @@ -1,13 +1,13 @@ import type { RefObject } from 'react' -import '@/lib/new-workspace' -import type { LinkedWorkItemSummary } from '@/lib/new-workspace' +import '@/lib/workspace/creation/new-workspace' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' import type { GitHubWorkItem } from '../../../shared/github/work-item-types' import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' import type { QuickSubmitOptions } from './composer-state/quick-creation-request' import type { TaskSourceContext } from '../../../shared/work-items/task-source-context' import type { WorkspaceSource as WorkspaceCreateTelemetrySource } from '../../../shared/workspace-source' import type { WorkspaceStatus } from '../../../shared/worktree/types' -import type { WorkspaceCreationTargetHint } from '@/lib/project-host-workspace-target' +import type { WorkspaceCreationTargetHint } from '@/lib/workspace/creation/project-host-workspace-target' import { buildComposerCardProps } from './composer-state/composer-card-props' import { canResolveFolderSmartGitHubSubmit, diff --git a/src/renderer/src/hooks/useEphemeralVmRecipeOptions.ts b/src/renderer/src/hooks/useEphemeralVmRecipeOptions.ts index 97750798d9e..19626d6edd7 100644 --- a/src/renderer/src/hooks/useEphemeralVmRecipeOptions.ts +++ b/src/renderer/src/hooks/useEphemeralVmRecipeOptions.ts @@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host' import type { OrcaVmRecipe } from '../../../shared/orca-yaml-hook-types' import type { EphemeralVmFailure } from '../../../shared/ephemeral-vm-failure-copy' -import { ephemeralVmErrorText } from '@/lib/ephemeral-vm-error-copy' +import { ephemeralVmErrorText } from '@/runtime/ephemeral-vm/ephemeral-vm-error-copy' import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' type EphemeralVmRecipeOptionsArgs = { diff --git a/src/renderer/src/lib/agent-session/launch/continuation/launch-agent-session-continuation-toast.test.tsx b/src/renderer/src/lib/agent-session/launch/continuation/launch-agent-session-continuation-toast.test.tsx index 474baef3eaf..42c27fb6e70 100644 --- a/src/renderer/src/lib/agent-session/launch/continuation/launch-agent-session-continuation-toast.test.tsx +++ b/src/renderer/src/lib/agent-session/launch/continuation/launch-agent-session-continuation-toast.test.tsx @@ -24,7 +24,7 @@ vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') ).runtimeRpcClientWithLayoutApply(await importOriginal()) ) -vi.mock('../../../host-chat-program-acquisition', () => ({ +vi.mock('../inventory/host-chat-program-acquisition', () => ({ acquireAgentLaunchChoices: async () => ({ detected: ['codex'], offered: ['codex'] }) })) diff --git a/src/renderer/src/lib/agent-session/launch/continuation/launch-agent-session-continuation.ts b/src/renderer/src/lib/agent-session/launch/continuation/launch-agent-session-continuation.ts index 86cfa89a60c..c75fa94a685 100644 --- a/src/renderer/src/lib/agent-session/launch/continuation/launch-agent-session-continuation.ts +++ b/src/renderer/src/lib/agent-session/launch/continuation/launch-agent-session-continuation.ts @@ -7,8 +7,8 @@ import { useAppStore } from '@/store/index' import { acquireAgentLaunchChoices, AgentLaunchChoiceCancelled -} from '../../../host-chat-program-acquisition' -import { agentChoicePending } from '../../../host-chat-program' +} from '../inventory/host-chat-program-acquisition' +import { agentChoicePending } from '../inventory/host-chat-program' import { worktreeLaunchWorkspace } from '../routing/agent-launch-route-input' import { isTuiAgentEnabled } from '../../../../../../shared/agent-launch/catalog/tui-agent-selection' import type { LaunchSource } from '../../../../../../shared/telemetry-property-schemas' diff --git a/src/renderer/src/lib/environment-setup-agent-launch.ts b/src/renderer/src/lib/agent-session/launch/environment-setup-agent-launch.ts similarity index 92% rename from src/renderer/src/lib/environment-setup-agent-launch.ts rename to src/renderer/src/lib/agent-session/launch/environment-setup-agent-launch.ts index 1cf1d1acba4..395533bc5bd 100644 --- a/src/renderer/src/lib/environment-setup-agent-launch.ts +++ b/src/renderer/src/lib/agent-session/launch/environment-setup-agent-launch.ts @@ -1,5 +1,5 @@ import { toast } from 'sonner' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { translate } from '@/i18n/i18n' import { resolveDefaultAgentForWorktree } from '@/lib/agent-session/launch/shortcuts/agent-tab-shortcuts' import { launchAgentInNewTabWithOutcome } from '@/lib/agent-session/launch/new-tab/launch-agent-in-new-tab' @@ -8,13 +8,13 @@ import { captureAgentTabLaunchContext } from '@/components/agent-tab-launch-cont import { activateAndRevealWorktreeWithOutcome } from '@/lib/workspace/activation/worktree-activation' import { reportAgentWorkspaceActivation } from '@/lib/workspace/activation/worktree-activation-outcome' import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface' -import { isGitRepoKind } from '../../../shared/repo-kind' -import type { Repo } from '../../../shared/repo-types' -import type { Worktree } from '../../../shared/worktree/types' +import { isGitRepoKind } from '../../../../../shared/repo-kind' +import type { Repo } from '../../../../../shared/repo-types' +import type { Worktree } from '../../../../../shared/worktree/types' import { buildEnvironmentSetupAgentPrompt, type EnvironmentSetupFailureContext -} from '../../../shared/environment-setup-agent-prompt' +} from '../../../../../shared/environment-setup-agent-prompt' /** The Git project an environment-setup agent should work on: the active one, else the first. */ export function pickEnvironmentSetupRepo( diff --git a/src/renderer/src/lib/host-chat-program-acquisition.ts b/src/renderer/src/lib/agent-session/launch/inventory/host-chat-program-acquisition.ts similarity index 93% rename from src/renderer/src/lib/host-chat-program-acquisition.ts rename to src/renderer/src/lib/agent-session/launch/inventory/host-chat-program-acquisition.ts index abe59f741be..ee4fdcf05d1 100644 --- a/src/renderer/src/lib/host-chat-program-acquisition.ts +++ b/src/renderer/src/lib/agent-session/launch/inventory/host-chat-program-acquisition.ts @@ -4,8 +4,8 @@ import { useAppStateValue } from '@/store/retained-views/app-state-view' import { useEffect, useMemo } from 'react' -import { useAppStore } from '@/store' -import type { ProspectiveWorkspace } from './agent-session/launch/routing/agent-launch-route-input' +import { useAppStore } from '@/store/index' +import type { ProspectiveWorkspace } from '../routing/agent-launch-route-input' import { agentsOfferedForLaunch, resolveChatProgramContext, @@ -19,14 +19,14 @@ import { firstHostStructuredAgentAvailability } from '@/runtime/native-chat/agent-catalogs/host-structured-agent-availability' import { onRuntimeEnvironmentsRetired } from '@/runtime/rpc/environment-revisions/runtime-environment-revision' -import { STRUCTURED_AGENT_SESSION_AVAILABILITY_RUNTIME_CAPABILITY as AVAILABILITY } from '../../../shared/agent-session/structured-agent-session-surface-capabilities' -import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' +import { STRUCTURED_AGENT_SESSION_AVAILABILITY_RUNTIME_CAPABILITY as AVAILABILITY } from '../../../../../../shared/agent-session/structured-agent-session-surface-capabilities' +import type { TuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent' import type { AppState } from '@/store/types' -import { isTuiAgent } from '../../../shared/agent-launch/catalog/tui-agent-config' +import { isTuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent-config' import { getDetectionTargetIdentityForWorktree, readAgentInventoryForWorktree -} from './agent-session/launch/inventory/agent-detection-target-inventory' +} from './agent-detection-target-inventory' export const useChatProgramFactsVersion = (): number => useAppViewExternalStore( diff --git a/src/renderer/src/lib/host-chat-program.ts b/src/renderer/src/lib/agent-session/launch/inventory/host-chat-program.ts similarity index 89% rename from src/renderer/src/lib/host-chat-program.ts rename to src/renderer/src/lib/agent-session/launch/inventory/host-chat-program.ts index 52c2440b6b1..beda9993fe5 100644 --- a/src/renderer/src/lib/host-chat-program.ts +++ b/src/renderer/src/lib/agent-session/launch/inventory/host-chat-program.ts @@ -1,24 +1,24 @@ -import { nativeChatPreferenceFor } from '../../../shared/structured-native-chat-launch-route' -import { parseExecutionHostId } from '../../../shared/execution-host' -import { MANAGED_RUNTIME_INSTALL_RUNTIME_CAPABILITY as INSTALL } from '../../../shared/managed-runtime-install' +import { nativeChatPreferenceFor } from '../../../../../../shared/structured-native-chat-launch-route' +import { parseExecutionHostId } from '../../../../../../shared/execution-host' +import { MANAGED_RUNTIME_INSTALL_RUNTIME_CAPABILITY as INSTALL } from '../../../../../../shared/managed-runtime-install' import { STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY as CATALOG, STRUCTURED_AGENT_SESSION_AVAILABILITY_RUNTIME_CAPABILITY as AVAILABILITY -} from '../../../shared/agent-session/structured-agent-session-surface-capabilities' -import { lastVerifiedRuntimeStatus } from '../../../shared/remote-runtime/host-status/runtime-host-status' -import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' -import type { AgentSessionChatProgram } from '../../../shared/agent-session/agent-session-agent-availability' -import { chatProviderAgents } from '../runtime/native-chat/agent-catalogs/chat-provider-agents' +} from '../../../../../../shared/agent-session/structured-agent-session-surface-capabilities' +import { lastVerifiedRuntimeStatus } from '../../../../../../shared/remote-runtime/host-status/runtime-host-status' +import type { TuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent' +import type { AgentSessionChatProgram } from '../../../../../../shared/agent-session/agent-session-agent-availability' +import { chatProviderAgents } from '../../../../runtime/native-chat/agent-catalogs/chat-provider-agents' import { resolveAgentLaunchRoute, structuredAgentLaunchSupport -} from './agent-session/launch/routing/agent-launch-routing' +} from '../routing/agent-launch-routing' import { buildAgentLaunchRouteInput, resolveAgentLaunchHost, type AgentLaunchRouteStore, type ProspectiveWorkspace -} from './agent-session/launch/routing/agent-launch-route-input' +} from '../routing/agent-launch-route-input' import { readHostStructuredAgentAvailability, subscribeHostStructuredAgentAvailability @@ -35,7 +35,7 @@ import { onRuntimeEnvironmentsRetired } from '@/runtime/rpc/environment-revisions/runtime-environment-revision' import { structuredAgentSessionTargetForHost } from '@/runtime/native-chat/session-ownership/structured-agent-session-owner' -import { getResolvedExecutionHostIdForWorktree } from './resolved-worktree-execution-host' +import { getResolvedExecutionHostIdForWorktree } from '../../../resolved-worktree-execution-host' export type ChatProgramObservation = AgentSessionChatProgram | 'unlearned' type HostFactsStore = Pick diff --git a/src/renderer/src/lib/agent-session/launch/native-chat-provider-choice.test.tsx b/src/renderer/src/lib/agent-session/launch/native-chat-provider-choice.test.tsx deleted file mode 100644 index 353a8a3d079..00000000000 --- a/src/renderer/src/lib/agent-session/launch/native-chat-provider-choice.test.tsx +++ /dev/null @@ -1,189 +0,0 @@ -// @vitest-environment happy-dom -import userEvent from '@testing-library/user-event' -import { cleanup, fireEvent, render, screen, within } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { projectAgentLaunchSettings } from '../../../../../shared/agent-launch/choices/agent-launch-settings' -import { createGlobalSettingsFixture } from '../../../../../shared/global-settings-test-fixture' -import type { GlobalSettings } from '../../../../../shared/global-settings-types' -import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent' -import type { ManagedRuntimeInstallObservation } from '@/runtime/hosts/installation/use-managed-runtime-install' -import type * as HostChatProgramModule from '@/lib/host-chat-program' -import type * as ManagedRuntimeInstallModule from '@/runtime/hosts/installation/managed-runtime-install-status' -import type * as SignInAreaModule from '../../../components/provider-accounts/AntigravityProviderSignInArea' -import { TooltipProvider } from '../../../components/ui/tooltip' -import { AgentLaunchSettingsCatalog } from '../../../components/settings/agents/launch/AgentLaunchSettingsCatalog' - -const store = vi.hoisted( - (): { settings: unknown; localDetectedAgentIdsByContext: { host: TuiAgent[] | null } } => ({ - settings: null, - localDetectedAgentIdsByContext: { host: ['claude'] } - }) -) -const inventory = vi.hoisted( - (): { - detected: TuiAgent[] | null - failed: boolean - chatAvailable: boolean - nativePrograms: TuiAgent[] - } => ({ - detected: ['claude'], - failed: false, - chatAvailable: true, - nativePrograms: [] - }) -) -const runtime = vi.hoisted((): { current: ManagedRuntimeInstallObservation } => ({ - current: { kind: 'pending' } -})) -vi.mock('../../../store/index', () => ({ - useAppStore: Object.assign((selector: (value: unknown) => unknown) => selector(store), { - getState: () => store - }) -})) -vi.mock('@/runtime/native-chat/agent-catalogs/chat-provider-agents', () => ({ - chatProviderAgents: () => ['claude', 'codex', 'antigravity'], - useHostStructuredAgentsVersion: () => 0 -})) -vi.mock('@/hooks/useDetectedAgents', () => ({ - useDetectedAgents: () => ({ - detectedIds: inventory.detected, - detectionFailed: inventory.failed, - isRefreshing: false, - refresh: vi.fn() - }) -})) -vi.mock('@/lib/host-chat-program-acquisition', () => ({ useChatProgramFacts: () => {} })) -vi.mock('@/lib/host-chat-program', async (importOriginal) => ({ - ...(await importOriginal()), - agentChoiceOpensAsChat: () => false, - resolveChatProgramContext: (_state: unknown, workspace: { runtimeEnvironmentId?: string }) => ({ - executionHostId: workspace.runtimeEnvironmentId - ? `runtime:${workspace.runtimeEnvironmentId}` - : 'local', - hostCapabilities: [], - runtimeId: null - }), - // The host publishes Antigravity's downloaded chat program; its agy CLI is not installed. - readChatProgram: (_store: unknown, agent: TuiAgent) => - (agent === 'antigravity' && inventory.chatAvailable) || inventory.nativePrograms.includes(agent) - ? 'available' - : 'missing' -})) -vi.mock('@/runtime/native-chat/agent-catalogs/host-structured-agents', () => ({ - readHostStructuredAgents: () => [{ agent: 'antigravity', managedRuntime: true }] -})) -vi.mock('@/runtime/hosts/installation/managed-runtime-install-status', async (importOriginal) => ({ - ...(await importOriginal()), - installManagedRuntime: vi.fn(async () => {}) -})) -vi.mock('@/runtime/hosts/installation/use-managed-runtime-install', () => ({ - useManagedRuntimeInstall: () => runtime.current -})) -vi.mock('../../../components/provider-accounts/use-antigravity-chat-sign-in', () => ({ - useAntigravityChatSignIn: () => ({ flow: null }) -})) -vi.mock( - '../../../components/provider-accounts/AntigravityProviderSignInArea', - async (importOriginal) => ({ - ...(await importOriginal()), - AntigravityProviderSignInArea: () =>

Antigravity account

- }) -) -beforeEach(() => { - inventory.detected = ['claude'] - inventory.failed = false - inventory.chatAvailable = true - inventory.nativePrograms = [] - store.localDetectedAgentIdsByContext.host = ['claude'] - runtime.current = { kind: 'pending' } - vi.stubGlobal('api', { platform: { get: () => ({ platform: 'darwin' }) } }) -}) -afterEach(() => { - cleanup() - vi.unstubAllGlobals() -}) - -describe('agent row chat or CLI', () => { - it('serializes choices from different rows while an inventory update arrives during the save', async () => { - const settings = createGlobalSettingsFixture({ agentDefaultSurface: 'chat' }) - store.settings = settings - const save = Promise.withResolvers() - const updateSettings = vi.fn(async (updates: Partial) => { - await save.promise - Object.assign(settings, updates) - }) - const element = () => ( - {})} - detectionTarget={{ kind: 'local' }} - hostName={null} - renderPermissions={() => null} - local={{ settings, updateSettings, saveEnvironment: vi.fn(async () => {}) }} - /> - ) - const view = render(element(), { wrapper: TooltipProvider }) - const cli = (label: string) => - within(screen.getByRole('radiogroup', { name: `Open ${label} as` })).getByRole('radio', { - name: 'CLI' - }) - fireEvent.click(cli('Claude')) - await vi.waitFor(() => expect(updateSettings).toHaveBeenCalledOnce()) - fireEvent.click(cli('Codex')) - inventory.detected = [] - view.rerender(element()) - expect(updateSettings).toHaveBeenCalledOnce() - save.resolve() - await vi.waitFor(() => expect(updateSettings).toHaveBeenCalledTimes(2)) - expect(settings.nativeChatProviders).toEqual({ claude: false, codex: false }) - }) -}) - -it('offers the selected paired native-only program editor and writes effort without CLI controls', async () => { - inventory.detected = [] - store.localDetectedAgentIdsByContext.host = ['claude', 'antigravity'] - const settings = createGlobalSettingsFixture({ - agentLaunchChoices: {}, - agentPermissionDefault: 'own' - }) - store.settings = settings - const mutate = vi.fn(async () => {}) - const element = () => ( - null} - /> - ) - const view = render(element(), { wrapper: TooltipProvider }) - const label = screen.getByText('Antigravity') - const row = label.closest('.py-3') - if (!(row instanceof HTMLElement)) { - throw new Error('Missing paired native-only row') - } - fireEvent.click(within(row).getByRole('button', { name: 'Expand agent settings' })) - expect(within(row).getByText('Model')).toBeTruthy() - expect(within(row).queryByRole('textbox', { name: 'Arguments' })).toBeNull() - expect(within(row).queryByRole('textbox', { name: 'Command' })).toBeNull() - expect(screen.queryByRole('radiogroup', { name: 'Open Antigravity as' })).toBeNull() - const effort = within(row).getByRole('button', { name: 'Reasoning effort: Default' }) - await userEvent.click(effort) - const option = screen.getAllByRole('menuitemradio').find((item) => item.textContent === 'High') - if (!option) { - throw new Error('Missing paired effort option') - } - fireEvent.click(option) - await vi.waitFor(() => expect(mutate).toHaveBeenCalledOnce()) - expect(mutate.mock.calls[0]).toEqual([ - expect.objectContaining({ - type: 'launch-choices', - agent: 'antigravity', - patch: { options: { effort: 'high' } } - }) - ]) - inventory.chatAvailable = false - view.rerender(element()) - expect(within(row).queryByText('Model')).toBeNull() -}) diff --git a/src/renderer/src/lib/agent-session/launch/new-tab/agent-launch-caller-prompt-transport.test.ts b/src/renderer/src/lib/agent-session/launch/new-tab/agent-launch-caller-prompt-transport.test.ts index 5132d1280e1..2b925a4e7e1 100644 --- a/src/renderer/src/lib/agent-session/launch/new-tab/agent-launch-caller-prompt-transport.test.ts +++ b/src/renderer/src/lib/agent-session/launch/new-tab/agent-launch-caller-prompt-transport.test.ts @@ -11,7 +11,7 @@ const mockPasteDraftWhenAgentReady = vi.fn<(request: Record) => ) vi.mock('@/store/index', () => ({ useAppStore: { getState: () => store } })) -vi.mock('@/lib/new-workspace', () => ({ CLIENT_PLATFORM: 'darwin' })) +vi.mock('@/lib/workspace/creation/new-workspace', () => ({ CLIENT_PLATFORM: 'darwin' })) vi.mock('@/lib/workspace/ownership/connection-context', () => ({ getConnectionIdFromState: mockLaunchConnectionId })) diff --git a/src/renderer/src/lib/agent-session/launch/new-tab/agent-launch-caller-routing.test.ts b/src/renderer/src/lib/agent-session/launch/new-tab/agent-launch-caller-routing.test.ts index ac27d959f1e..dd0fc84fbc2 100644 --- a/src/renderer/src/lib/agent-session/launch/new-tab/agent-launch-caller-routing.test.ts +++ b/src/renderer/src/lib/agent-session/launch/new-tab/agent-launch-caller-routing.test.ts @@ -21,7 +21,7 @@ const mockHostCapabilities = vi.fn<() => readonly string[] | null>(() => []) const mockExecutionHostId = vi.fn(() => 'local') vi.mock('@/store/index', () => ({ useAppStore: { getState: () => store } })) -vi.mock('@/lib/new-workspace', () => ({ CLIENT_PLATFORM: 'darwin' })) +vi.mock('@/lib/workspace/creation/new-workspace', () => ({ CLIENT_PLATFORM: 'darwin' })) vi.mock('@/lib/workspace/ownership/connection-context', () => ({ getConnectionIdFromState: mockLaunchConnectionId })) diff --git a/src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab-main-surface.test.ts b/src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab-main-surface.test.ts index c558d5dff24..8ef96c3b93f 100644 --- a/src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab-main-surface.test.ts +++ b/src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab-main-surface.test.ts @@ -29,7 +29,7 @@ vi.mock('@/store/index', () => ({ } })) -vi.mock('@/lib/host-chat-program-acquisition', async (original) => ({ +vi.mock('@/lib/agent-session/launch/inventory/host-chat-program-acquisition', async (original) => ({ ...(await original()), acquireAgentLaunchChoices: async () => ({ detected: ['claude', 'codex'] }) })) diff --git a/src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-web-host-tab.ts b/src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-web-host-tab.ts index 8f288bf1bcd..852812d26eb 100644 --- a/src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-web-host-tab.ts +++ b/src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-web-host-tab.ts @@ -14,11 +14,11 @@ import { agentSessionCreateCapabilities } from '@/runtime/hosted-terminals/creat import { AGENT_SESSION_CREATE_OPTIONS_RUNTIME_CAPABILITY } from '../../../../../../shared/agent-session/agent-session-runtime-capabilities' import { isRuntimeCompatBlockError } from '@/runtime/rpc/compatibility/runtime-protocol-compat' import { getRuntimeEnvironmentRevision } from '@/runtime/rpc/environment-revisions/runtime-environment-revision' -import { pairedAgentLaunchInputs } from '../../../paired-agent-launch-inputs' +import { pairedAgentLaunchInputs } from '../routing/paired-agent-launch-inputs' import { createWebRuntimeSessionTerminalResult } from '@/runtime/hosted-terminals/creation/web-runtime-terminal-create-operation' import { toast } from 'sonner' import { useAppStore } from '@/store/index' -import { completeWebHostAgentLaunch } from '@/lib/web-host-agent-launch-completion' +import { completeWebHostAgentLaunch } from '@/lib/agent-session/launch/new-tab/web-host-agent-launch-completion' import { deliverCreatedWebRuntimeAgentSessionPrompt } from '@/runtime/hosted-terminals/creation/web-runtime-created-agent-prompt-delivery' import type { CreateWebRuntimeSessionTerminalOnHostArgs } from '@/runtime/hosted-terminals/creation/terminal-create-contracts' import { diff --git a/src/renderer/src/lib/web-host-agent-launch-completion.ts b/src/renderer/src/lib/agent-session/launch/new-tab/web-host-agent-launch-completion.ts similarity index 78% rename from src/renderer/src/lib/web-host-agent-launch-completion.ts rename to src/renderer/src/lib/agent-session/launch/new-tab/web-host-agent-launch-completion.ts index 5fbe9176ba1..0fce2e3bac9 100644 --- a/src/renderer/src/lib/web-host-agent-launch-completion.ts +++ b/src/renderer/src/lib/agent-session/launch/new-tab/web-host-agent-launch-completion.ts @@ -1,11 +1,11 @@ import { toast } from 'sonner' -import { useAppStore } from '@/store' -import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' +import { useAppStore } from '@/store/index' +import type { TuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent' import type { WebRuntimeTerminalCreateOutcome } from '@/runtime/hosted-terminals/creation/terminal-create-contracts' -import type { AgentTerminalLaunchCompletion } from './agent-session/launch/structured-agent-session-launch-admission' +import type { AgentTerminalLaunchCompletion } from '../structured-agent-session-launch-admission' import { webTerminalPlacementParentTabId } from '@/runtime/hosted-terminals/placement/web-session-terminal-placement' -import { toWebTerminalSurfaceTabId } from '../../../shared/workspace-layout/terminal-surface-id' -import { notifyAgentLaunchPromptNotSent } from './agent-session/launch/prompt/agent-launch-prompt-failure-notice' +import { toWebTerminalSurfaceTabId } from '../../../../../../shared/workspace-layout/terminal-surface-id' +import { notifyAgentLaunchPromptNotSent } from '../prompt/agent-launch-prompt-failure-notice' export function completeWebHostAgentLaunch(args: { agent: TuiAgent diff --git a/src/renderer/src/lib/agent-session/launch/prompt/launch-agent-tab-prompt-paste.ts b/src/renderer/src/lib/agent-session/launch/prompt/launch-agent-tab-prompt-paste.ts index d956f602ad5..1274f495e2f 100644 --- a/src/renderer/src/lib/agent-session/launch/prompt/launch-agent-tab-prompt-paste.ts +++ b/src/renderer/src/lib/agent-session/launch/prompt/launch-agent-tab-prompt-paste.ts @@ -1,6 +1,6 @@ import { createPasteReadinessTimeoutNotice } from '@/lib/agent-session/launch/prompt/launch-agent-paste-timeout-notice' import { deliverLaunchPromptToAgentTab } from '@/lib/agent-session/launch/prompt/agent-launch-prompt-delivery' -import { seedCommandCodeSubmittedPromptStatus } from '@/lib/command-code-prompt-status-seed' +import { seedCommandCodeSubmittedPromptStatus } from '@/lib/agent-status/evidence/command-code-prompt-status-seed' import type { TuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent' /** Share readiness/paste delivery and outcome reporting for both window-spawned and agent.launch-owned tab PTYs. */ diff --git a/src/renderer/src/lib/new-agent-prompt-outcome.ts b/src/renderer/src/lib/agent-session/launch/prompt/new-agent-prompt-outcome.ts similarity index 84% rename from src/renderer/src/lib/new-agent-prompt-outcome.ts rename to src/renderer/src/lib/agent-session/launch/prompt/new-agent-prompt-outcome.ts index 8ca58e5ca5b..d7474672eb3 100644 --- a/src/renderer/src/lib/new-agent-prompt-outcome.ts +++ b/src/renderer/src/lib/agent-session/launch/prompt/new-agent-prompt-outcome.ts @@ -1,5 +1,5 @@ -import type { ActiveAgentNotesSendResult } from './agent-session/messaging/terminal/active-agent-note-send-result' -import type { StructuredPromptDeliveryResult } from './agent-session/launch/structured-agent-session-launch-prompt' +import type { ActiveAgentNotesSendResult } from '../../messaging/terminal/active-agent-note-send-result' +import type { StructuredPromptDeliveryResult } from '../structured-agent-session-launch-callers' /** Delivered releases notes once host/composer owns the text; failure is omitted when the chat already reports startup/cancellation. */ export type NewAgentPromptOutcome = { delivered: boolean; failure?: ActiveAgentNotesSendResult } diff --git a/src/renderer/src/lib/paired-agent-launch-inputs.ts b/src/renderer/src/lib/agent-session/launch/routing/paired-agent-launch-inputs.ts similarity index 80% rename from src/renderer/src/lib/paired-agent-launch-inputs.ts rename to src/renderer/src/lib/agent-session/launch/routing/paired-agent-launch-inputs.ts index a590564d30f..774b7966c7a 100644 --- a/src/renderer/src/lib/paired-agent-launch-inputs.ts +++ b/src/renderer/src/lib/agent-session/launch/routing/paired-agent-launch-inputs.ts @@ -1,32 +1,32 @@ -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { readHostAgentLaunchSettings, hostAgentLaunchSettingsSource } from '@/runtime/agent-launch-settings/agent-launch-settings-transport' import { getRuntimeEnvironmentRevision } from '@/runtime/rpc/environment-revisions/runtime-environment-revision' -import { lastVerifiedRuntimeStatus } from '../../../shared/remote-runtime/host-status/runtime-host-status' +import { lastVerifiedRuntimeStatus } from '../../../../../../shared/remote-runtime/host-status/runtime-host-status' import { agentLaunchNeedsPreparedCommand, toAgentLaunchPreferences -} from '../../../shared/agent-launch/choices/agent-launch-preferences' -import { projectAgentLaunchProfile } from '../../../shared/agent-launch/choices/agent-launch-profile' -import { resolveAgentStartupPlanInputs } from '../../../shared/agent-launch/startup/agent-startup-plan-inputs' -import { sourceControlActionAgentArgs } from '../../../shared/source-control/ai/recipes/source-control-action-launch-preferences' -import { agentArgsSetPermission } from '../../../shared/agent-launch/permissions/agent-permission-args' -import { liftAgentPermissionArgs } from '../../../shared/agent-launch/permissions/tui-agent-permission-lift' +} from '../../../../../../shared/agent-launch/choices/agent-launch-preferences' +import { projectAgentLaunchProfile } from '../../../../../../shared/agent-launch/choices/agent-launch-profile' +import { resolveAgentStartupPlanInputs } from '../../../../../../shared/agent-launch/startup/agent-startup-plan-inputs' +import { sourceControlActionAgentArgs } from '../../../../../../shared/source-control/ai/recipes/source-control-action-launch-preferences' +import { agentArgsSetPermission } from '../../../../../../shared/agent-launch/permissions/agent-permission-args' +import { liftAgentPermissionArgs } from '../../../../../../shared/agent-launch/permissions/tui-agent-permission-lift' import { agentPermissionHasTerminalChoice, readLaunchPermissionChoice -} from '../../../shared/agent-launch/permissions/tui-agent-permission-choice' -import { YOLO_TUI_AGENT_ENV } from '../../../shared/agent-launch/permissions/tui-agent-permissions' +} from '../../../../../../shared/agent-launch/permissions/tui-agent-permission-choice' +import { YOLO_TUI_AGENT_ENV } from '../../../../../../shared/agent-launch/permissions/tui-agent-permissions' import { resolveStartupShell, tokenizeStartupCommand, type AgentStartupShell -} from '../../../shared/agent-launch/startup/tui-agent-startup-shell' -import { resolveHostAgentStartupShell } from '../../../shared/windows-terminal-shell' -import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' -import type { SessionOptionValue } from '../../../shared/native-chat/input/native-chat-session-options' +} from '../../../../../../shared/agent-launch/startup/tui-agent-startup-shell' +import { resolveHostAgentStartupShell } from '../../../../../../shared/windows-terminal-shell' +import type { TuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent' +import type { SessionOptionValue } from '../../../../../../shared/native-chat/input/native-chat-session-options' export async function pairedAgentLaunchInputs(args: { environmentId: string diff --git a/src/renderer/src/lib/agent-session/launch/shortcuts/agent-tab-shortcuts.ts b/src/renderer/src/lib/agent-session/launch/shortcuts/agent-tab-shortcuts.ts index 7819d763499..014507a9df3 100644 --- a/src/renderer/src/lib/agent-session/launch/shortcuts/agent-tab-shortcuts.ts +++ b/src/renderer/src/lib/agent-session/launch/shortcuts/agent-tab-shortcuts.ts @@ -1,4 +1,4 @@ -import { acquireAgentLaunchChoices } from '../../../host-chat-program-acquisition' +import { acquireAgentLaunchChoices } from '../inventory/host-chat-program-acquisition' import { agentTabActionId } from '../../../../../../shared/keybindings/definitions' import type { AgentTabActionId, @@ -17,7 +17,7 @@ import { type ProspectiveWorkspace, worktreeLaunchWorkspace } from '@/lib/agent-session/launch/routing/agent-launch-route-input' -import { agentChoiceMayOpenAsChat } from '@/lib/host-chat-program' +import { agentChoiceMayOpenAsChat } from '@/lib/agent-session/launch/inventory/host-chat-program' import { ensureAgentLaunchPreferences, readAgentLaunchPreferencesForWorktree diff --git a/src/renderer/src/lib/agent-session/resume/agent-resume-launch-target.ts b/src/renderer/src/lib/agent-session/resume/agent-resume-launch-target.ts index 8ff1a7e73a2..95a2a9f1191 100644 --- a/src/renderer/src/lib/agent-session/resume/agent-resume-launch-target.ts +++ b/src/renderer/src/lib/agent-session/resume/agent-resume-launch-target.ts @@ -1,4 +1,4 @@ -import { CLIENT_PLATFORM } from '@/lib/new-workspace' +import { CLIENT_PLATFORM } from '@/lib/workspace/creation/new-workspace' import { REMOTE_RUNTIME_PTY_HONOURS_TAB_SHELL_OVERRIDE } from '@/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-shell' import { parseExecutionHostId } from '../../../../../shared/execution-host' import { lastVerifiedRuntimeStatus } from '../../../../../shared/remote-runtime/host-status/runtime-host-status' diff --git a/src/renderer/src/lib/agent-session/resume/history/ai-vault-antigravity-reference-host.test.ts b/src/renderer/src/lib/agent-session/resume/history/ai-vault-antigravity-reference-host.test.ts index 971351bdf03..0d579f24429 100644 --- a/src/renderer/src/lib/agent-session/resume/history/ai-vault-antigravity-reference-host.test.ts +++ b/src/renderer/src/lib/agent-session/resume/history/ai-vault-antigravity-reference-host.test.ts @@ -2,17 +2,13 @@ import { describe, expect, it, vi } from 'vitest' import { makeFolderWorkspace } from '@/store/folder-workspaces/folder-workspace.test-fixture' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' import { resolveAiVaultSessionLaunchTarget } from '@/components/right-sidebar/ai-vault/session-actions/ai-vault-session-launch-target' -import { - buildAiVaultResumeCopyCommandForWorktree, - buildAiVaultResumeStartupForWorktree -} from './ai-vault-resume-command' +import type { buildAiVaultResumeStartupForWorktree } from './ai-vault-resume-command' import { getAiVaultResumeWorkspaceWslDistro } from './ai-vault-resume-shell' -import { buildAgentLaunchRouteInput } from '../../launch/routing/agent-launch-route-input' -import { getLocalProjectExecutionRuntimeContext } from '../../../local-preflight-context' + import type { ExecutionHostId } from '../../../../../../shared/execution-host' import { createGlobalSettingsFixture } from '../../../../../../shared/global-settings-test-fixture' -vi.mock('@/lib/new-workspace', () => ({ CLIENT_PLATFORM: 'win32' })) +vi.mock('@/lib/workspace/creation/new-workspace', () => ({ CLIENT_PLATFORM: 'win32' })) vi.mock('@/lib/renderer-app-platform', () => ({ getRendererAppPlatform: () => 'win32' })) type State = Parameters[0]['state'] @@ -64,59 +60,7 @@ function stateFor(host: ExecutionHostId, distro?: string): State { } } -const cases = [ - { source: 'local', target: 'local', file: debianFile, distro: 'Debian', allowed: true }, - { source: 'local', target: 'local', file: debianFile, distro: 'Ubuntu', allowed: false }, - { source: 'local', target: 'local', file: debianFile, allowed: false }, - { source: 'local', target: 'local', file: windowsFile, distro: 'Debian', allowed: false }, - { source: 'local', target: 'local', file: windowsFile, allowed: true }, - { source: 'local', target: 'ssh:other', file: debianFile, allowed: false }, - { source: 'ssh:owner', target: 'ssh:other', file: linuxFile, allowed: false }, - { source: 'ssh:owner', target: 'local', file: linuxFile, allowed: false }, - { source: 'ssh:owner', target: 'ssh:owner', file: linuxFile, allowed: true }, - { source: 'runtime:owner', target: 'runtime:other', file: linuxFile, allowed: false }, - { source: 'runtime:owner', target: 'runtime:owner', file: linuxFile, allowed: true } -] as const - describe('Antigravity transcript reference ownership', () => { - it.each(cases)( - 'confines $file from $source to $target ($distro)', - ({ source, target, file, allowed, ...options }) => { - const distro = 'distro' in options ? options.distro : undefined - const state = stateFor(target, distro) - const session = { - agent: 'antigravity' as const, - sessionId: 'copied-id', - cwd: null, - codexHome: null, - executionHostId: source, - executionHostPlatform: target === 'local' ? ('win32' as const) : ('linux' as const), - filePath: file - } - const launch = resolveAiVaultSessionLaunchTarget({ - sessionFilePath: file, - sessionExecutionHostId: source, - activeWorktreeId: state.activeWorktreeId, - targetState: state - }) - expect(launch.status).toBe(allowed ? 'ready' : 'unsupported') - for (const build of [ - buildAiVaultResumeStartupForWorktree, - buildAiVaultResumeCopyCommandForWorktree - ]) { - if (!allowed) { - expect(() => build({ state, session })).toThrow('execution host or WSL distro') - } else { - const result = build({ state, session }) - const command = typeof result === 'string' ? result : result.command - expect(command).toContain('--prompt-interactive') - expect(command).not.toContain('--conversation') - expect(command).not.toContain('wsl.localhost') - } - } - } - ) - it('applies the same confinement to folder workspaces', () => { const state = stateFor('local') state.activeRepoId = null @@ -145,32 +89,6 @@ describe('Antigravity transcript reference ownership', () => { ).toBe('unsupported') }) - it('uses the folder launch project runtime for a native folder path', () => { - const state = stateFor('local', 'Debian') - state.activeWorktreeId = 'folder:folder-1' - state.folderWorkspaces = [makeFolderWorkspace({ folderPath: 'C:/project/folder' })] - expect( - buildAgentLaunchRouteInput(state, { - agent: 'antigravity', - workspace: { kind: 'folder', repoId: 'repo' } - }).projectRuntime - ).toMatchObject({ status: 'resolved', runtime: { kind: 'wsl', distro: 'Debian' } }) - expect(getAiVaultResumeWorkspaceWslDistro(state, state.activeWorktreeId)).toBe('Debian') - for (const [file, status] of [ - [windowsFile, 'unsupported'], - [debianFile, 'ready'] - ] as const) { - expect( - resolveAiVaultSessionLaunchTarget({ - sessionFilePath: file, - sessionExecutionHostId: 'local', - activeWorktreeId: state.activeWorktreeId, - targetState: state - }).status - ).toBe(status) - } - }) - it('lets an explicit folder project runtime override the UNC path distro', () => { const state = stateFor('local', 'Ubuntu') state.activeWorktreeId = 'folder:folder-1' @@ -210,57 +128,6 @@ describe('Antigravity transcript reference ownership', () => { ).toBe('ready') }) - it('uses the target folder owner for both the pane and reference gate with another repo active', () => { - const state = stateFor('local', 'Ubuntu') - state.repos[0].path = 'C:/project' - state.repos[0].kind = 'folder' - state.activeRepoId = 'unrelated' - state.activeWorktreeId = 'unrelated::workspace' - state.repos = [ - ...state.repos, - { - id: 'unrelated', - path: 'C:/elsewhere', - displayName: 'unrelated', - badgeColor: '', - addedAt: 0 - } - ] - state.folderWorkspaces = [makeFolderWorkspace({ folderPath: 'C:/project/folder' })] - const target = 'folder:folder-1' - expect(getLocalProjectExecutionRuntimeContext(state, target, 'win32')).toMatchObject({ - status: 'resolved', - runtime: { kind: 'wsl', distro: 'Ubuntu' } - }) - expect(getAiVaultResumeWorkspaceWslDistro(state, target)).toBe('Ubuntu') - for (const [file, expected] of [ - [windowsFile, 'unsupported'], - [debianFile.replace('Debian', 'Ubuntu'), 'ready'] - ] as const) { - expect( - resolveAiVaultSessionLaunchTarget({ - sessionFilePath: file, - sessionExecutionHostId: 'local', - activeWorktreeId: state.activeWorktreeId, - targetWorktreeId: target, - targetState: state - }).status - ).toBe(expected) - } - }) - - it('keeps explicit SSH folder authority ahead of a matching local project path', () => { - const state = stateFor('local', 'Debian') - state.repos[0].path = 'C:/project' - state.folderWorkspaces = [ - makeFolderWorkspace({ folderPath: 'C:/project/folder', executionHostId: 'ssh:owner' }) - ] - expect( - getLocalProjectExecutionRuntimeContext(state, 'folder:folder-1', 'win32') - ).toBeUndefined() - expect(getAiVaultResumeWorkspaceWslDistro(state, 'folder:folder-1')).toBeNull() - }) - it('refuses local references while the project runtime requires repair', () => { const state = stateFor('local') state.projects[0].localWindowsRuntimePreference = { kind: 'inherit-global' } diff --git a/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-command.drop-repin.test.ts b/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-command.drop-repin.test.ts index e71f11cbcd9..b21c2b6e869 100644 --- a/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-command.drop-repin.test.ts +++ b/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-command.drop-repin.test.ts @@ -5,7 +5,7 @@ import { makeWorktree } from '../../../../store/slices/worktrees/worktree.test-f import { describe, expect, it, vi } from 'vitest' import { buildAiVaultDropRepinStartup } from './ai-vault-resume-command' -vi.mock('@/lib/new-workspace', () => ({ +vi.mock('@/lib/workspace/creation/new-workspace', () => ({ CLIENT_PLATFORM: 'darwin' })) diff --git a/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-command.test.ts b/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-command.test.ts index c003b5d33b9..6bbb9716e38 100644 --- a/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-command.test.ts +++ b/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-command.test.ts @@ -7,11 +7,8 @@ import { buildAiVaultResumeCopyCommandForWorktree, buildAiVaultResumeStartupForWorktree } from './ai-vault-resume-command' -import { getAiVaultAgentProviderSession } from '../../../../../../shared/ai-vault/resume/ai-vault-resume-startup' -import { dropDeletedRemoteResumeCwd } from './ai-vault-session-resume-preparation' -import { RuntimeRpcCallError } from '@/runtime/rpc/calls/runtime-rpc-result' -vi.mock('@/lib/new-workspace', () => ({ +vi.mock('@/lib/workspace/creation/new-workspace', () => ({ CLIENT_PLATFORM: 'win32' })) @@ -82,47 +79,6 @@ function buildQueuedAiVaultResumeCommand( } describe('ai vault resume command runtime', () => { - it.each(['local', 'ssh:reference-host'] as const)( - 'starts a fresh IDE reference on %s with model and environment preserved', - (executionHostId) => { - const state = makeState({ - worktreePath: '\\\\wsl.localhost\\Ubuntu\\home\\example\\project', - localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' } - }) - if (executionHostId !== 'local') { - state.repos = state.repos.map((repo) => ({ ...repo, executionHostId })) - } - const session = { - agent: 'antigravity' as const, - sessionId: 'ide-id', - cwd: '/home/example/project', - codexHome: null, - executionHostId, - executionHostPlatform: 'linux' as const, - resumeCommand: 'agy --conversation ide-id', - filePath: - executionHostId === 'local' - ? '\\\\wsl.localhost\\Ubuntu\\home\\example\\.gemini\\antigravity-ide\\brain\\ide-id\\.system_generated\\logs\\transcript_full.jsonl' - : '/home/example/.gemini/antigravity-ide/brain/ide-id/.system_generated/logs/transcript_full.jsonl' - } - if (!state.settings) { - throw new Error('Missing fixture settings') - } - state.settings.agentDefaultArgs = { antigravity: '--model claude-sonnet-4-6' } - state.settings.agentDefaultEnv = { antigravity: { AGY_CLI_HIDE_ACCOUNT_INFO: '1' } } - const startup = buildAiVaultResumeStartupForWorktree({ state, session }) - expect(startup.command).toContain('--prompt-interactive') - expect(startup.command).not.toContain('--conversation') - expect(startup.command).not.toContain('wsl.localhost') - expect(startup.command).toContain('--model') - expect(startup.command).toContain('claude-sonnet-4-6') - expect(startup.env).toMatchObject({ AGY_CLI_HIDE_ACCOUNT_INFO: '1' }) - expect(startup.providerSession).toBeUndefined() - expect(getAiVaultAgentProviderSession(session)).toBeNull() - expect(startup.cwd).toBe('/home/example/project') - } - ) - it('repro: queues a host-runtime resume without configured-WSL shell syntax', () => { const state = makeState({ worktreePath: 'C:\\Users\\alice\\repo', @@ -414,73 +370,6 @@ describe('ai vault resume command runtime', () => { }) }) - it('resumes an SSH session at the workspace root once the host reports its folder deleted', async () => { - const pathExists = vi.fn().mockResolvedValue(false) - vi.stubGlobal('window', { api: { fs: { pathExists } } }) - const session = { - agent: 'codex' as const, - sessionId: 'session one', - cwd: '/home/alice/wt/feat-x', - codexHome: '/home/alice/.codex', - executionHostId: 'ssh:dev-box' as const, - executionHostPlatform: 'linux' as const, - resumeCommand: - "cd '/home/alice/wt/feat-x' && CODEX_HOME='/home/alice/.codex' codex resume 'session one'" - } - - const startup = buildAiVaultResumeStartupForWorktree({ - state: makeState({ worktreePath: '/home/alice/wt/main' }), - worktreeId: 'repo-1::worktree-1', - session: await dropDeletedRemoteResumeCwd(session) - }) - - // A deleted SSH cwd blocks startup, and Codex retains that missing folder even when resumed at root (#17745). - expect(startup.command).not.toContain('feat-x') - expect(startup.command).toContain("'-c' 'tui.resume_cwd=current' 'resume'") - expect(startup.cwd).toBeUndefined() - expect(pathExists).toHaveBeenCalledWith({ - filePath: '/home/alice/wt/feat-x', - connectionId: 'dev-box' - }) - }) - - it('resumes a paired server session at the workspace root once the server reports its folder deleted', async () => { - browseServerDir.mockImplementation(async (_environmentId: string, path: string) => { - if (path === '~') { - return { resolvedPath: '/home/alice', entries: [], pathFlavor: 'posix' } - } - throw new RuntimeRpcCallError({ - id: 'req', - ok: false, - error: { - code: 'runtime_error', - message: `ENOENT: no such file or directory, stat '${path}'` - } - }) - }) - const session = { - agent: 'codex' as const, - sessionId: 'session one', - cwd: '/home/alice/wt/feat-x', - codexHome: '/home/alice/.codex', - executionHostId: 'runtime:env-1' as const, - executionHostPlatform: 'linux' as const, - resumeCommand: - "cd '/home/alice/wt/feat-x' && CODEX_HOME='/home/alice/.codex' codex resume 'session one'" - } - - const startup = buildAiVaultResumeStartupForWorktree({ - state: makeState({ worktreePath: '/home/alice/wt/main' }), - worktreeId: 'repo-1::worktree-1', - session: await dropDeletedRemoteResumeCwd(session) - }) - - expect(startup.command).not.toContain('feat-x') - expect(startup.command).toContain("'-c' 'tui.resume_cwd=current' 'resume'") - expect(startup.cwd).toBeUndefined() - expect(browseServerDir).toHaveBeenCalledWith('env-1', '/home/alice/wt/feat-x') - }) - it('rebuilds remote real-home Codex commands without a stored home assignment', () => { const state = makeState({ worktreePath: '/home/alice/repo' }) state.repos = [{ id: 'repo-1', path: '/home/alice/repo', connectionId: 'ssh-1' }] as never diff --git a/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-platform.test.ts b/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-platform.test.ts index 759bcba24c7..b11380e0b8e 100644 --- a/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-platform.test.ts +++ b/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-platform.test.ts @@ -5,7 +5,7 @@ import { makeWorktree } from '../../../../store/slices/worktrees/worktree.test-f import type { AiVaultResumePlatformState } from './ai-vault-resume-platform' import { buildAiVaultDropRepinStartup } from './ai-vault-resume-command' -vi.mock('@/lib/new-workspace', () => ({ CLIENT_PLATFORM: 'darwin' })) +vi.mock('@/lib/workspace/creation/new-workspace', () => ({ CLIENT_PLATFORM: 'darwin' })) const WORKTREE_ID = 'repo-1::/srv/repo' diff --git a/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-platform.ts b/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-platform.ts index 81aa282e883..1a81a95eeff 100644 --- a/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-platform.ts +++ b/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-platform.ts @@ -1,5 +1,5 @@ import { getLocalProjectExecutionRuntimeContext } from '@/lib/local-preflight-context' -import { CLIENT_PLATFORM } from '@/lib/new-workspace' +import { CLIENT_PLATFORM } from '@/lib/workspace/creation/new-workspace' import { getExecutionHostIdForWorktree } from '@/lib/workspace/ownership/worktree-runtime-owner' import { getAiVaultResumeWorkspacePath } from '@/lib/agent-session/resume/history/ai-vault-resume-shell' import { resolveWorktreeExecutionHostPlatform } from '@/runtime/hosts/platform/execution-host-facts' diff --git a/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-shell.ts b/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-shell.ts index 54657b86fa3..58ad749f9d9 100644 --- a/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-shell.ts +++ b/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-shell.ts @@ -4,7 +4,7 @@ import '../../../workspace/ownership/folder-workspace-connection' import { findFolderWorkspaceCandidateRepos } from '../../../../../../shared/folder-workspaces/folder-workspace-execution-host' import { getAiVaultResumeWorkspaceExecutionHostId } from './ai-vault-resume-target' import { LOCAL_EXECUTION_HOST_ID } from '../../../../../../shared/execution-host' -import { CLIENT_PLATFORM } from '@/lib/new-workspace' +import { CLIENT_PLATFORM } from '@/lib/workspace/creation/new-workspace' import { resolveLocalWindowsTerminalShellOverrideForTab } from '../../../../../../shared/local-windows-terminal-runtime' import { resolveWindowsShellStartupFamily } from '../../../../../../shared/windows-terminal-shell' import { diff --git a/src/renderer/src/lib/command-code-prompt-status-seed.ts b/src/renderer/src/lib/agent-status/evidence/command-code-prompt-status-seed.ts similarity index 80% rename from src/renderer/src/lib/command-code-prompt-status-seed.ts rename to src/renderer/src/lib/agent-status/evidence/command-code-prompt-status-seed.ts index 217e1aa1177..9081d3fcddd 100644 --- a/src/renderer/src/lib/command-code-prompt-status-seed.ts +++ b/src/renderer/src/lib/agent-status/evidence/command-code-prompt-status-seed.ts @@ -1,7 +1,7 @@ -import { useAppStore } from '@/store' -import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { getConnectionIdFromState } from './workspace/ownership/connection-owner-resolution' -import { resolveLiveAgentStatusConnectionRouting } from './agent-status/ownership/agent-status-connection-ownership' +import { useAppStore } from '@/store/index' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' +import { getConnectionIdFromState } from '../../workspace/ownership/connection-owner-resolution' +import { resolveLiveAgentStatusConnectionRouting } from '../ownership/agent-status-connection-ownership' import { rendererAgentStatusObservations } from './renderer-agent-status-observations' // Command Code lacks prompt-submit hooks; seed working when generated input is delivered so rows do not stay idle until its next hook. diff --git a/src/renderer/src/lib/renderer-agent-status-observations.ts b/src/renderer/src/lib/agent-status/evidence/renderer-agent-status-observations.ts similarity index 85% rename from src/renderer/src/lib/renderer-agent-status-observations.ts rename to src/renderer/src/lib/agent-status/evidence/renderer-agent-status-observations.ts index a6d220e919d..5e0c5465192 100644 --- a/src/renderer/src/lib/renderer-agent-status-observations.ts +++ b/src/renderer/src/lib/agent-status/evidence/renderer-agent-status-observations.ts @@ -1,7 +1,7 @@ import { AgentStatusObservationSequencer, createAgentStatusAuthorityId -} from '../../../shared/agent-status/contracts/agent-status-observation' +} from '../../../../../shared/agent-status/contracts/agent-status-observation' /** Sequence only renderer-owned remote-runtime OSC/launch/Command Code seeds; main-stamped rows retain main’s authority. Observation IDs across authorities are incomparable (shared/agent-status-observation.ts); not yet consumed (STA-4293). */ export const rendererAgentStatusObservations = new AgentStatusObservationSequencer( diff --git a/src/renderer/src/lib/hook-command-delayed-delivery.test.ts b/src/renderer/src/lib/hook-command-delayed-delivery.test.ts deleted file mode 100644 index e98c4f0c469..00000000000 --- a/src/renderer/src/lib/hook-command-delayed-delivery.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store' -import { - queueHookCommandsForFirstWorktreeTab, - resetHookCommandDelayedDeliveryForTests -} from './hook-command-delayed-delivery' - -type AppState = ReturnType - -const initialTabsByWorktree = useAppStore.getState().tabsByWorktree -const initialGetKnownWorktreeById = useAppStore.getState().getKnownWorktreeById - -function setStorePartial(partial: Record): void { - useAppStore.setState(partial as Partial) -} - -function markWorktreeKnown(worktreeId: string): void { - setStorePartial({ - getKnownWorktreeById: ((id: string) => - id === worktreeId ? { id } : undefined) as unknown as AppState['getKnownWorktreeById'] - }) -} - -afterEach(() => { - resetHookCommandDelayedDeliveryForTests() - setStorePartial({ - tabsByWorktree: initialTabsByWorktree, - getKnownWorktreeById: initialGetKnownWorktreeById - }) -}) - -describe('queueHookCommandsForFirstWorktreeTab', () => { - it('holds the delivery until the first worktree tab lands, then delivers exactly once', () => { - markWorktreeKnown('wt-1') - setStorePartial({ tabsByWorktree: {} }) - const deliver = vi.fn() - - queueHookCommandsForFirstWorktreeTab({ worktreeId: 'wt-1', deliver }) - expect(deliver).not.toHaveBeenCalled() - - setStorePartial({ tabsByWorktree: { 'wt-1': [{ id: 'mirror-tab-1' }] } }) - - expect(deliver).toHaveBeenCalledTimes(1) - expect(deliver).toHaveBeenCalledWith(expect.anything(), 'mirror-tab-1') - - // Later tab churn must not re-deliver the consumed entry. - setStorePartial({ tabsByWorktree: { 'wt-1': [{ id: 'mirror-tab-1' }, { id: 'tab-2' }] } }) - expect(deliver).toHaveBeenCalledTimes(1) - }) - - it('keeps every delivery queued for the same worktree', () => { - // Setup/issue commands and agent seeds must coexist while awaiting the same mirrored terminal. - markWorktreeKnown('wt-1') - setStorePartial({ tabsByWorktree: {} }) - const deliverFirst = vi.fn() - const deliverSecond = vi.fn() - - queueHookCommandsForFirstWorktreeTab({ worktreeId: 'wt-1', deliver: deliverFirst }) - queueHookCommandsForFirstWorktreeTab({ worktreeId: 'wt-1', deliver: deliverSecond }) - - setStorePartial({ tabsByWorktree: { 'wt-1': [{ id: 'mirror-tab-1' }] } }) - - expect(deliverFirst).toHaveBeenCalledTimes(1) - expect(deliverSecond).toHaveBeenCalledTimes(1) - expect(deliverSecond).toHaveBeenCalledWith(expect.anything(), 'mirror-tab-1') - }) -}) diff --git a/src/renderer/src/lib/host-chat-program.test.ts b/src/renderer/src/lib/host-chat-program.test.ts deleted file mode 100644 index ae39be3f79f..00000000000 --- a/src/renderer/src/lib/host-chat-program.test.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { agentTabLaunchStore } from './agent-session/launch/new-tab/launch-agent-execution-context' -import { getRuntimeAgentInventoryKey } from '@/store/slices/agent-inventory/runtime-agent-inventory-key' -import { resolveDefaultAgentForWorkspace } from './agent-session/launch/shortcuts/agent-tab-shortcuts' -import { EVERY_AGENT_CHAT } from '../../../shared/native-chat/every-agent-chat.test-fixture' - -import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' -import { TEST_REPO } from '@/store/repos/repo.test-fixture' - -import { afterEach, assert, beforeEach, expect, it, vi } from 'vitest' -import { getDefaultSettings } from '../../../shared/constants' - -import { clearHostAgentMenuSettingsForTests } from '@/runtime/agent-launch-settings/host-agent-launch-preferences-resource' - -import { createCompatibleRuntimeStatusResponse } from '@/runtime/rpc/testing/runtime-compatibility-test-fixture' -import { MANAGED_RUNTIME_INSTALL_RUNTIME_CAPABILITY as INSTALL } from '../../../shared/managed-runtime-install' -import { - STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY as CATALOG, - STRUCTURED_AGENT_SESSION_AVAILABILITY_RUNTIME_CAPABILITY as HEALTH -} from '../../../shared/agent-session/structured-agent-session-surface-capabilities' -import { - STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY as CHAT, - STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY as MODE -} from '../../../shared/agent-session/agent-session-runtime-capabilities' -const rpc = vi.hoisted(() => ({ - call: vi.fn(), - subscribe: vi.fn(), - direct: vi.fn(), - supports: vi.fn() -})) -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ - callRuntimeRpc: rpc.call -})) -vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', () => ({ - runtimeEnvironmentSupportsCapability: rpc.supports -})) -vi.mock('@/runtime/rpc/subscriptions/runtime-rpc-subscribe', () => ({ - subscribeRuntimeRpc: rpc.subscribe -})) -import { useAppStore } from '@/store' -import { resetHostStructuredAgentsForTests } from '@/runtime/native-chat/agent-catalogs/host-structured-agents' -import { setLocalRuntimeCapabilitiesForTests } from '@/runtime/hosts/capabilities/local-runtime-capabilities' -import { acquireAgentLaunchChoices } from './host-chat-program-acquisition' - -vi.mock('./workspace/creation/work-item/launch-work-item-direct', () => ({ - launchWorkItemDirect: rpc.direct -})) -const CAPS = [CHAT, CATALOG, INSTALL, HEALTH, MODE] -const workspace = { kind: 'git-worktree', runtimeEnvironmentId: 'B' } as const - -const initial = useAppStore.getState() -const runtime = createCompatibleRuntimeStatusResponse() -assert(runtime.ok, 'Expected compatible runtime fixture') -const status = (runtimeId = 'r1', connectionGeneration?: number) => ({ - connectionGeneration, - status: { ...runtime.result, runtimeId, capabilities: CAPS }, - checkedAt: 1 -}) -const managed = { agent: 'antigravity', capabilities: {}, managedRuntime: true } -const catalog = { agents: [managed, { agent: 'grok', capabilities: {} }] } -const frame = (agent: string, chatProgram: string) => ({ - type: 'availability', - agents: [{ agent, state: 'available', chatProgram }] -}) -const flush = () => - Array.from({ length: 12 }).reduce>((tick) => tick.then(), Promise.resolve()) -beforeEach(() => { - rpc.call.mockReset().mockResolvedValue(catalog) - rpc.supports.mockReset().mockResolvedValue(true) - rpc.subscribe.mockReset().mockResolvedValue({ unsubscribe: vi.fn() }) - setLocalRuntimeCapabilitiesForTests(CAPS) - useAppStore.setState({ - settings: { ...getDefaultSettings('/tmp'), nativeChatProviders: EVERY_AGENT_CHAT }, - runtimeStatusByEnvironmentId: new Map([['B', status()]]) - }) -}) -afterEach(() => { - vi.useRealTimers() - resetHostStructuredAgentsForTests() - clearHostAgentMenuSettingsForTests() - setLocalRuntimeCapabilitiesForTests(null) - useAppStore.setState(initial, true) -}) - -it('releases a pending stream at the chat deadline while slow ordinary detection keeps waiting', async () => { - vi.useFakeTimers() - const handle = Promise.withResolvers<{ unsubscribe: () => void }>() - const detect = Promise.withResolvers<[]>() - rpc.subscribe.mockReturnValue(handle.promise) - const action = acquireAgentLaunchChoices(workspace, () => detect.promise) - const settled = vi.fn() - void action.then(settled) - await flush() - await vi.advanceTimersByTimeAsync(5000) - expect(settled).not.toHaveBeenCalled() - useAppStore.setState({ runtimeStatusByEnvironmentId: new Map([['B', status('r1', 1)]]) }) - expect(rpc.subscribe).toHaveBeenCalledOnce() - const unsubscribe = vi.fn() - handle.resolve({ unsubscribe }) - await flush() - expect(unsubscribe).toHaveBeenCalledOnce() - detect.resolve([]) - await action -}) -it('keeps one still-detecting action on the current open through learning/reconnect', async () => { - useAppStore.setState({ runtimeStatusByEnvironmentId: new Map() }) - const detect = Promise.withResolvers<[]>() - const settled = vi.fn() - const action = acquireAgentLaunchChoices(workspace, () => detect.promise).then(settled) - useAppStore.setState({ runtimeStatusByEnvironmentId: new Map([['B', status()]]) }) - await flush() - rpc.subscribe.mock.calls.at(-1)![3].onEvent(frame('grok', 'available')) - rpc.subscribe.mock.calls.at(-1)![3].onClose() - useAppStore.setState({ runtimeStatusByEnvironmentId: new Map([['B', status('r1', 1)]]) }) - detect.resolve([]) - await flush() - expect(rpc.subscribe).toHaveBeenCalledTimes(2) - expect(settled).not.toHaveBeenCalled() - rpc.subscribe.mock.calls.at(-1)![3].onClose() - await action -}) - -it('keeps default-agent discovery on the captured workspace copy while another copy is selected', async () => { - const worktreeId = 'captured-workspace' - const target = { kind: 'git-worktree', worktreeId } as const - rpc.call.mockResolvedValue({ - agents: [ - { agent: 'claude', capabilities: {} }, - { agent: 'codex', capabilities: {} } - ] - }) - useAppStore.setState({ - repos: [TEST_REPO], - worktreesByRepo: { - [TEST_REPO.id]: [ - makeWorktree({ id: worktreeId, repoId: TEST_REPO.id, hostId: 'runtime:A' }), - makeWorktree({ id: worktreeId, repoId: TEST_REPO.id, hostId: 'runtime:B' }) - ] - }, - activeWorktreeId: worktreeId, - activeWorkspaceExecutionHostId: 'runtime:A', - runtimeStatusByEnvironmentId: new Map([ - ['A', status('a')], - ['B', status('b')] - ]), - runtimeDetectedAgentIds: { - [getRuntimeAgentInventoryKey('A', worktreeId)]: ['claude'], - [getRuntimeAgentInventoryKey('B', worktreeId)]: ['codex'] - }, - settings: { ...getDefaultSettings('/tmp'), agentDefaultSurface: 'chat' } - }) - const getState = () => - agentTabLaunchStore(useAppStore.getState(), { - worktreeId, - workspaceExecutionHostId: 'runtime:A' - }) - const detected = Promise.withResolvers<['claude']>() - const action = acquireAgentLaunchChoices( - target, - () => detected.promise, - undefined, - false, - getState - ) - await flush() - rpc.subscribe.mock.calls.at(-1)![3].onEvent(frame('claude', 'available')) - useAppStore.setState({ activeWorkspaceExecutionHostId: 'runtime:B' }) - detected.resolve(['claude']) - const choices = await action - expect(choices).toEqual({ detected: ['claude'], offered: ['claude'] }) - expect( - resolveDefaultAgentForWorkspace({ - defaultTuiAgent: null, - detectedAgentIds: choices.detected, - disabledTuiAgents: [], - chatIn: { store: getState(), workspace: target } - }) - ).toBe('claude') -}) diff --git a/src/renderer/src/lib/new-workspace.test.ts b/src/renderer/src/lib/new-workspace.test.ts deleted file mode 100644 index d6447d19024..00000000000 --- a/src/renderer/src/lib/new-workspace.test.ts +++ /dev/null @@ -1,324 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { - mockInspectRuntimeTerminalProcess, - mockPasteDraftToAgentPtyWhenReady, - mockShowAutomationPromptNotSentToast, - mockTrack, - store, - storeListeners, - startupLeafId -} = vi.hoisted(() => ({ - mockInspectRuntimeTerminalProcess: vi.fn(), - mockPasteDraftToAgentPtyWhenReady: vi.fn(), - mockShowAutomationPromptNotSentToast: vi.fn(), - mockTrack: vi.fn(), - storeListeners: new Set<(state: unknown, previousState: unknown) => void>(), - startupLeafId: '11111111-1111-4111-8111-111111111111', - store: { - settings: {}, - activeTabIdByWorktree: { 'wt-1': 'tab-1' } as Record, - tabsByWorktree: { 'wt-1': [{ id: 'tab-1' }] } as Record, - ptyIdsByTabId: { 'tab-1': ['pty-1'] } as Record, - pendingStartupByTabId: {} as Record, - terminalLayoutsByTabId: { - 'tab-1': { - root: null, - activeLeafId: null, - expandedLeafId: null, - ptyIdsByLeafId: { '11111111-1111-4111-8111-111111111111': 'pty-1' } - } - } as Record< - string, - { - root: null - activeLeafId: null - expandedLeafId: null - ptyIdsByLeafId?: Record - } - >, - agentLaunchConfigByPaneKey: { - 'tab-1:11111111-1111-4111-8111-111111111111': { - launchConfig: { agentCommand: 'codex', agentArgs: '', agentEnv: {} }, - registeredAt: 1, - identity: { - tabId: 'tab-1', - leafId: '11111111-1111-4111-8111-111111111111', - launchToken: 'launch-token-1' - } - } - } as Record< - string, - { - launchConfig: { agentCommand: string; agentArgs: string; agentEnv: Record } - registeredAt: number - identity: { tabId?: string; leafId?: string; launchToken?: string } - } - > - } -})) - -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => store, - subscribe: (listener: (state: unknown, previousState: unknown) => void) => { - storeListeners.add(listener) - return () => { - storeListeners.delete(listener) - } - } - } -})) - -vi.mock('@/runtime/hosted-terminals/inspection/runtime-terminal-process-inspection', () => ({ - inspectRuntimeTerminalProcess: mockInspectRuntimeTerminalProcess -})) - -vi.mock('@/lib/agent-session/messaging/paste/agent-paste-draft', () => ({ - pasteDraftToAgentPtyWhenReady: mockPasteDraftToAgentPtyWhenReady -})) - -const mockLaunchUuid = vi.hoisted(() => () => 'launch-token-1') -vi.mock('../../../shared/non-secure-context-uuid', () => ({ - createNonSecureContextUuid: mockLaunchUuid -})) - -vi.mock('@/lib/telemetry', () => ({ - track: mockTrack -})) - -vi.mock('@/lib/agent-session/launch/background/agent-background-session-timeout-toast', () => ({ - showAutomationPromptNotSentToast: mockShowAutomationPromptNotSentToast -})) - -import { ensureAgentStartupInTerminal } from './new-workspace' -import { resetAgentStartupDelayedDeliveryForTests } from './agent-session/launch/startup/agent-startup-delayed-delivery' - -describe('ensureAgentStartupInTerminal prompt delivery', () => { - beforeEach(() => { - vi.useRealTimers() - vi.clearAllMocks() - storeListeners.clear() - store.settings = {} - store.activeTabIdByWorktree = { 'wt-1': 'tab-1' } - store.tabsByWorktree = { 'wt-1': [{ id: 'tab-1' }] } - store.ptyIdsByTabId = { 'tab-1': ['pty-1'] } - store.pendingStartupByTabId = {} - store.terminalLayoutsByTabId = { - 'tab-1': { - root: null, - activeLeafId: null, - expandedLeafId: null, - ptyIdsByLeafId: { [startupLeafId]: 'pty-1' } - } - } - store.agentLaunchConfigByPaneKey = { - [`tab-1:${startupLeafId}`]: { - launchConfig: { agentCommand: 'codex', agentArgs: '', agentEnv: {} }, - registeredAt: 1, - identity: { tabId: 'tab-1', leafId: startupLeafId, launchToken: 'launch-token-1' } - } - } - mockInspectRuntimeTerminalProcess.mockResolvedValue({ - foregroundProcess: 'aider', - hasChildProcesses: true - }) - mockPasteDraftToAgentPtyWhenReady.mockResolvedValue(true) - }) - - afterEach(() => { - vi.useRealTimers() - resetAgentStartupDelayedDeliveryForTests() - }) - - it('keeps waiting when a non-startup split PTY appears before the startup PTY', async () => { - vi.useFakeTimers() - store.ptyIdsByTabId = {} - store.terminalLayoutsByTabId = {} - store.agentLaunchConfigByPaneKey = {} - store.pendingStartupByTabId = { 'tab-1': { launchToken: 'launch-token-1' } } - - const delivery = ensureAgentStartupInTerminal({ - worktreeId: 'wt-1', - primaryTabId: 'tab-1', - startup: { - agent: 'codex', - launchCommand: 'codex', - expectedProcess: 'codex', - followupPrompt: null, - launchConfig: { agentArgs: '', agentEnv: {} }, - draftPrompt: 'linked draft' - } - }) - - await vi.advanceTimersByTimeAsync(5_000) - await delivery - - const splitLeafId = '22222222-2222-4222-8222-222222222222' - store.ptyIdsByTabId = { 'tab-1': ['split-pty'] } - store.terminalLayoutsByTabId = { - 'tab-1': { - root: null, - activeLeafId: null, - expandedLeafId: null, - ptyIdsByLeafId: { [splitLeafId]: 'split-pty' } - } - } - store.agentLaunchConfigByPaneKey = { - [`tab-1:${splitLeafId}`]: { - launchConfig: { agentCommand: 'codex', agentArgs: '', agentEnv: {} }, - registeredAt: 1, - identity: { tabId: 'tab-1', leafId: splitLeafId, launchToken: 'other-token' } - } - } - for (const listener of storeListeners) { - listener(store, store) - } - - expect(mockPasteDraftToAgentPtyWhenReady).not.toHaveBeenCalled() - - store.ptyIdsByTabId = { 'tab-1': ['split-pty', 'startup-pty'] } - store.terminalLayoutsByTabId = { - 'tab-1': { - root: null, - activeLeafId: null, - expandedLeafId: null, - ptyIdsByLeafId: { [splitLeafId]: 'split-pty', [startupLeafId]: 'startup-pty' } - } - } - store.agentLaunchConfigByPaneKey = { - [`tab-1:${splitLeafId}`]: { - launchConfig: { agentCommand: 'codex', agentArgs: '', agentEnv: {} }, - registeredAt: 1, - identity: { tabId: 'tab-1', leafId: splitLeafId, launchToken: 'other-token' } - }, - [`tab-1:${startupLeafId}`]: { - launchConfig: { agentCommand: 'codex', agentArgs: '', agentEnv: {} }, - registeredAt: 2, - identity: { tabId: 'tab-1', leafId: startupLeafId, launchToken: 'launch-token-1' } - } - } - for (const listener of storeListeners) { - listener(store, store) - } - - expect(mockPasteDraftToAgentPtyWhenReady).toHaveBeenCalledTimes(1) - expect(mockPasteDraftToAgentPtyWhenReady).toHaveBeenCalledWith({ - ptyId: 'startup-pty', - content: 'linked draft', - agent: 'codex', - forcePaste: true, - onTimeout: expect.any(Function) - }) - }) - - it('keeps one delayed subscription and tears it down after delivery drains', async () => { - vi.useFakeTimers() - store.ptyIdsByTabId = {} - store.terminalLayoutsByTabId = {} - store.agentLaunchConfigByPaneKey = {} - store.pendingStartupByTabId = { 'tab-1': { launchToken: 'launch-token-1' } } - const startup = { - agent: 'codex' as const, - launchCommand: 'codex', - expectedProcess: 'codex', - followupPrompt: null, - launchConfig: { agentArgs: '', agentEnv: {} }, - draftPrompt: 'linked draft', - launchToken: 'launch-token-1' - } - - const first = ensureAgentStartupInTerminal({ - worktreeId: 'wt-1', - primaryTabId: 'tab-1', - startup - }) - const second = ensureAgentStartupInTerminal({ - worktreeId: 'wt-1', - primaryTabId: 'tab-1', - startup - }) - - await vi.advanceTimersByTimeAsync(5_000) - await Promise.all([first, second]) - - expect(storeListeners.size).toBe(1) - - store.ptyIdsByTabId = { 'tab-1': ['pty-delayed'] } - store.pendingStartupByTabId = {} - store.terminalLayoutsByTabId = { - 'tab-1': { - root: null, - activeLeafId: null, - expandedLeafId: null, - ptyIdsByLeafId: { [startupLeafId]: 'pty-delayed' } - } - } - store.agentLaunchConfigByPaneKey = { - [`tab-1:${startupLeafId}`]: { - launchConfig: { agentCommand: 'codex', agentArgs: '', agentEnv: {} }, - registeredAt: 1, - identity: { tabId: 'tab-1', leafId: startupLeafId, launchToken: 'launch-token-1' } - } - } - for (const listener of storeListeners) { - listener(store, store) - } - - expect(mockPasteDraftToAgentPtyWhenReady).toHaveBeenCalledTimes(1) - expect(storeListeners.size).toBe(0) - }) - - it('does not let a newer same-tab launch satisfy an older pending delivery', async () => { - vi.useFakeTimers() - store.ptyIdsByTabId = {} - store.terminalLayoutsByTabId = {} - store.agentLaunchConfigByPaneKey = {} - store.pendingStartupByTabId = { 'tab-1': { launchToken: 'launch-token-old' } } - - const delivery = ensureAgentStartupInTerminal({ - worktreeId: 'wt-1', - primaryTabId: 'tab-1', - startup: { - agent: 'codex', - launchCommand: 'codex', - expectedProcess: 'codex', - followupPrompt: null, - launchConfig: { agentArgs: '', agentEnv: {} }, - draftPrompt: 'old linked draft', - launchToken: 'launch-token-old' - } - }) - - await vi.advanceTimersByTimeAsync(5_000) - await delivery - - store.pendingStartupByTabId = { 'tab-1': { launchToken: 'launch-token-new' } } - for (const listener of storeListeners) { - listener(store, store) - } - - store.ptyIdsByTabId = { 'tab-1': ['pty-new'] } - store.pendingStartupByTabId = {} - store.terminalLayoutsByTabId = { - 'tab-1': { - root: null, - activeLeafId: null, - expandedLeafId: null, - ptyIdsByLeafId: { [startupLeafId]: 'pty-new' } - } - } - store.agentLaunchConfigByPaneKey = { - [`tab-1:${startupLeafId}`]: { - launchConfig: { agentCommand: 'codex', agentArgs: '', agentEnv: {} }, - registeredAt: 1, - identity: { tabId: 'tab-1', leafId: startupLeafId, launchToken: 'launch-token-old' } - } - } - for (const listener of storeListeners) { - listener(store, store) - } - - expect(mockPasteDraftToAgentPtyWhenReady).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/lib/non-secure-context-crypto.repro.test.ts b/src/renderer/src/lib/non-secure-context-crypto.repro.test.ts deleted file mode 100644 index 51288b50c62..00000000000 --- a/src/renderer/src/lib/non-secure-context-crypto.repro.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -/** Exercise real call sites with plain-HTTP crypto shape: LAN clients lack randomUUID/subtle. */ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { createNonSecureContextCrypto } from './non-secure-context-crypto-stub' - -const realCrypto = globalThis.crypto - -beforeEach(() => { - Object.defineProperty(globalThis, 'crypto', { - configurable: true, - value: createNonSecureContextCrypto(realCrypto) - }) -}) - -afterEach(() => { - Object.defineProperty(globalThis, 'crypto', { configurable: true, value: realCrypto }) -}) - -describe('non-secure context (plain HTTP LAN web client)', () => { - // Fallback hashes must match secure-context hashes or previously approved hook trust would mismatch. - it('produces the same hash as crypto.subtle did in a secure context', async () => { - const { hashOrcaHookScript } = await import('./orca-hook-trust') - const secureHash = await (async () => { - Object.defineProperty(globalThis, 'crypto', { configurable: true, value: realCrypto }) - return hashOrcaHookScript('echo hi') - })() - Object.defineProperty(globalThis, 'crypto', { - configurable: true, - value: createNonSecureContextCrypto(realCrypto) - }) - expect(await hashOrcaHookScript('echo hi')).toBe(secureHash) - }) -}) diff --git a/src/renderer/src/lib/onboarding-folder-cancellation.test.ts b/src/renderer/src/lib/onboarding-folder-cancellation.test.ts deleted file mode 100644 index 238f1f30391..00000000000 --- a/src/renderer/src/lib/onboarding-folder-cancellation.test.ts +++ /dev/null @@ -1,227 +0,0 @@ -import type * as RuntimeCapabilityProofModule from '@/runtime/rpc/compatibility/runtime-capability-proof' -import type * as RuntimeRpcCallModule from '@/runtime/rpc/calls/runtime-rpc-call' - -import type * as Telemetry from '@/lib/telemetry' -import { afterEach, beforeAll, expect, it, vi } from 'vitest' -import { toast } from 'sonner' -import { useAppStore } from '@/store' -import { createTestStore } from '@/store/testing/app-store-test-fixture' -import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' -import { makeDetectedResult } from '@/store/slices/worktrees/listing/worktrees-detected-listing-fixtures' -import { getDefaultSettings } from '../../../shared/constants' -import { getDefaultOnboardingState } from '../../../shared/onboarding-defaults' -import type { PublicKnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { projectAgentLaunchSettings } from '../../../shared/agent-launch/choices/agent-launch-settings' -import { clearHostAgentMenuSettingsForTests } from '@/runtime/agent-launch-settings/host-agent-launch-preferences-resource' -import { stubRuntimeEnvironmentBridge } from '@/runtime/rpc/testing/runtime-environment-bridge-fixture' -import { rememberEmptyHostAnswerForTests } from '@/runtime/web-session-tabs-sync/host-terminal-count-fixture' -import { loadWebRuntimeSessionTabsApplyModulesForTests } from '@/runtime/web-session-tabs-sync/inventory/web-runtime-session-snapshot' -import { resetWebSessionTabsSnapshotFreshnessForTests } from '@/runtime/web-session-tabs-sync/tracking-lifecycle' -import { - shouldSkipWebRuntimeWakeTerminalRespawn, - resetWebRuntimeWakeTerminalRespawnForTests -} from '@/runtime/hosted-terminals/restoration/web-runtime-wake-terminal-respawn' - -const rpc = vi.hoisted(() => vi.fn()) -vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', async (importOriginal) => ({ - ...(await importOriginal()), - runtimeEnvironmentSupportsCapability: vi.fn(async () => true) -})) -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => ({ - ...(await importOriginal()), - callRuntimeRpc: rpc -})) -vi.mock('sonner', () => ({ - toast: { error: vi.fn(), success: vi.fn(), info: vi.fn(), dismiss: vi.fn() } -})) -vi.mock('@/lib/telemetry', async (importOriginal) => ({ - ...(await importOriginal()), - track: vi.fn() -})) - -beforeAll(async () => { - await loadWebRuntimeSessionTabsApplyModulesForTests() - await import('./onboarding-folder-agent-launch') -}) -afterEach(() => { - clearHostAgentMenuSettingsForTests() - resetWebSessionTabsSnapshotFreshnessForTests() - resetWebRuntimeWakeTerminalRespawnForTests() - vi.restoreAllMocks() - vi.unstubAllGlobals() - vi.useRealTimers() -}) - -function environment(revision: number): PublicKnownRuntimeEnvironment { - return { - id: 'box', - name: 'Box', - createdAt: 1, - updatedAt: revision, - pairingRevision: revision, - lastUsedAt: null, - runtimeId: 'box-runtime', - endpoints: [], - preferredEndpointId: 'endpoint', - hostKeyFingerprint: 'same-host' - } -} - -it.each(['same-host', 'purged'] as const)( - 'keeps the committed folder after optional cancellation and reveals only its %s owner', - async (mode) => { - vi.clearAllMocks() - vi.useFakeTimers() - const store = createTestStore() - vi.spyOn(useAppStore, 'getState').mockImplementation(store.getState) - vi.spyOn(useAppStore, 'setState').mockImplementation(store.setState) - store.setState({ - settings: { - ...getDefaultSettings('/tmp/workspaces'), - defaultTuiAgent: 'claude', - agentDefaultArgs: { claude: '--model old-seed' }, - activeRuntimeEnvironmentId: 'box' - } - }) - store.getState().setRuntimeEnvironments([environment(1)]) - store.setState({ - runtimeStatusByEnvironmentId: new Map([ - [ - 'box', - { - checkedAt: 1, - status: { - runtimeId: 'box-runtime', - rendererGraphEpoch: 0, - graphStatus: 'ready', - authoritativeWindowId: null, - liveTabCount: 0, - liveLeafCount: 0, - hostPlatform: 'linux', - capabilities: [] - } - } - ] - ]) - }) - const folder = makeWorktree({ - id: 'folder-repo::/folder', - repoId: 'folder-repo', - path: '/folder' - }) - const pending = Promise.withResolvers<{ - settings: ReturnType - }>() - rpc.mockImplementation(async (_target, method) => { - if (method === 'repo.add') { - return { - repo: { - id: 'folder-repo', - path: '/folder', - displayName: 'Folder', - badgeColor: '', - addedAt: 1, - kind: 'folder' - } - } - } - if (method === 'worktree.detectedList') { - return makeDetectedResult('folder-repo', [folder]) - } - if (method === 'github.prForBranch') { - return null - } - if (method === 'worktree.lineageList') { - return { lineage: {} } - } - if (method === 'settings.getAgentLaunch') { - return pending.promise - } - throw new Error(`Unexpected RPC ${method}`) - }) - const dispatch = vi.fn( - async (request: { - method: string - expectedEnvironmentPairingRevision?: number - params?: unknown - }) => { - if (request.method === 'session.tabs.createTerminal') { - return { ok: true, result: { tab: { id: 'plain-tab', leafId: 'leaf' } } } - } - if (request.method === 'session.tabs.list') { - return { - ok: true, - result: { - worktree: folder.id, - publicationEpoch: 'epoch', - snapshotVersion: 1, - activeGroupId: null, - activeTabId: null, - activeTabType: null, - tabs: [] - } - } - } - if (request.method === 'worktree.activate') { - return { ok: true, result: {} } - } - throw new Error(`Unexpected dispatch ${request.method}`) - } - ) - stubRuntimeEnvironmentBridge({ call: dispatch }) - Object.assign(window.api, { - onboarding: { - get: vi.fn(async () => ({ ...getDefaultOnboardingState(), outcome: 'dismissed' })), - update: vi.fn(async () => undefined) - } - }) - const adding = store.getState().addNonGitFolder('/folder', { runtimeEnvironmentId: 'box' }) - await vi.advanceTimersByTimeAsync(0) - await vi.waitFor(() => - expect( - rpc.mock.calls.filter(([, method]) => method === 'settings.getAgentLaunch') - ).toHaveLength(1) - ) - expect(store.getState().getKnownWorktreeById(folder.id)).toBeDefined() - expect(dispatch).not.toHaveBeenCalled() - store.getState().setRuntimeEnvironments(mode === 'same-host' ? [environment(2)] : []) - if (mode === 'same-host') { - rememberEmptyHostAnswerForTests('box', folder.id) - } - await vi.advanceTimersByTimeAsync(0) - await expect(adding).resolves.toMatchObject({ - id: 'folder-repo', - executionHostId: 'runtime:box' - }) - await vi.advanceTimersByTimeAsync(0) - const creates = () => - dispatch.mock.calls.filter(([request]) => request.method === 'session.tabs.createTerminal') - if (mode === 'same-host') { - expect(store.getState().activeWorktreeId).toBe(folder.id) - expect(creates()).toHaveLength(1) - expect(creates()[0][0]).toMatchObject({ expectedEnvironmentPairingRevision: 2 }) - expect(creates()[0][0].params).toMatchObject({ command: undefined }) - expect(creates()[0][0].params).not.toHaveProperty('launchAgent') - expect( - dispatch.mock.calls.find(([request]) => request.method === 'worktree.activate')?.[0] - ).toMatchObject({ expectedEnvironmentPairingRevision: 2 }) - } else { - expect(store.getState().getKnownWorktreeById(folder.id)).toBeUndefined() - expect(store.getState().repos).toEqual([]) - expect(dispatch).not.toHaveBeenCalled() - } - expect(shouldSkipWebRuntimeWakeTerminalRespawn(folder.id)).toBe(false) - pending.resolve({ - settings: projectAgentLaunchSettings({ - agentLaunchChoices: { claude: { model: 'late-seed' } } - }) - }) - await vi.advanceTimersByTimeAsync(10_000) - expect(creates()).toHaveLength(mode === 'same-host' ? 1 : 0) - expect( - dispatch.mock.calls.some(([request]) => request.method === 'terminal.createAgentSession') - ).toBe(false) - expect(store.getState().tabsByWorktree[folder.id] ?? []).toEqual([]) - expect(toast.error).not.toHaveBeenCalled() - } -) diff --git a/src/renderer/src/lib/orca-yaml-trust-prompt-slot-eviction.test.ts b/src/renderer/src/lib/orca-yaml-trust-prompt-slot-eviction.test.ts deleted file mode 100644 index d98b472fcd5..00000000000 --- a/src/renderer/src/lib/orca-yaml-trust-prompt-slot-eviction.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { StoreApi } from 'zustand/vanilla' -import type { AppState } from '@/store/types' -import { createUIStore } from '@/store/slices/ui/ui-slice-test-harness' -import { __resetTrustPromptChainForTests, ensureHooksConfirmed } from './ensure-hooks-confirmed' -import { createCompatibleRuntimeStatusResponseIfNeeded } from '@/runtime/rpc/testing/runtime-compatibility-test-fixture' -import type { RuntimeEnvironmentCallRequest } from '@/runtime/rpc/testing/runtime-compatibility-test-fixture' -import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '@/runtime/rpc/compatibility/runtime-compatibility-cache' - -const hooksCheckMock = vi.fn() -const readIssueCommandMock = vi.fn() -const runtimeEnvironmentTransportCallMock = vi.fn() - -// Why: a hand-rolled openModal double would decide the eviction outcome under test. -function createStateBackedByRealModalSlot(): { - store: StoreApi - state: AppState -} { - const store = createUIStore() - store.setState({ - repos: [{ id: 'repo-1', displayName: 'Repo One' }], - trustedOrcaHooks: {} - } as unknown as Partial) - return { store, state: store.getState() } -} - -async function settleOrReport(promise: Promise): Promise { - return Promise.race([ - promise, - new Promise<'never-settled'>((resolve) => setTimeout(() => resolve('never-settled'), 100)) - ]) -} - -describe('orca.yaml trust prompt evicted from the modal slot', () => { - beforeEach(() => { - hooksCheckMock.mockReset() - readIssueCommandMock.mockReset() - runtimeEnvironmentTransportCallMock.mockReset() - runtimeEnvironmentTransportCallMock.mockImplementation((args: RuntimeEnvironmentCallRequest) => - createCompatibleRuntimeStatusResponseIfNeeded(args) - ) - clearRuntimeCompatibilityCacheForTests() - vi.stubGlobal('window', { - api: { - hooks: { check: hooksCheckMock, readIssueCommand: readIssueCommandMock }, - runtimeEnvironments: { call: runtimeEnvironmentTransportCallMock } - } - }) - __resetTrustPromptChainForTests() - hooksCheckMock.mockResolvedValue({ - hasHooks: true, - hooks: { scripts: { setup: 'pnpm install' } }, - mayNeedUpdate: false - }) - }) - - it('resolves the pending decision as skip when another modal takes the slot', async () => { - const { store, state } = createStateBackedByRealModalSlot() - const runSetup = vi.fn() - - const decision = ensureHooksConfirmed(state, 'repo-1', 'setup') - await vi.waitFor(() => expect(store.getState().activeModal).toBe('confirm-orca-yaml-hooks')) - - store.getState().openModal('worktree-palette') - - const result = await settleOrReport(decision) - if (result === 'run') { - runSetup() - } - - expect(result).toBe('skip') - expect(runSetup).not.toHaveBeenCalled() - expect(store.getState().trustedOrcaHooks).toEqual({}) - }) -}) diff --git a/src/renderer/src/lib/run-target-host-visibility.ts b/src/renderer/src/lib/run-target-host-visibility.ts index bfb2032a616..a022c851913 100644 --- a/src/renderer/src/lib/run-target-host-visibility.ts +++ b/src/renderer/src/lib/run-target-host-visibility.ts @@ -1,6 +1,6 @@ import type { ExecutionHostId } from '../../../shared/execution-host' import type { ExecutionHostRegistryEntry } from '../../../shared/execution-host/execution-host-registry-entry' -import { isEphemeralVmProjectHost } from './project-host-setup-options' +import { isEphemeralVmProjectHost } from './workspace/creation/project-host-setup-options' /** Run on never lists per-workspace VMs, so Create waits for a visible host; a VM recipe creates a new VM instead. */ export function needsVisibleRunTargetHost( diff --git a/src/renderer/src/lib/sleeping-agent-session-launch-windows-quoting.test.ts b/src/renderer/src/lib/sleeping-agent-session-launch-windows-quoting.test.ts deleted file mode 100644 index 5b12d22954a..00000000000 --- a/src/renderer/src/lib/sleeping-agent-session-launch-windows-quoting.test.ts +++ /dev/null @@ -1,228 +0,0 @@ -// Resume lines enter the selected Windows shell; cmd.exe must never receive PowerShell single quoting (#12320). - -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' -import type * as ConnectionOwnerResolution from '@/lib/workspace/ownership/connection-owner-resolution' -import type * as LaunchAgentKindModule from '../../../shared/agent-kind' - -const mockCreateTab = vi.fn() - -type TestRepo = { id: string; connectionId: string | null; executionHostId?: string; path: string } -const INITIAL_REPOS: TestRepo[] = [ - { id: 'repo-1', connectionId: null, path: 'C:\\Users\\neil\\repo' } -] - -const store = { - agentStatusByPaneKey: {}, - settings: { - agentCmdOverrides: {}, - agentDefaultArgs: {} as Record, - agentDefaultEnv: {} as Record>, - activeRuntimeEnvironmentId: null as string | null - } as { - agentCmdOverrides: Record - agentDefaultArgs: Record - agentDefaultEnv: Record> - activeRuntimeEnvironmentId: string | null - terminalWindowsShell?: string - }, - repos: INITIAL_REPOS, - worktreesByRepo: { - 'repo-1': [ - { - id: 'wt-1', - repoId: 'repo-1', - path: 'C:\\Users\\neil\\repo\\feature', - displayName: 'feature' - } - ] - } as Record, - getKnownWorktreeById: (id: string) => - Object.values(store.worktreesByRepo) - .flat() - .find((worktree) => worktree.id === id), - sshConnectionStates: new Map(), - sshStateByEnvironment: new Map(), - runtimeStatusByEnvironmentId: new Map(), - tabsByWorktree: { 'wt-1': [{ id: 'tab-1' }] }, - unifiedTabsByWorktree: {}, - openFiles: [] as { id: string; worktreeId: string }[], - browserTabsByWorktree: {} as Record, - tabBarOrderByWorktree: {} as Record, - createTab: mockCreateTab, - claimAutomaticAgentResume: vi.fn(), - clearSleepingAgentSession: vi.fn(), - setActiveTabType: vi.fn(), - setTabBarOrder: vi.fn() -} - -vi.mock('@/store', () => ({ useAppStore: { getState: () => store } })) -const connectionOwner = vi.hoisted((): { nestedConnectionId: string | undefined } => ({ - nestedConnectionId: undefined -})) -vi.mock('@/lib/workspace/ownership/connection-owner-resolution', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - getConnectionIdFromState: (...args: Parameters) => - connectionOwner.nestedConnectionId ?? actual.getConnectionIdFromState(...args) - } -}) -vi.mock('@/lib/new-workspace', () => ({ CLIENT_PLATFORM: 'win32' })) -vi.mock('sonner', () => ({ toast: { message: vi.fn(), error: vi.fn() } })) -vi.mock('@/lib/telemetry', () => ({ - track: vi.fn(), - tuiAgentToAgentKind: mockLaunchAgentKind -})) -const mockLaunchAgentKind = vi.hoisted(() => (agent: string) => agent) -vi.mock('../../../shared/agent-kind', async (importOriginal) => ({ - ...(await importOriginal()), - tuiAgentToAgentKind: mockLaunchAgentKind -})) - -vi.mock('@/components/tab-bar/reconcile-order', () => ({ - reconcileTabOrder: vi.fn((_stored, termIds: string[]) => [...termIds]) -})) - -const SESSION_ID = '0199f7a1-0000-7000-8000-000000000001' - -const record: SleepingAgentSessionRecord = { - paneKey: 'tab-1::leaf-1', - tabId: 'tab-1', - worktreeId: 'wt-1', - agent: 'codex', - providerSession: { key: 'session_id', id: SESSION_ID }, - prompt: 'finish the task', - state: 'done', - origin: 'worktree-sleep', - capturedAt: 1, - updatedAt: 1 -} - -async function launch(sessionRecord = record): Promise { - const { launchSleepingAgentSession } = - await import('./agent-session/resume/sleeping-agent-session-launch') - launchSleepingAgentSession(sessionRecord) - const options = mockCreateTab.mock.calls.at(-1)?.[3] as - | { pendingStartup?: { command: string } } - | undefined - return options?.pendingStartup?.command -} - -describe('launchSleepingAgentSession Windows shell quoting', () => { - beforeEach(() => { - vi.clearAllMocks() - store.settings = { - agentCmdOverrides: {}, - agentDefaultArgs: {}, - agentDefaultEnv: {}, - activeRuntimeEnvironmentId: null - } - store.repos = [{ id: 'repo-1', connectionId: null, path: 'C:\\Users\\neil\\repo' }] - store.sshConnectionStates = new Map() - store.worktreesByRepo = { - 'repo-1': [ - { - id: 'wt-1', - repoId: 'repo-1', - path: 'C:\\Users\\neil\\repo\\feature', - displayName: 'feature' - } - ] - } - store.runtimeStatusByEnvironmentId = new Map() - connectionOwner.nestedConnectionId = undefined - mockCreateTab.mockReturnValue({ id: 'tab-1' }) - }) - - // Why: a folder or nested-SSH workspace on a server runs on its SSH target, so the server's OS must not quote it. - it('quotes a nested SSH workspace on a Windows server for its SSH target', async () => { - store.repos = [ - { - id: 'repo-1', - connectionId: null, - executionHostId: 'runtime:env-1', - path: '/home/neil/repo' - } - ] - store.worktreesByRepo = { - 'repo-1': [{ id: 'wt-1', repoId: 'repo-1', path: '/home/neil/repo', displayName: 'feature' }] - } - store.runtimeStatusByEnvironmentId = new Map([['env-1', { status: { hostPlatform: 'win32' } }]]) - connectionOwner.nestedConnectionId = 'ssh-nested' - - await expect( - launch({ ...record, providerSession: { key: 'session_id', id: "s'1" } }) - ).resolves.toContain(`'resume' 's'"'"'1'`) - }) - - it('quotes the resume argv for a cmd.exe tab', async () => { - store.settings.terminalWindowsShell = 'cmd.exe' - - await expect(launch()).resolves.toBe(`codex "resume" "${SESSION_ID}"`) - }) - - it('ignores the local Windows shell setting for an SSH workspace', async () => { - store.settings.terminalWindowsShell = 'cmd.exe' - store.repos = [{ id: 'repo-1', connectionId: 'ssh-1', path: '/home/neil/repo' }] - store.worktreesByRepo = { - 'repo-1': [ - { - id: 'wt-1', - repoId: 'repo-1', - path: '/home/neil/repo/feature', - displayName: 'feature' - } - ] - } - - await expect(launch()).resolves.toBe(`codex 'resume' '${SESSION_ID}'`) - }) - it.each([ - ['cmd.exe', 'omp "--resume" "C:\\custom sessions\\session.jsonl"'], - ['powershell.exe', "omp '--resume' 'C:\\custom sessions\\session.jsonl'"] - ])('keeps a hook-only OMP locator when waking into %s', async (shell, expected) => { - store.settings.terminalWindowsShell = shell - const omp: SleepingAgentSessionRecord = { - ...record, - agent: 'omp', - providerSession: { - key: 'session_id', - id: SESSION_ID, - transcriptPath: 'C:\\custom sessions\\session.jsonl' - } - } - await expect(launch(omp)).resolves.toBe(expected) - }) - it('quotes for PowerShell on an SSH host that reported Windows', async () => { - store.settings.terminalWindowsShell = 'cmd.exe' - store.repos = [{ id: 'repo-1', connectionId: 'ssh-1', path: 'C:\\repo' }] - store.sshConnectionStates = new Map([['ssh-1', { remotePlatform: 'win32' }]]) - const omp: SleepingAgentSessionRecord = { - ...record, - agent: 'omp', - providerSession: { - key: 'session_id', - id: SESSION_ID, - transcriptPath: "C:\\neil's sessions\\session.jsonl" - } - } - await expect(launch(omp)).resolves.toBe("omp '--resume' 'C:\\neil''s sessions\\session.jsonl'") - }) - it('keeps the remote OMP path instead of using the local Windows shell or UUID', async () => { - store.settings.terminalWindowsShell = 'cmd.exe' - store.repos = [{ id: 'repo-1', connectionId: 'ssh-1', path: '/repo' }] - const omp: SleepingAgentSessionRecord = { - ...record, - agent: 'omp', - providerSession: { - key: 'session_id', - id: SESSION_ID, - transcriptPath: '/remote/custom sessions/session.jsonl' - } - } - await expect(launch(omp)).resolves.toBe( - "omp '--resume' '/remote/custom sessions/session.jsonl'" - ) - }) -}) diff --git a/src/renderer/src/lib/source-control/ai/source-control-agent-action-launch-check.ts b/src/renderer/src/lib/source-control/ai/source-control-agent-action-launch-check.ts index b9bf1879c6c..201f6776578 100644 --- a/src/renderer/src/lib/source-control/ai/source-control-agent-action-launch-check.ts +++ b/src/renderer/src/lib/source-control/ai/source-control-agent-action-launch-check.ts @@ -1,6 +1,6 @@ import { buildAgentStartupPlan } from '../../../../../shared/agent-launch/startup/tui-agent-startup' import { planAgentCliArgsSuffix } from '../../../../../shared/agent-launch/startup/tui-agent-startup-shell' -import { CLIENT_PLATFORM } from '@/lib/new-workspace' +import { CLIENT_PLATFORM } from '@/lib/workspace/creation/new-workspace' import { isTuiAgentEnabled } from '../../../../../shared/agent-launch/catalog/tui-agent-selection' import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent' import { translate } from '@/i18n/i18n' diff --git a/src/renderer/src/lib/source-control/ai/source-control-agent-picker.ts b/src/renderer/src/lib/source-control/ai/source-control-agent-picker.ts index 83e783df930..da1befa35de 100644 --- a/src/renderer/src/lib/source-control/ai/source-control-agent-picker.ts +++ b/src/renderer/src/lib/source-control/ai/source-control-agent-picker.ts @@ -1,7 +1,7 @@ import type { AppState } from '@/store/types' import type { AgentLaunchPreferences } from '@/runtime/agent-launch-settings/host-agent-launch-preferences-resource' import type { ProspectiveWorkspace } from '@/lib/agent-session/launch/routing/agent-launch-route-input' -import { readAgentLaunchChoice } from '@/lib/host-chat-program' +import { readAgentLaunchChoice } from '@/lib/agent-session/launch/inventory/host-chat-program' import { resolveSourceControlActionRecipe } from '../../../../../shared/source-control/ai/source-control-ai-operation-policy' import type { SourceControlActionId, diff --git a/src/renderer/src/lib/source-control/checks/fix-checks-agent-launch.ts b/src/renderer/src/lib/source-control/checks/fix-checks-agent-launch.ts index e2a542bb946..d612a3b5dab 100644 --- a/src/renderer/src/lib/source-control/checks/fix-checks-agent-launch.ts +++ b/src/renderer/src/lib/source-control/checks/fix-checks-agent-launch.ts @@ -9,7 +9,7 @@ import { import { AgentLaunchChoiceCancelled, acquireAgentLaunchChoices -} from '../../host-chat-program-acquisition' +} from '../../agent-session/launch/inventory/host-chat-program-acquisition' import { toast } from 'sonner' import { ensureDetectedAgentsForRepo, diff --git a/src/renderer/src/lib/work-items/github/smart-github-submit.ts b/src/renderer/src/lib/work-items/github/smart-github-submit.ts index 1ea7af8cf96..6a2842cb9c2 100644 --- a/src/renderer/src/lib/work-items/github/smart-github-submit.ts +++ b/src/renderer/src/lib/work-items/github/smart-github-submit.ts @@ -3,7 +3,7 @@ import type { GitPushTarget } from '../../../../../shared/worktree/types' import type { TaskSourceContext } from '../../../../../shared/work-items/task-source-context' import { getTaskSourceCacheScope } from '../../../../../shared/work-items/task-source-context' import { getLinkedWorkItemWorkspaceName } from '../../../../../shared/workspace-name' -import type { LinkedWorkItemSummary } from '../../new-workspace' +import type { LinkedWorkItemSummary } from '../../workspace/creation/new-workspace' import { parseGitHubIssueOrPRLink } from '../../../../../shared/github/links' import { resolveGitHubWorkItemIdentity } from '../../../../../shared/new-workspace/github-work-item-identity' import { githubRepoIdentityKey } from '../../../../../shared/github/repository-identity-key' diff --git a/src/renderer/src/lib/work-items/linear/linear-linked-work-item.ts b/src/renderer/src/lib/work-items/linear/linear-linked-work-item.ts index eea347a7db4..69c656a7fae 100644 --- a/src/renderer/src/lib/work-items/linear/linear-linked-work-item.ts +++ b/src/renderer/src/lib/work-items/linear/linear-linked-work-item.ts @@ -4,7 +4,7 @@ import { } from '../../../../../shared/work-items/task-source-context' import { getLinearIssueWorkspaceName } from '../../../../../shared/workspace-name' import type { LinearIssue } from '../../../../../shared/linear/issue-types' -import type { LinkedWorkItemSummary } from '@/lib/new-workspace' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' import { buildLinearWorkspaceSource, getUsableLinearBranchName diff --git a/src/renderer/src/lib/workspace/activation/initial-surface/empty-workspace-default-agent-chat.ts b/src/renderer/src/lib/workspace/activation/initial-surface/empty-workspace-default-agent-chat.ts index dee4d15b21e..6624984f9e2 100644 --- a/src/renderer/src/lib/workspace/activation/initial-surface/empty-workspace-default-agent-chat.ts +++ b/src/renderer/src/lib/workspace/activation/initial-surface/empty-workspace-default-agent-chat.ts @@ -1,6 +1,6 @@ import { pickTuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent-selection' import { newAgentLaunchesMayOpenChats } from '@/runtime/native-chat/local-sessions/local-structured-chats' -import { acquireAgentLaunchChoices } from '../../../host-chat-program-acquisition' +import { acquireAgentLaunchChoices } from '../../../agent-session/launch/inventory/host-chat-program-acquisition' import { useAppStore } from '@/store/index' import type { AppState } from '@/store/types' import { @@ -14,7 +14,10 @@ import { } from '@/lib/agent-session/launch/inventory/agent-detection-target-inventory' import { workspaceKindForWorktreeId } from '../../../../../../shared/agent-launch/contracts/workspace-launch-kind' import { worktreeLaunchWorkspace } from '@/lib/agent-session/launch/routing/agent-launch-route-input' -import { chosenAgentChatUnlearned, agentChoiceOpensAsChat } from '@/lib/host-chat-program' +import { + chosenAgentChatUnlearned, + agentChoiceOpensAsChat +} from '@/lib/agent-session/launch/inventory/host-chat-program' import { planAgentSessionLaunch } from '@/lib/agent-session/launch/routing/agent-session-launch-plan' import { newAgentLaunchRequestId } from '@/lib/agent-session/launch/routing/agent-launch-request-id' import { launchAgentInNewTab } from '@/lib/agent-session/launch/new-tab/launch-agent-in-new-tab' diff --git a/src/renderer/src/lib/workspace/activation/initial-surface/worktree-initial-terminal-seeding.ts b/src/renderer/src/lib/workspace/activation/initial-surface/worktree-initial-terminal-seeding.ts index 245e10aa90a..c1166b266b8 100644 --- a/src/renderer/src/lib/workspace/activation/initial-surface/worktree-initial-terminal-seeding.ts +++ b/src/renderer/src/lib/workspace/activation/initial-surface/worktree-initial-terminal-seeding.ts @@ -13,7 +13,7 @@ import { createSequencedSetupAgentCommands } from '../../../../../../shared/agen import { getSetupRunnerCommandPlatformForPath } from '../../../../../../shared/agent-launch/startup/setup-runner-command' import { agentKindToTuiAgent } from '../../../../../../shared/agent-kind' import { useAppStore } from '@/store/index' -import { queueHookCommandsForFirstWorktreeTab } from '@/lib/hook-command-delayed-delivery' +import { queueHookCommandsForFirstWorktreeTab } from '@/lib/workspace/creation/setup/hook-command-delayed-delivery' import { resolveWorkspaceTerminalHostAuthority } from '@/lib/workspace/ownership/workspace-terminal-host-authority' import { seedNativeChatAppliedSessionOptions } from '../../../../../../shared/native-chat/input/native-chat-session-option-cache' import type { diff --git a/src/renderer/src/lib/workspace/activation/initial-surface/worktree-setup-issue-command-queue.ts b/src/renderer/src/lib/workspace/activation/initial-surface/worktree-setup-issue-command-queue.ts index de1fae5e3d4..726876577f2 100644 --- a/src/renderer/src/lib/workspace/activation/initial-surface/worktree-setup-issue-command-queue.ts +++ b/src/renderer/src/lib/workspace/activation/initial-surface/worktree-setup-issue-command-queue.ts @@ -1,5 +1,5 @@ import type { WorktreeSetupLaunch } from '../../../../../../shared/worktree/launch-types' -import { buildSetupRunnerCommand } from '../../../setup-runner' +import { buildSetupRunnerCommand } from '../../creation/setup/setup-runner' import { translate } from '@/i18n/i18n' import type { InitialTerminalOptions, diff --git a/src/renderer/src/lib/workspace/activation/sidebar-worktree-activation.ts b/src/renderer/src/lib/workspace/activation/sidebar-worktree-activation.ts index 4315ec17c83..c063ddd5cc4 100644 --- a/src/renderer/src/lib/workspace/activation/sidebar-worktree-activation.ts +++ b/src/renderer/src/lib/workspace/activation/sidebar-worktree-activation.ts @@ -7,7 +7,7 @@ import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import type { ExecutionHostId } from '../../../../../shared/execution-host' import type { EphemeralVmWorkspaceLifecycleResult } from '../../../../../shared/ephemeral-vm-runtimes' -import { ephemeralVmErrorText } from '@/lib/ephemeral-vm-error-copy' +import { ephemeralVmErrorText } from '@/runtime/ephemeral-vm/ephemeral-vm-error-copy' import { ephemeralVmFailureFromError } from '../../../../../shared/ephemeral-vm-failure-copy' /** Coded failures render through the catalog; a thrown IPC error only has its message. */ diff --git a/src/renderer/src/lib/workspace/activation/worktree-activation.test-fixture.ts b/src/renderer/src/lib/workspace/activation/worktree-activation.test-fixture.ts index 5dbb7033b4a..b62759c18a4 100644 --- a/src/renderer/src/lib/workspace/activation/worktree-activation.test-fixture.ts +++ b/src/renderer/src/lib/workspace/activation/worktree-activation.test-fixture.ts @@ -1,7 +1,7 @@ import { afterEach, vi } from 'vitest' import type { Mock } from 'vitest' import { getDefaultSettings } from '../../../../../shared/constants' -import { resetHookCommandDelayedDeliveryForTests } from '../../hook-command-delayed-delivery' +import { resetHookCommandDelayedDeliveryForTests } from '../creation/setup/hook-command-delayed-delivery' import { useAppStore } from '@/store/index' export type AppStoreState = ReturnType diff --git a/src/renderer/src/lib/composer-create-handoff.ts b/src/renderer/src/lib/workspace/creation/composer-create-handoff.ts similarity index 99% rename from src/renderer/src/lib/composer-create-handoff.ts rename to src/renderer/src/lib/workspace/creation/composer-create-handoff.ts index 21aadf72917..efb17231abe 100644 --- a/src/renderer/src/lib/composer-create-handoff.ts +++ b/src/renderer/src/lib/workspace/creation/composer-create-handoff.ts @@ -1,5 +1,5 @@ import { toast } from 'sonner' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { translate } from '@/i18n/i18n' import { findPendingLinkedWorkItemCreationId, diff --git a/src/renderer/src/lib/composer-issue-command.ts b/src/renderer/src/lib/workspace/creation/composer-issue-command.ts similarity index 92% rename from src/renderer/src/lib/composer-issue-command.ts rename to src/renderer/src/lib/workspace/creation/composer-issue-command.ts index 78e85867e88..335dfc7219b 100644 --- a/src/renderer/src/lib/composer-issue-command.ts +++ b/src/renderer/src/lib/workspace/creation/composer-issue-command.ts @@ -2,8 +2,8 @@ import type { WorktreeCreationRequest } from '@/lib/workspace/creation/pending-w import { canUseIssueCommandForLinkedItemProvider, renderIssueCommandTemplate -} from '@/lib/new-workspace' -import type { WorkspaceLinkedItem as FolderWorkspaceLinkedTask } from '../../../shared/worktree/types' +} from '@/lib/workspace/creation/new-workspace' +import type { WorkspaceLinkedItem as FolderWorkspaceLinkedTask } from '../../../../../shared/worktree/types' type ComposerIssueCommandInput = { enabled: boolean diff --git a/src/renderer/src/lib/composer-submit-cancellation.ts b/src/renderer/src/lib/workspace/creation/composer-submit-cancellation.ts similarity index 100% rename from src/renderer/src/lib/composer-submit-cancellation.ts rename to src/renderer/src/lib/workspace/creation/composer-submit-cancellation.ts diff --git a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts b/src/renderer/src/lib/workspace/creation/ephemeral-vm-worktree-creation.ts similarity index 92% rename from src/renderer/src/lib/ephemeral-vm-worktree-creation.ts rename to src/renderer/src/lib/workspace/creation/ephemeral-vm-worktree-creation.ts index fb6604f8eda..9243e25717f 100644 --- a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts +++ b/src/renderer/src/lib/workspace/creation/ephemeral-vm-worktree-creation.ts @@ -1,20 +1,20 @@ import { toast } from 'sonner' -import { useAppStore } from '@/store' -import { prepareEphemeralVmWorkspaceTarget } from '@/lib/ephemeral-vm-workspace-target' +import { useAppStore } from '@/store/index' +import { prepareEphemeralVmWorkspaceTarget } from '@/runtime/ephemeral-vm/ephemeral-vm-workspace-target' import type { WorktreeCreationRequest } from '@/lib/workspace/creation/pending-worktree-creation' -import { getProjectIdentityKey } from '../../../shared/project-host-setup-projection' -import type { Repo } from '../../../shared/repo-types' +import { getProjectIdentityKey } from '../../../../../shared/project-host-setup-projection' +import type { Repo } from '../../../../../shared/repo-types' import { translate } from '@/i18n/i18n' -import { cleanupFailedEphemeralVmWorkspace } from '@/lib/ephemeral-vm-failed-create-cleanup' -import { gateVmCreateOnEnvironmentCheck } from '@/lib/ephemeral-vm-environment-check' +import { cleanupFailedEphemeralVmWorkspace } from '@/runtime/ephemeral-vm/ephemeral-vm-failed-create-cleanup' +import { gateVmCreateOnEnvironmentCheck } from '@/runtime/ephemeral-vm/ephemeral-vm-environment-check' import { hideVmCreateCheckout, settleVmCreateCheckoutAfterCleanup -} from '@/lib/vm-create-hidden-checkouts' +} from '@/runtime/ephemeral-vm/vm-create-hidden-checkouts' import { appendProvisioningLog, appendProvisioningWarnings -} from '@/lib/pending-creation-provisioning-log' +} from '@/lib/workspace/creation/pending-creation-provisioning-log' export async function prepareRequestForCreate( creationId: string, diff --git a/src/renderer/src/lib/nested-repo-selected-paths.ts b/src/renderer/src/lib/workspace/creation/nested-repo-selected-paths.ts similarity index 74% rename from src/renderer/src/lib/nested-repo-selected-paths.ts rename to src/renderer/src/lib/workspace/creation/nested-repo-selected-paths.ts index 1faf58ca430..c04c7673e4a 100644 --- a/src/renderer/src/lib/nested-repo-selected-paths.ts +++ b/src/renderer/src/lib/workspace/creation/nested-repo-selected-paths.ts @@ -1,4 +1,4 @@ -import type { NestedRepoScanResult } from '../../../shared/project-group-types' +import type { NestedRepoScanResult } from '../../../../../shared/project-group-types' export function getSelectedNestedRepoPathsInScanOrder( scan: Pick, diff --git a/src/renderer/src/lib/new-workspace-composer-repo.ts b/src/renderer/src/lib/workspace/creation/new-workspace-composer-repo.ts similarity index 55% rename from src/renderer/src/lib/new-workspace-composer-repo.ts rename to src/renderer/src/lib/workspace/creation/new-workspace-composer-repo.ts index cf8957812cc..82b733734fd 100644 --- a/src/renderer/src/lib/new-workspace-composer-repo.ts +++ b/src/renderer/src/lib/workspace/creation/new-workspace-composer-repo.ts @@ -1,27 +1,18 @@ import { getRepoExecutionHostId, isRuntimeOwnedSshTargetId, - parseExecutionHostId, - type ExecutionHostScope -} from '../../../shared/execution-host' -import { - getNewWorkspaceDialogEligibleRepos, - resolveNewWorkspaceDialogGitRepoId, - resolveNewWorkspaceDialogRepoId -} from '../../../shared/new-workspace-dialog-repo' -import { getProjectIdentityKey } from '../../../shared/project-host-setup-projection' -import type { Repo } from '../../../shared/repo-types' + parseExecutionHostId +} from '../../../../../shared/execution-host' +import '../../../../../shared/new-workspace-dialog-repo' +import { getProjectIdentityKey } from '../../../../../shared/project-host-setup-projection' +import type { Repo } from '../../../../../shared/repo-types' import { isEphemeralVmRuntimeEnvironment, type PublicKnownRuntimeEnvironment -} from '../../../shared/remote-runtime/host-catalog/runtime-environments' +} from '../../../../../shared/remote-runtime/host-catalog/runtime-environments' type RuntimeEnvironmentSource = Pick -export function getComposerEligibleRepos(repos: readonly Repo[]): Repo[] { - return getNewWorkspaceDialogEligibleRepos(repos) -} - /** Per-workspace runtimes come in two kinds: runtime-owned SSH targets and ephemeral-VM Orca servers. */ function isPerWorkspaceRuntimeRepo( repo: Repo, @@ -60,35 +51,3 @@ export function resolveComposerActiveRepoId( ) return sibling?.id ?? activeRepoId } - -export function resolveComposerRepoId({ - eligibleRepos, - draftRepoId, - initialRepoId, - activeRepoId, - focusedHostScope -}: { - eligibleRepos: readonly Repo[] - draftRepoId?: string | null - initialRepoId?: string | null - activeRepoId?: string | null - focusedHostScope?: ExecutionHostScope | null -}): string { - return resolveNewWorkspaceDialogRepoId({ - eligibleRepos, - draftRepoId, - initialRepoId, - activeRepoId, - focusedHostScope - }) -} - -export function resolveComposerGitRepoId(args: { - eligibleRepos: readonly Repo[] - draftRepoId?: string | null - initialRepoId?: string | null - activeRepoId?: string | null - focusedHostScope?: ExecutionHostScope | null -}): string | null { - return resolveNewWorkspaceDialogGitRepoId(args) -} diff --git a/src/renderer/src/lib/new-workspace-create-gates.ts b/src/renderer/src/lib/workspace/creation/new-workspace-create-gates.ts similarity index 100% rename from src/renderer/src/lib/new-workspace-create-gates.ts rename to src/renderer/src/lib/workspace/creation/new-workspace-create-gates.ts diff --git a/src/renderer/src/lib/new-workspace-duplicate-project-details.ts b/src/renderer/src/lib/workspace/creation/new-workspace-duplicate-project-details.ts similarity index 99% rename from src/renderer/src/lib/new-workspace-duplicate-project-details.ts rename to src/renderer/src/lib/workspace/creation/new-workspace-duplicate-project-details.ts index 51bce9cec5b..4486f758480 100644 --- a/src/renderer/src/lib/new-workspace-duplicate-project-details.ts +++ b/src/renderer/src/lib/workspace/creation/new-workspace-duplicate-project-details.ts @@ -1,4 +1,4 @@ -import { getExecutionHostLabel, type ExecutionHostId } from '../../../shared/execution-host' +import { getExecutionHostLabel, type ExecutionHostId } from '../../../../../shared/execution-host' import type { NewWorkspaceProjectOption } from './new-workspace-project-options' export type ProjectSetupDirectory = { diff --git a/src/renderer/src/lib/new-workspace-enter-guard.ts b/src/renderer/src/lib/workspace/creation/new-workspace-enter-guard.ts similarity index 100% rename from src/renderer/src/lib/new-workspace-enter-guard.ts rename to src/renderer/src/lib/workspace/creation/new-workspace-enter-guard.ts diff --git a/src/renderer/src/lib/new-workspace-project-options.ts b/src/renderer/src/lib/workspace/creation/new-workspace-project-options.ts similarity index 91% rename from src/renderer/src/lib/new-workspace-project-options.ts rename to src/renderer/src/lib/workspace/creation/new-workspace-project-options.ts index 21c70365cde..3c8df617c20 100644 --- a/src/renderer/src/lib/new-workspace-project-options.ts +++ b/src/renderer/src/lib/workspace/creation/new-workspace-project-options.ts @@ -1,19 +1,19 @@ -import { projectHostSetupProjectionFromRepos } from '../../../shared/project-host-setup-projection' -import type { ProjectGroup } from '../../../shared/project-group-types' -import type { Project, ProjectHostSetup } from '../../../shared/project-types' -import type { Repo } from '../../../shared/repo-types' -import { isClipboardTextByteLengthOverLimit } from '../../../shared/clipboard-text' -import type { ExecutionHostRegistryEntry } from '../../../shared/execution-host/execution-host-registry-entry' +import { projectHostSetupProjectionFromRepos } from '../../../../../shared/project-host-setup-projection' +import type { ProjectGroup } from '../../../../../shared/project-group-types' +import type { Project, ProjectHostSetup } from '../../../../../shared/project-types' +import type { Repo } from '../../../../../shared/repo-types' +import { isClipboardTextByteLengthOverLimit } from '../../../../../shared/clipboard-text' +import type { ExecutionHostRegistryEntry } from '../../../../../shared/execution-host/execution-host-registry-entry' import { getExecutionHostLabel, getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID, type ExecutionHostId -} from '../../../shared/execution-host' +} from '../../../../../shared/execution-host' import { buildProjectGroupingIndex, isCheckoutScopedProjectSetup -} from '../../../shared/project-section-grouping' +} from '../../../../../shared/project-section-grouping' import { getDuplicateProjectDetailsById, type ProjectSetupDirectory @@ -247,10 +247,6 @@ function getProjectGroupDetail(group: ProjectGroup): string { return group.parentPath?.trim() || 'Repo group' } -export function getNewWorkspaceProjectGroupHostId(group: ProjectGroup): ExecutionHostId { - return getRepoExecutionHostId(group) -} - /** Require actionable hosts for folder selection, draft restore and retention of an existing pick. */ export function findActionableFolderProjectGroup({ projectGroups, @@ -269,7 +265,7 @@ export function findActionableFolderProjectGroup({ (group) => group.id === groupId && Boolean(group.parentPath?.trim()) && - actionableHostIds.has(getNewWorkspaceProjectGroupHostId(group)) + actionableHostIds.has(getRepoExecutionHostId(group)) ) ?? null ) } @@ -284,7 +280,7 @@ export function buildNewWorkspaceCreateTargetOptions({ .filter( (group) => Boolean(group.parentPath?.trim()) && - (!liveHostIds || liveHostIds.has(getNewWorkspaceProjectGroupHostId(group))) + (!liveHostIds || liveHostIds.has(getRepoExecutionHostId(group))) ) .map((group) => ({ kind: 'project-group' as const, diff --git a/src/renderer/src/lib/new-workspace-ssh-gate.ts b/src/renderer/src/lib/workspace/creation/new-workspace-ssh-gate.ts similarity index 79% rename from src/renderer/src/lib/new-workspace-ssh-gate.ts rename to src/renderer/src/lib/workspace/creation/new-workspace-ssh-gate.ts index 1cd863d907a..4cd1d601c64 100644 --- a/src/renderer/src/lib/new-workspace-ssh-gate.ts +++ b/src/renderer/src/lib/workspace/creation/new-workspace-ssh-gate.ts @@ -1,6 +1,6 @@ import { isConnectingSshStatus } from '@/ssh/ssh-connection-recoverability' -import { isRuntimeOwnedSshTargetId } from '../../../shared/execution-host' -import type { SshConnectionStatus } from '../../../shared/ssh-types' +import { isRuntimeOwnedSshTargetId } from '../../../../../shared/execution-host' +import type { SshConnectionStatus } from '../../../../../shared/ssh-types' export type SelectedRepoSshGate = { selectedRepoConnectionId: string | null @@ -9,10 +9,6 @@ export type SelectedRepoSshGate = { selectedRepoConnectInProgress: boolean } -export function isSshConnectInProgress(status: SshConnectionStatus | null): boolean { - return isConnectingSshStatus(status) -} - export function getSelectedRepoSshGate(input: { connectionId: string | null | undefined status: SshConnectionStatus | null | undefined @@ -27,7 +23,7 @@ export function getSelectedRepoSshGate(input: { selectedRepoSshStatus, selectedRepoRequiresConnection: selectedRepoConnectionId !== null && selectedRepoSshStatus !== 'connected', - selectedRepoConnectInProgress: isSshConnectInProgress(selectedRepoSshStatus) + selectedRepoConnectInProgress: isConnectingSshStatus(selectedRepoSshStatus) } } diff --git a/src/renderer/src/lib/new-workspace.ts b/src/renderer/src/lib/workspace/creation/new-workspace.ts similarity index 92% rename from src/renderer/src/lib/new-workspace.ts rename to src/renderer/src/lib/workspace/creation/new-workspace.ts index db1a1de525c..4a7853a35d5 100644 --- a/src/renderer/src/lib/new-workspace.ts +++ b/src/renderer/src/lib/workspace/creation/new-workspace.ts @@ -1,8 +1,8 @@ -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { pasteDraftToAgentPtyWhenReady } from '@/lib/agent-session/messaging/paste/agent-paste-draft' import { sendFollowupPromptWhenAgentReady } from '@/lib/agent-session/messaging/paste/agent-followup-delivery' import { showAutomationPromptNotSentToast } from '@/lib/agent-session/launch/background/agent-background-session-timeout-toast' -import type { AgentStartupPlan } from '../../../shared/agent-launch/startup/tui-agent-startup' +import type { AgentStartupPlan } from '../../../../../shared/agent-launch/startup/tui-agent-startup' import type { LinkedWorkItemContext } from '@/lib/work-items/linked-work-item-context' import { beginAgentStartupDeliveryAttempt, @@ -10,12 +10,9 @@ import { queuePendingAgentStartupDelivery, resolveAgentStartupTabId } from '@/lib/agent-session/launch/startup/agent-startup-delayed-delivery' -import type { WorkspaceLinkedItem as FolderWorkspaceLinkedTask } from '../../../shared/worktree/types' -import { slugifyForWorkspaceName } from '../../../shared/workspace-name' -import { createNonSecureContextUuid as createBrowserUuid } from '../../../shared/non-secure-context-uuid' -export { getLinkedWorkItemSuggestedName } from '../../../shared/workspace-name' -export { getLinkedWorkItemWorkspaceName } from '../../../shared/workspace-name' -export { getWorkspaceIntentName } from '../../../shared/workspace-name' +import type { WorkspaceLinkedItem as FolderWorkspaceLinkedTask } from '../../../../../shared/worktree/types' +import { slugifyForWorkspaceName } from '../../../../../shared/workspace-name' +import { createNonSecureContextUuid as createBrowserUuid } from '../../../../../shared/non-secure-context-uuid' export const CLIENT_PLATFORM: NodeJS.Platform = navigator.userAgent.includes('Windows') ? 'win32' diff --git a/src/renderer/src/lib/pending-creation-provisioning-log.ts b/src/renderer/src/lib/workspace/creation/pending-creation-provisioning-log.ts similarity index 95% rename from src/renderer/src/lib/pending-creation-provisioning-log.ts rename to src/renderer/src/lib/workspace/creation/pending-creation-provisioning-log.ts index 5be89aa8a7a..5aade03d087 100644 --- a/src/renderer/src/lib/pending-creation-provisioning-log.ts +++ b/src/renderer/src/lib/workspace/creation/pending-creation-provisioning-log.ts @@ -1,4 +1,4 @@ -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' const MAX_PROVISIONING_LOG_CHARS = 12_000 diff --git a/src/renderer/src/lib/project-clone-url-prefill.test.ts b/src/renderer/src/lib/workspace/creation/project-clone-url-prefill.test.ts similarity index 57% rename from src/renderer/src/lib/project-clone-url-prefill.test.ts rename to src/renderer/src/lib/workspace/creation/project-clone-url-prefill.test.ts index d0e065ace25..d8b0b0e19bd 100644 --- a/src/renderer/src/lib/project-clone-url-prefill.test.ts +++ b/src/renderer/src/lib/workspace/creation/project-clone-url-prefill.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import type { Project } from '../../../shared/project-types' -import type { Repo } from '../../../shared/repo-types' +import type { Project } from '../../../../../shared/project-types' +import type { Repo } from '../../../../../shared/repo-types' import { resolveProjectCloneUrlPrefill } from './project-clone-url-prefill' function project(sourceRepoIds: string[]): Project { @@ -23,30 +23,6 @@ describe('resolveProjectCloneUrlPrefill', () => { expect(prefill).toBe('https://github.com/acme/orca.git') expect(prefill).not.toContain('ghp_ABC123') }) - it('stops on the first usable source and indexes later misses only once', () => { - let reads = 0 - const repos = Array.from({ length: 1000 }, (_, i) => ({ - ...repo(`repo-${i}`, 'https://gitlab.com/acme/repo.git'), - get id() { - reads++ - return `repo-${i}` - } - })) - const sourceIds = Array.from({ length: 1000 }, (_, i) => `repo-${i}`) - expect(resolveProjectCloneUrlPrefill([project(sourceIds)], repos, 'project-orca')).toBe( - 'https://gitlab.com/acme/repo.git' - ) - expect(reads).toBe(1) - reads = 0 - expect( - resolveProjectCloneUrlPrefill( - [project(sourceIds.map((id) => `missing-${id}`))], - repos, - 'project-orca' - ) - ).toBe('') - expect(reads).toBeLessThanOrEqual(2000) - }) it('keeps the first duplicate repo authoritative when building the fallback index', () => { expect( diff --git a/src/renderer/src/lib/project-clone-url-prefill.ts b/src/renderer/src/lib/workspace/creation/project-clone-url-prefill.ts similarity index 83% rename from src/renderer/src/lib/project-clone-url-prefill.ts rename to src/renderer/src/lib/workspace/creation/project-clone-url-prefill.ts index ec97d4db2ea..c8bc8ba91bf 100644 --- a/src/renderer/src/lib/project-clone-url-prefill.ts +++ b/src/renderer/src/lib/workspace/creation/project-clone-url-prefill.ts @@ -1,6 +1,6 @@ -import { stripCredentialsFromMessage } from '../../../shared/git/remotes/git-remote-error' -import type { Project } from '../../../shared/project-types' -import type { Repo } from '../../../shared/repo-types' +import { stripCredentialsFromMessage } from '../../../../../shared/git/remotes/git-remote-error' +import type { Project } from '../../../../../shared/project-types' +import type { Repo } from '../../../../../shared/repo-types' /** Seed from the project remote after stripping embedded credentials: target-host clone persists URLs to .git/config and must not receive an unentered PAT. Match getProvisionedRootRecipeRepoUrl. */ export function resolveProjectCloneUrlPrefill( diff --git a/src/renderer/src/lib/project-host-health-detail.ts b/src/renderer/src/lib/workspace/creation/project-host-health-detail.ts similarity index 86% rename from src/renderer/src/lib/project-host-health-detail.ts rename to src/renderer/src/lib/workspace/creation/project-host-health-detail.ts index 218f46c4236..bb2705db83f 100644 --- a/src/renderer/src/lib/project-host-health-detail.ts +++ b/src/renderer/src/lib/workspace/creation/project-host-health-detail.ts @@ -1,4 +1,4 @@ -import type { ExecutionHostHealth } from '../../../shared/execution-host/execution-host-health' +import type { ExecutionHostHealth } from '../../../../../shared/execution-host/execution-host-health' /** Why a host cannot take a project setup right now, from its health; null when health allows it. */ export function getHostHealthUnavailableDetail(health: ExecutionHostHealth): string | null { diff --git a/src/renderer/src/lib/project-host-setup-options.ts b/src/renderer/src/lib/workspace/creation/project-host-setup-options.ts similarity index 93% rename from src/renderer/src/lib/project-host-setup-options.ts rename to src/renderer/src/lib/workspace/creation/project-host-setup-options.ts index a3acdbeb19e..9859258304a 100644 --- a/src/renderer/src/lib/project-host-setup-options.ts +++ b/src/renderer/src/lib/workspace/creation/project-host-setup-options.ts @@ -4,18 +4,19 @@ import { LOCAL_EXECUTION_HOST_ID, parseExecutionHostId, type ExecutionHostId -} from '../../../shared/execution-host' -import type { ExecutionHostRegistryEntry } from '../../../shared/execution-host/execution-host-registry-entry' +} from '../../../../../shared/execution-host' +import type { ExecutionHostRegistryEntry } from '../../../../../shared/execution-host/execution-host-registry-entry' import { getHostHealthUnavailableDetail } from './project-host-health-detail' -import { isHostLocalProjectId } from '../../../shared/project-host-setup-projection' -import { isEphemeralVmRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { isMergedAwayExecutionHost } from '../../../shared/execution-host/managed-orcad-execution-host' +import { isHostLocalProjectId } from '../../../../../shared/project-host-setup-projection' +import { isEphemeralVmRuntimeEnvironment } from '../../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { isMergedAwayExecutionHost } from '../../../../../shared/execution-host/managed-orcad-execution-host' +import '../../../../../shared/protocol-version' import { PROJECT_HOST_SETUP_RUNTIME_CAPABILITY, WORKSPACE_RUN_CONTEXT_RUNTIME_CAPABILITY -} from '../../../shared/protocol-version' -import type { ProjectHostSetup } from '../../../shared/project-types' -import type { Repo } from '../../../shared/repo-types' +} from '../../../../../shared/worktree-runtime-capabilities' +import type { ProjectHostSetup } from '../../../../../shared/project-types' +import type { Repo } from '../../../../../shared/repo-types' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import { diff --git a/src/renderer/src/lib/project-host-setup-row-dedupe.ts b/src/renderer/src/lib/workspace/creation/project-host-setup-row-dedupe.ts similarity index 93% rename from src/renderer/src/lib/project-host-setup-row-dedupe.ts rename to src/renderer/src/lib/workspace/creation/project-host-setup-row-dedupe.ts index c3181418727..d6ea2f48ed3 100644 --- a/src/renderer/src/lib/project-host-setup-row-dedupe.ts +++ b/src/renderer/src/lib/workspace/creation/project-host-setup-row-dedupe.ts @@ -1,5 +1,5 @@ -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { ExecutionHostRegistryEntry } from '../../../shared/execution-host/execution-host-registry-entry' +import type { ExecutionHostId } from '../../../../../shared/execution-host' +import type { ExecutionHostRegistryEntry } from '../../../../../shared/execution-host/execution-host-registry-entry' import type { ProjectHostSetupSelection, ReadyProjectHostSetupOption diff --git a/src/renderer/src/lib/project-host-workspace-target.jira-mapping.test.ts b/src/renderer/src/lib/workspace/creation/project-host-workspace-target.jira-mapping.test.ts similarity index 95% rename from src/renderer/src/lib/project-host-workspace-target.jira-mapping.test.ts rename to src/renderer/src/lib/workspace/creation/project-host-workspace-target.jira-mapping.test.ts index 0e74166d4c4..27776182235 100644 --- a/src/renderer/src/lib/project-host-workspace-target.jira-mapping.test.ts +++ b/src/renderer/src/lib/workspace/creation/project-host-workspace-target.jira-mapping.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import type { Repo } from '../../../shared/repo-types' -import { projectHostSetupProjectionFromRepos } from '../../../shared/project-host-setup-projection' +import type { Repo } from '../../../../../shared/repo-types' +import { projectHostSetupProjectionFromRepos } from '../../../../../shared/project-host-setup-projection' import { getRepoWorkspaceCreationTargetHint, resolveWorkspaceCreationTarget diff --git a/src/renderer/src/lib/project-host-workspace-target.test.ts b/src/renderer/src/lib/workspace/creation/project-host-workspace-target.test.ts similarity index 95% rename from src/renderer/src/lib/project-host-workspace-target.test.ts rename to src/renderer/src/lib/workspace/creation/project-host-workspace-target.test.ts index b1e03edaaf5..c5ac42f4d93 100644 --- a/src/renderer/src/lib/project-host-workspace-target.test.ts +++ b/src/renderer/src/lib/workspace/creation/project-host-workspace-target.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { Project, ProjectHostSetup } from '../../../shared/project-types' -import type { Repo } from '../../../shared/repo-types' +import type { ExecutionHostId } from '../../../../../shared/execution-host' +import type { Project, ProjectHostSetup } from '../../../../../shared/project-types' +import type { Repo } from '../../../../../shared/repo-types' import { resolveWorkspaceCreationTarget } from './project-host-workspace-target' function makeRepo(id: string, overrides: Partial = {}): Repo { diff --git a/src/renderer/src/lib/project-host-workspace-target.ts b/src/renderer/src/lib/workspace/creation/project-host-workspace-target.ts similarity index 93% rename from src/renderer/src/lib/project-host-workspace-target.ts rename to src/renderer/src/lib/workspace/creation/project-host-workspace-target.ts index c082614e5bc..108c3ca4425 100644 --- a/src/renderer/src/lib/project-host-workspace-target.ts +++ b/src/renderer/src/lib/workspace/creation/project-host-workspace-target.ts @@ -3,16 +3,17 @@ import { getRepoExecutionHostId, type ExecutionHostId, type ExecutionHostScope -} from '../../../shared/execution-host' +} from '../../../../../shared/execution-host' import { getProjectIdentityKey, projectHostSetupProjectionFromRepos -} from '../../../shared/project-host-setup-projection' -import type { Project, ProjectHostSetup } from '../../../shared/project-types' -import type { Repo } from '../../../shared/repo-types' -import { resolveComposerRepoId } from './new-workspace-composer-repo' -import { findSoleHostCopy } from '../../../shared/worktree/host-qualified-identity' -import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' +} from '../../../../../shared/project-host-setup-projection' +import type { Project, ProjectHostSetup } from '../../../../../shared/project-types' +import type { Repo } from '../../../../../shared/repo-types' +import './new-workspace-composer-repo' +import { resolveNewWorkspaceDialogRepoId } from '../../../../../shared/new-workspace-dialog-repo' +import { findSoleHostCopy } from '../../../../../shared/worktree/host-qualified-identity' +import { normalizeRuntimePathForComparison } from '../../../../../shared/cross-platform-path' export type WorkspaceCreationTarget = { projectId: string @@ -252,7 +253,7 @@ export function resolveWorkspaceCreationTarget( return { status: 'unavailable', reason: 'project-not-set-up-on-host' } } - const repoId = resolveComposerRepoId(input) + const repoId = resolveNewWorkspaceDialogRepoId(input) const legacyCandidates = repoId ? (reposById.get(repoId) ?? []) : [] const focusedLegacyRepo = focusedHostScope && focusedHostScope !== ALL_EXECUTION_HOSTS_SCOPE diff --git a/src/renderer/src/lib/provisioned-root-create-options.ts b/src/renderer/src/lib/workspace/creation/provisioned-root-create-options.ts similarity index 90% rename from src/renderer/src/lib/provisioned-root-create-options.ts rename to src/renderer/src/lib/workspace/creation/provisioned-root-create-options.ts index a2cceb85964..2a6df07d7a5 100644 --- a/src/renderer/src/lib/provisioned-root-create-options.ts +++ b/src/renderer/src/lib/workspace/creation/provisioned-root-create-options.ts @@ -1,4 +1,4 @@ -import type { WorktreeCreationRequest } from './workspace/creation/pending-worktree-creation' +import type { WorktreeCreationRequest } from './pending-worktree-creation' export type ProvisionedRootCreateOptions = { runtimeId: string diff --git a/src/renderer/src/lib/quick-workspace-agent-selection.ts b/src/renderer/src/lib/workspace/creation/quick-workspace-agent-selection.ts similarity index 92% rename from src/renderer/src/lib/quick-workspace-agent-selection.ts rename to src/renderer/src/lib/workspace/creation/quick-workspace-agent-selection.ts index 86757c75660..c0ad812c7fb 100644 --- a/src/renderer/src/lib/quick-workspace-agent-selection.ts +++ b/src/renderer/src/lib/workspace/creation/quick-workspace-agent-selection.ts @@ -3,15 +3,15 @@ import { agentPickerFreshLaunchInputs, type AgentPickerDraft, type AgentPickerEntry -} from '../../../shared/agent-launch/picker/agent-launch-picker' -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' +} from '../../../../../shared/agent-launch/picker/agent-launch-picker' +import type { ExecutionHostId } from '../../../../../shared/execution-host' +import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent' import type { ProspectiveWorkspace } from '@/lib/agent-session/launch/routing/agent-launch-route-input' import { isTuiAgentEnabled, pickTuiAgent, TUI_AGENT_AUTO_PICK_ORDER -} from '../../../shared/agent-launch/catalog/tui-agent-selection' +} from '../../../../../shared/agent-launch/catalog/tui-agent-selection' /** `offeredAgentIds`: chosen agents that open as a chat without a CLI; auto-picks stay detected. */ export function pickQuickWorkspaceAgent( diff --git a/src/renderer/src/lib/hook-command-delayed-delivery.ts b/src/renderer/src/lib/workspace/creation/setup/hook-command-delayed-delivery.ts similarity index 98% rename from src/renderer/src/lib/hook-command-delayed-delivery.ts rename to src/renderer/src/lib/workspace/creation/setup/hook-command-delayed-delivery.ts index 462545373ae..2247157d5c0 100644 --- a/src/renderer/src/lib/hook-command-delayed-delivery.ts +++ b/src/renderer/src/lib/workspace/creation/setup/hook-command-delayed-delivery.ts @@ -1,4 +1,4 @@ -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { selectDetectedWorktreesByRepo, selectFolderWorkspaces, diff --git a/src/renderer/src/lib/setup-runner.ts b/src/renderer/src/lib/workspace/creation/setup/setup-runner.ts similarity index 74% rename from src/renderer/src/lib/setup-runner.ts rename to src/renderer/src/lib/workspace/creation/setup/setup-runner.ts index 4e07c9d4df5..4dd1f4bee36 100644 --- a/src/renderer/src/lib/setup-runner.ts +++ b/src/renderer/src/lib/workspace/creation/setup/setup-runner.ts @@ -1,8 +1,8 @@ import { buildSetupRunnerCommand as buildSharedSetupRunnerCommand, getSetupRunnerCommandPlatformForPath -} from '../../../shared/agent-launch/startup/setup-runner-command' -import type { SetupRunnerShell } from '../../../shared/agent-launch/startup/setup-runner-command' +} from '../../../../../../shared/agent-launch/startup/setup-runner-command' +import type { SetupRunnerShell } from '../../../../../../shared/agent-launch/startup/setup-runner-command' export function buildSetupRunnerCommand( runnerScriptPath: string, diff --git a/src/renderer/src/lib/workspace/creation/setup/workspace-setup-preparation.ts b/src/renderer/src/lib/workspace/creation/setup/workspace-setup-preparation.ts index 59629227cc0..46e58911394 100644 --- a/src/renderer/src/lib/workspace/creation/setup/workspace-setup-preparation.ts +++ b/src/renderer/src/lib/workspace/creation/setup/workspace-setup-preparation.ts @@ -9,7 +9,7 @@ import { getDefaultSetupDecision, type SetupConfig } from '../../../../../../shared/orca-hook-setup-config' -import { settleComposerSubmit } from '../../../composer-submit-cancellation' +import { settleComposerSubmit } from '../composer-submit-cancellation' type SetupRepo = { hookSettings?: RepoHookSettings } type SetupReadOutcome = diff --git a/src/renderer/src/lib/workspace-setup-trust.ts b/src/renderer/src/lib/workspace/creation/setup/workspace-setup-trust.ts similarity index 73% rename from src/renderer/src/lib/workspace-setup-trust.ts rename to src/renderer/src/lib/workspace/creation/setup/workspace-setup-trust.ts index a2c60c6e1d2..f437f3d4cea 100644 --- a/src/renderer/src/lib/workspace-setup-trust.ts +++ b/src/renderer/src/lib/workspace/creation/setup/workspace-setup-trust.ts @@ -1,10 +1,10 @@ import type { AppState } from '@/store/types' -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { SetupDecision } from '../../../shared/worktree/create-types' -import type { ApprovedSetupHashes } from '../../../shared/worktree/approved-setup-hashes' -import { approvedOrcaHookContentHashes } from '../../../shared/orca-hook-trust-entries' -import { ensureHooksApproved } from './ensure-hooks-confirmed' -import { settleComposerSubmit } from './composer-submit-cancellation' +import type { ExecutionHostId } from '../../../../../../shared/execution-host' +import type { SetupDecision } from '../../../../../../shared/worktree/create-types' +import type { ApprovedSetupHashes } from '../../../../../../shared/worktree/approved-setup-hashes' +import { approvedOrcaHookContentHashes } from '../../../../../../shared/orca-hook-trust-entries' +import { ensureHooksApproved } from '../../../../runtime/repo-hooks/ensure-hooks-confirmed' +import { settleComposerSubmit } from '../composer-submit-cancellation' export async function confirmWorkspaceSetupDecision( stateOrGetter: AppState | (() => AppState), diff --git a/src/renderer/src/lib/workspace/creation/work-item/direct-work-item-setup.ts b/src/renderer/src/lib/workspace/creation/work-item/direct-work-item-setup.ts index 3913c1581c7..776fd17b9ef 100644 --- a/src/renderer/src/lib/workspace/creation/work-item/direct-work-item-setup.ts +++ b/src/renderer/src/lib/workspace/creation/work-item/direct-work-item-setup.ts @@ -7,7 +7,7 @@ import { MODAL_DISMISSED_KEY } from '@/store/slices/ui/modal-slot-dismissal' import './launch-work-item-direct-preflight' import { inspectRequiredWorkspaceSetup as resolveDirectSetupDecision } from '../setup/workspace-setup-preparation' import type { WorkspaceSetupInspection as DirectSetupInspection } from '../setup/workspace-setup-preparation' -import { confirmWorkspaceSetupDecision } from '../../../workspace-setup-trust' +import { confirmWorkspaceSetupDecision } from '../setup/workspace-setup-trust' import type { Repo } from '../../../../../../shared/repo-types' import type { ExecutionHostId } from '../../../../../../shared/execution-host' import type { SetupDecision } from '../../../../../../shared/worktree/create-types' diff --git a/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-accepted.test.tsx b/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-accepted.test.tsx index fbb02bcc32b..c2e02e7cb92 100644 --- a/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-accepted.test.tsx +++ b/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-accepted.test.tsx @@ -1,52 +1,23 @@ // @vitest-environment happy-dom -import { mocks, hostMocks } from './launch-work-item-direct-test-fixture' -import { getDefaultSettings } from '../../../../../../shared/constants' -import { i18n } from '@/i18n/i18n' -import fr from '@/i18n/locales/fr.json' -import { act, cleanup, fireEvent, render, renderHook, screen } from '@testing-library/react' +import { mocks } from './launch-work-item-direct-test-fixture' + +import { act, cleanup, renderHook } from '@testing-library/react' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { sourceControlActionRecipeEntry } from '../../../../../../shared/source-control/ai/recipes/source-control-action-selection' import { useAppStore } from '@/store/index' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' -import * as preparation from './launch-work-item-direct-route-preparation' + import * as preflight from './launch-work-item-direct-preflight' -import { adoptAgentSessionLaunchVerdict } from '../../../agent-session/launch/routing/agent-session-launch-plan' -import { newAgentLaunchRequestId } from '../../../agent-session/launch/routing/agent-launch-request-id' -import { LOCAL_EXECUTION_HOST_ID } from '../../../../../../shared/execution-host' -import { createUIStore } from '@/store/slices/ui/ui-slice-test-harness' -import { readDirectSetupRequest } from './direct-work-item-setup-test-fixture' -import { DirectWorkItemSetupDialog } from '@/components/new-workspace/DirectWorkItemSetupDialog' -import { projectRelationsTableFixture } from '../../../../../../shared/github/project-relations.test-fixture' -import { - publicRuntimeEnvironment, - connectedRuntimeStatus -} from '@/runtime/rpc/testing/paired-runtime-environment-test-fixture' -import { runtimeEnvironmentStatusFromSnapshot } from '../../../../../../shared/remote-runtime/host-status/runtime-host-status' -import { replaceRuntimeEnvironmentRevisions } from '@/runtime/rpc/environment-revisions/runtime-environment-revision' -import { - resource, - clearHostAgentMenuSettingsForTests -} from '@/runtime/agent-launch-settings/host-agent-launch-preferences-resource' -import { readAgentLaunchPreferencesForWorkspace } from '@/runtime/agent-launch-settings/use-host-agent-launch-preferences' -import { getRuntimeAgentInventoryKey } from '@/store/slices/agent-inventory/runtime-agent-inventory-key' - -vi.mock('@/lib/repo-slug-index', () => ({ - useRepoSlugIndex: () => ({ - ready: true, - lookupSlug: () => useAppStore.getState().repos[0], - lookupSlugMatches: () => ({ origin: useAppStore.getState().repos, upstream: [] }) - }) -})) - -vi.doUnmock('@/lib/ensure-hooks-confirmed') +vi.doUnmock('@/runtime/repo-hooks/ensure-hooks-confirmed') const { useSourceControlAgentActionStart } = await import('@/components/right-sidebar/source-control/ai/useSourceControlAgentActionStart') const { startFixChecksFromDialog } = await import('@/components/pull-request-page/checks/fix-launch') const { launchWorkItemDirect } = await import('./launch-work-item-direct') -const { useProjectRowActions } = await import('@/components/github-project/useProjectRowActions') -const { __resetTrustPromptChainForTests } = await import('../../../ensure-hooks-confirmed') + +const { __resetTrustPromptChainForTests } = + await import('../../../../runtime/repo-hooks/ensure-hooks-confirmed') const structured = vi.hoisted(() => vi.fn()) vi.mock('@/lib/agent-session/structured-agent-session-provisional-tab', () => ({ @@ -125,187 +96,6 @@ function mountStart(agentArgs = '--model o3') { return { ...view, onClose, onLaunched } } -it.each([false, true])( - 'settles a real Ask Run trust digest rejection with precreate cancellation=%s', - async (cancel) => { - const ui = createUIStore() - useAppStore.setState({ - openModal: ui.getState().openModal, - closeModal: ui.getState().closeModal, - modalData: {}, - repos: [ - { - ...useAppStore.getState().repos[0], - hookSettings: { - mode: 'auto', - scripts: { setup: '', archive: '' }, - setupRunPolicy: 'ask' - } - } - ] - }) - const unsubscribe = ui.subscribe(({ activeModal, modalData }) => - useAppStore.setState({ activeModal, modalData }) - ) - const digest = Promise.withResolvers() - const hash = vi.spyOn(crypto.subtle, 'digest').mockReturnValueOnce(digest.promise) - hostMocks.checkRuntimeHooks.mockResolvedValue({ - hasHooks: true, - hooks: { scripts: { setup: 'echo setup' } } - }) - const view = mountStart() - let start: Promise - try { - act(() => { - start = view.result.current.startWithDetectedAgents({ detectedAgents: ['codex'] }) - }) - await vi.waitFor(() => - expect(useAppStore.getState().activeModal).toBe('new-workspace-composer') - ) - render( - - ) - fireEvent.click(screen.getByRole('button', { name: 'Run setup' })) - await vi.waitFor(() => expect(hash).toHaveBeenCalledOnce()) - if (cancel) { - act(() => view.result.current.cancelStart()) - } - await act(async () => { - digest.reject(new DOMException('Setup trust hash failed', 'OperationError')) - expect(await start!).toBe(false) - }) - expect(mocks.toastError.mock.calls).toEqual( - cancel - ? [] - : [['Could not start a new Codex session.', { description: 'Setup trust hash failed' }]] - ) - expect(mocks.createWorktree).not.toHaveBeenCalled() - expect(view.onLaunched).not.toHaveBeenCalled() - expect(view.onClose).not.toHaveBeenCalled() - expect(view.result.current.isStarting).toBe(false) - } finally { - unsubscribe() - } - } -) - -it.each(['terminal', 'structured'] as const)( - 'retains an issued %s create through hide/cleanup and matching settlement', - async (route) => { - const pending = Promise.withResolvers() - mocks.createWorktree.mockReturnValueOnce(pending.promise) - hostMocks.checkRuntimeHooks.mockResolvedValue({ hasHooks: false, hooks: null }) - if (route === 'structured') { - const plan = adoptAgentSessionLaunchVerdict({ - requestId: newAgentLaunchRequestId(), - route: 'structured-native-chat', - agent: 'codex', - executionHostId: LOCAL_EXECUTION_HOST_ID, - worktreeId: created.worktree.id, - prompt: 'Edited prompt', - promptDelivery: 'submit-after-ready', - launchOptions: { model: 'o3' }, - requestedSurface: 'chat' - }) - vi.spyOn(preflight, 'planDirectWorkItemLaunch').mockResolvedValueOnce(plan) - structured.mockImplementationOnce(({ plan: submitted, beforeOpen }) => { - expect(submitted).toMatchObject({ prompt: 'Edited prompt', launchOptions: { model: 'o3' } }) - expect(beforeOpen()).toBe(true) - return { tab: { id: 'chat-tab' } } - }) - } - const view = mountStart() - let start: Promise - act(() => { - start = view.result.current.startWithDetectedAgents({ detectedAgents: ['codex'] }) - }) - await vi.waitFor(() => { - expect(mocks.createWorktree).toHaveBeenCalledOnce() - expect(view.result.current.isCreateAccepted).toBe(true) - }) - act(() => view.result.current.cancelStart()) - view.rerender({ open: false, connectionId: 'another-context' }) - view.rerender({ open: true, connectionId: 'another-context' }) - expect(view.result.current.isStarting).toBe(true) - await act(async () => - expect(await view.result.current.startWithDetectedAgents({ detectedAgents: ['codex'] })).toBe( - false - ) - ) - await act(async () => { - // The real store publishes a workspace before returning its create result. - useAppStore.setState({ - worktreesByRepo: { 'repo-1': [{ ...created.worktree, repoId: 'repo-1' }] } - }) - pending.resolve(created) - expect(await start!).toBe(true) - }) - expect(mocks.createWorktree).toHaveBeenCalledOnce() - expect(mocks.activateAndRevealWorktree).toHaveBeenCalledWith( - created.worktree.id, - expect.objectContaining({ setup: created.setup, defaultTabs: created.defaultTabs }) - ) - if (route === 'terminal') { - expect(mocks.pasteDraftWhenAgentReady).toHaveBeenCalledWith( - expect.objectContaining({ content: 'Edited prompt', agent: 'codex', submit: true }) - ) - } else { - expect(structured).toHaveBeenCalledOnce() - expect(mocks.pasteDraftWhenAgentReady).not.toHaveBeenCalled() - } - expect(view.onLaunched).toHaveBeenCalledOnce() - expect(view.onClose).not.toHaveBeenCalled() - expect(view.result.current.isStarting).toBe(false) - expect(mocks.toastError).not.toHaveBeenCalled() - } -) - -it.each(['create', 'agent-preparation', 'activation', 'prompt-plan'] as const)( - 'reports one real accepted %s failure after detachment and releases for retry', - async (stage) => { - const gate = Promise.withResolvers() - const creation = Promise.withResolvers() - if (stage === 'create') { - mocks.createWorktree.mockReturnValueOnce(gate.promise) - } else if (stage === 'agent-preparation') { - vi.spyOn(preparation, 'prepareDirectWorkItemAgentLaunch').mockReturnValueOnce(gate.promise) - } else if (stage === 'activation') { - mocks.createWorktree.mockReturnValueOnce(creation.promise) - mocks.activateAndRevealWorktree.mockReturnValueOnce(false) - } else { - mocks.createWorktree.mockReturnValueOnce(creation.promise) - const actualPrepare = preparation.prepareDirectWorkItemAgentLaunch - vi.spyOn(preparation, 'prepareDirectWorkItemAgentLaunch').mockImplementationOnce( - async (args) => ({ ...(await actualPrepare(args)), startupPlanFailed: true }) - ) - } - const view = mountStart() - let start: Promise - act(() => { - start = view.result.current.startWithDetectedAgents({ detectedAgents: ['codex'] }) - }) - await vi.waitFor(() => expect(mocks.createWorktree).toHaveBeenCalledOnce()) - act(() => view.result.current.cancelStart()) - creation.resolve(created) - if (stage === 'create' || stage === 'agent-preparation') { - gate.reject(new Error('Accepted preparation failed')) - } - await act(async () => expect(await start!).toBe(false)) - expect(mocks.toastError).toHaveBeenCalledOnce() - expect(view.onLaunched).not.toHaveBeenCalled() - expect(view.onClose).not.toHaveBeenCalled() - expect(view.result.current.isStarting).toBe(false) - await act(async () => - expect(await view.result.current.startWithDetectedAgents({ detectedAgents: ['codex'] })).toBe( - true - ) - ) - expect(mocks.createWorktree).toHaveBeenCalledTimes(2) - } -) - it('does not release or close a successor when cancelled pre-create work later settles', async () => { const oldPlan = Promise.withResolvers>>() @@ -345,58 +135,6 @@ it('does not release or close a successor when cancelled pre-create work later s expect(view.result.current.isStarting).toBe(false) }) -it.each(['settled-host', 'pending-host', 'missing-owner', 'pr-head', 'arguments'] as const)( - 'Fix checks reports one precreate failure, with pending silent: %s', - async (failure) => { - if (failure === 'settled-host' || failure === 'pending-host') { - useAppStore.setState({ - repos: [{ ...useAppStore.getState().repos[0], connectionId: 'ssh-1' }], - sshConnectionStates: new Map([ - [ - 'ssh-1', - { - targetId: 'ssh-1', - status: failure === 'pending-host' ? 'connecting' : 'connected', - error: null, - reconnectAttempt: 0 - } - ] - ]) - }) - } else if (failure === 'missing-owner') { - useAppStore.setState({ repos: [] }) - } else if (failure === 'pr-head') { - mocks.resolvePrBase.mockResolvedValueOnce({ - error: 'PR #42 not found.', - errorCode: 'github.prNotFound', - errorParams: { number: 42 } - }) - } - const view = mountStart(failure === 'arguments' ? "--model '" : undefined) - await act(async () => { - expect(await view.result.current.startWithDetectedAgents({ detectedAgents: ['codex'] })).toBe( - false - ) - }) - expect(mocks.toastError).toHaveBeenCalledTimes( - failure === 'pending-host' || failure === 'arguments' ? 0 : 1 - ) - if (failure !== 'pending-host' && failure !== 'arguments') { - expect(mocks.toastError.mock.calls[0][0]).toBe('Could not start a new Codex session.') - } - if (failure === 'settled-host') { - expect(mocks.toastError.mock.calls[0][1]).toEqual({ - description: - 'Terminal launch is unavailable on this SSH host. Open a terminal in the workspace and start the agent there.' - }) - } - expect(mocks.createWorktree).not.toHaveBeenCalled() - expect(view.onLaunched).not.toHaveBeenCalled() - expect(view.onClose).not.toHaveBeenCalled() - expect(view.result.current.isStarting).toBe(false) - } -) - it('keeps a functional navigation fallback after reporting a PR lookup failure', async () => { mocks.resolvePrBase.mockResolvedValueOnce({ error: 'PR #42 not found.', @@ -420,98 +158,3 @@ it('keeps a functional navigation fallback after reporting a PR lookup failure', expect(mocks.toastError).toHaveBeenCalledOnce() expect(mocks.createWorktree).not.toHaveBeenCalled() }) - -it('Fix checks localizes the one named-agent PR lookup failure', async () => { - const language = i18n.language - i18n.addResourceBundle('fr', 'translation', fr) - try { - await i18n.changeLanguage('fr') - mocks.resolvePrBase.mockResolvedValueOnce({ - error: 'PR #42 not found.', - errorCode: 'github.prNotFound', - errorParams: { number: 42 } - }) - const view = mountStart() - await act(async () => { - expect(await view.result.current.startWithDetectedAgents({ detectedAgents: ['codex'] })).toBe( - false - ) - }) - expect(mocks.toastError).toHaveBeenCalledExactlyOnceWith( - 'Impossible de démarrer une nouvelle session Codex.', - { - description: - 'Impossible de lire la pull request. Vérifiez que vous pouvez l’ouvrir, puis réessayez.' - } - ) - expect(mocks.createWorktree).not.toHaveBeenCalled() - } finally { - await i18n.changeLanguage(language) - } -}) - -it('Start work reports one truthful recovery before a remote agent has been selected', async () => { - const environment = publicRuntimeEnvironment({ - id: 'hub-a', - pairingRevision: 1, - runtimeId: 'hub-runtime' - }) - replaceRuntimeEnvironmentRevisions([environment]) - try { - const state = useAppStore.getState() - useAppStore.setState({ - repos: [{ ...state.repos[0], path: '/srv/repo', executionHostId: 'runtime:hub-a' }], - settings: { ...getDefaultSettings('/tmp'), defaultTuiAgent: 'claude' }, - runtimeEnvironments: [environment], - runtimeDetectedAgentIds: { [getRuntimeAgentInventoryKey('hub-a')]: ['codex'] }, - runtimeStatusByEnvironmentId: new Map([ - [ - 'hub-a', - runtimeEnvironmentStatusFromSnapshot({ - environmentId: 'hub-a', - pairingRevision: 1, - sequence: 1, - checkedAt: 1, - status: connectedRuntimeStatus('hub-runtime', 1).status, - verification: 'verified', - transport: 'ready' - }) - ] - ]) - }) - const preferences = resource({ - environmentId: 'hub-a', - pairingRevision: 1, - runtimeId: 'hub-runtime' - }) - preferences.snapshot = { defaultTuiAgent: 'codex', disabledTuiAgents: [] } - expect( - readAgentLaunchPreferencesForWorkspace(useAppStore.getState(), { - kind: 'git-worktree', - repoId: 'repo-1', - executionHostId: 'runtime:hub-a' - }).defaultTuiAgent - ).toBe('codex') - const table = projectRelationsTableFixture() - const row = table.rows[0] - row.content.url = 'https://github.com/acme/repo/issues/1' - const view = renderHook(() => - useProjectRowActions({ - table, - currentCacheKey: 'project-key', - selectedRepoIds: new Set(['repo-1']) - }) - ) - await act(async () => view.result.current.startWork(row)) - expect(mocks.toastError).toHaveBeenCalledExactlyOnceWith( - 'Update Orca on this workspace’s server, then try again.' - ) - expect(mocks.createWorktree).not.toHaveBeenCalled() - expect(hostMocks.callRuntimeRpc).not.toHaveBeenCalled() - expect(mocks.ensureDetectedAgents).not.toHaveBeenCalled() - expect(mocks.ensureRemoteDetectedAgents).not.toHaveBeenCalled() - } finally { - clearHostAgentMenuSettingsForTests() - replaceRuntimeEnvironmentRevisions([]) - } -}) diff --git a/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-agent-routing.ts b/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-agent-routing.ts index 61cde6a3158..ecc64b68cb2 100644 --- a/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-agent-routing.ts +++ b/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-agent-routing.ts @@ -11,7 +11,7 @@ import { buildDirectWorkItemAgentStartupPlan, notifyDirectWorkItemAgentStartTimeout } from '@/lib/workspace/creation/work-item/launch-work-item-direct-agent' -import { acquireAgentLaunchChoices } from '../../../host-chat-program-acquisition' +import { acquireAgentLaunchChoices } from '../../../agent-session/launch/inventory/host-chat-program-acquisition' import { useAppStore } from '@/store/index' import type { TuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent' import type { AppState } from '@/store/types' @@ -19,7 +19,7 @@ import { isTuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-ag import { isTuiAgentEnabled } from '../../../../../../shared/agent-launch/catalog/tui-agent-selection' import { resolveDefaultAgentForWorkspace } from '../../../agent-session/launch/shortcuts/agent-tab-shortcuts' import { worktreeLaunchWorkspace } from '@/lib/agent-session/launch/routing/agent-launch-route-input' -import { agentChoiceMayOpenAsChat } from '@/lib/host-chat-program' +import { agentChoiceMayOpenAsChat } from '@/lib/agent-session/launch/inventory/host-chat-program' import type { AgentSessionLaunchPlan } from '@/lib/agent-session/launch/routing/agent-session-launch-plan' import { resolveExecutionHostAgentStartupShell, diff --git a/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-draft.ts b/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-draft.ts index ae04885b4c9..59706492aa3 100644 --- a/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-draft.ts +++ b/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-draft.ts @@ -3,7 +3,7 @@ import { getWorkspaceIntentName, getLinearIssueWorkspaceName } from '../../../../../../shared/workspace-name' -import { getWorkspaceSeedName } from '@/lib/new-workspace' +import { getWorkspaceSeedName } from '@/lib/workspace/creation/new-workspace' import type { LaunchableWorkItem } from '@/lib/workspace/creation/work-item/launch-work-item-direct-types' export function getDirectWorkItemWorkspaceNames( diff --git a/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-messages.ts b/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-messages.ts index bc6396ca4b1..e3c20b82b13 100644 --- a/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-messages.ts +++ b/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-messages.ts @@ -7,7 +7,7 @@ import { import { getAgentLabel } from '../../../agent-catalog/agent-catalog' import type { TuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent' -import '@/lib/new-workspace' +import '@/lib/workspace/creation/new-workspace' import { isGitLabIssueUrl } from '../../../../../../shared/new-workspace/workspace-source' import { translate } from '@/i18n/i18n' diff --git a/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-preflight.ts b/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-preflight.ts index ca78c949d90..f28b5b52b58 100644 --- a/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-preflight.ts +++ b/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-preflight.ts @@ -11,7 +11,7 @@ import { ensureDetectedAgentsForRepo, loadProjectLaunchContext } from '../../../agent-session/launch/inventory/agent-detection-target-inventory' -import { CLIENT_PLATFORM } from '../../../new-workspace' +import { CLIENT_PLATFORM } from '../new-workspace' import { getLocalRepoProjectExecutionRuntimeContext } from '../../../local-preflight-context' import { refineLocalLaunchPlatform, diff --git a/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-route-preparation.ts b/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-route-preparation.ts index 8cfd7c1b835..4960b1df65c 100644 --- a/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-route-preparation.ts +++ b/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-route-preparation.ts @@ -9,7 +9,7 @@ import { resolveRepoExecutionHostPlatform, type KnownExecutionHostPlatform } from '@/runtime/hosts/platform/execution-host-facts' -import { CLIENT_PLATFORM } from '@/lib/new-workspace' +import { CLIENT_PLATFORM } from '@/lib/workspace/creation/new-workspace' import { getLocalProjectExecutionRuntimeContext } from '@/lib/local-preflight-context' import { resolveLocalWindowsTerminalShellOverrideForTab } from '../../../../../../shared/local-windows-terminal-runtime' import { isWslUncPath } from '../../../../../../shared/wsl-paths' diff --git a/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-setup.test.tsx b/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-setup.test.tsx index 8d8e5ce69b5..5ecc1b4bf8f 100644 --- a/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-setup.test.tsx +++ b/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-setup.test.tsx @@ -3,15 +3,14 @@ import { hostMocks, mocks } from './launch-work-item-direct-test-fixture' import { readDirectSetupRequest } from '@/lib/workspace/creation/work-item/direct-work-item-setup-test-fixture' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' -import * as preflight from './launch-work-item-direct-preflight' -import * as inventory from '../../../agent-session/launch/inventory/agent-detection-target-inventory' import { useAppStore } from '@/store/index' import { createUIStore } from '@/store/slices/ui/ui-slice-test-harness' -vi.doUnmock('@/lib/ensure-hooks-confirmed') +vi.doUnmock('@/runtime/repo-hooks/ensure-hooks-confirmed') const { launchWorkItemDirect } = await import('./launch-work-item-direct') -const { __resetTrustPromptChainForTests } = await import('../../../ensure-hooks-confirmed') +const { __resetTrustPromptChainForTests } = + await import('../../../../runtime/repo-hooks/ensure-hooks-confirmed') const { DirectWorkItemSetupDialog } = await import('@/components/new-workspace/DirectWorkItemSetupDialog') @@ -62,30 +61,6 @@ describe('direct work item setup preparation', () => { unsubscribe() }) - it.each(['absent', 'error', 'malformed', 'rejection'] as const)( - 'cancels during initial inspection before consuming its late %s outcome', - async (shape) => { - const abort = new AbortController() - const read = Promise.withResolvers<{ hasHooks: boolean; hooks: null; status?: 'error' }>() - hostMocks.checkRuntimeHooks.mockReturnValueOnce(read.promise) - const launch = launchWorkItemDirect({ ...args, signal: abort.signal }) - abort.abort() - if (shape === 'rejection') { - read.reject(new Error('late inspection failure')) - } else { - read.resolve({ - hasHooks: shape === 'malformed', - hooks: null, - ...(shape === 'error' ? { status: 'error' } : {}) - }) - } - await expect(launch).resolves.toBe('cancelled') - expect(mocks.createWorktree).not.toHaveBeenCalled() - expect(mocks.toastError).not.toHaveBeenCalled() - expect(args.openModalFallback).not.toHaveBeenCalled() - } - ) - async function chooseSetup(): Promise { await vi.waitFor(() => expect(useAppStore.getState().activeModal).toBe('new-workspace-composer') @@ -93,57 +68,6 @@ describe('direct work item setup preparation', () => { readDirectSetupRequest(useAppStore.getState().modalData.directSetup).choose('run') } - it.each(['pr', 'project', 'detection', 'plan'] as const)( - 'suppresses a late cancelled %s rejection through the original launch', - async (stage) => { - const gate = Promise.withResolvers() - const abort = new AbortController() - let reached: () => boolean - switch (stage) { - case 'pr': - mocks.resolvePrBase.mockReturnValueOnce(gate.promise) - reached = () => mocks.resolvePrBase.mock.calls.length > 0 - break - case 'project': { - const read = vi - .spyOn(inventory, 'loadProjectLaunchContext') - .mockReturnValueOnce(gate.promise) - reached = () => read.mock.calls.length > 0 - break - } - case 'detection': { - const detect = vi - .spyOn(preflight, 'resolveDirectProspectiveAgent') - .mockReturnValueOnce(gate.promise) - reached = () => detect.mock.calls.length > 0 - break - } - case 'plan': { - const plan = vi - .spyOn(preflight, 'planDirectWorkItemLaunch') - .mockReturnValueOnce(gate.promise) - reached = () => plan.mock.calls.length > 0 - break - } - } - hostMocks.checkRuntimeHooks.mockResolvedValue({ hasHooks: true, hooks }) - const launch = launchWorkItemDirect({ - ...args, - signal: abort.signal, - item: { ...args.item, type: 'pr', url: 'https://github.com/acme/repo/pull/42' } - }) - await chooseSetup() - await vi.waitFor(() => expect(reached()).toBe(true)) - abort.abort() - gate.reject(new Error('late preparation failed')) - await expect(launch).resolves.toBe('cancelled') - expect(mocks.toastError).not.toHaveBeenCalled() - expect(args.openModalFallback).not.toHaveBeenCalled() - expect(mocks.pasteDraftWhenAgentReady).not.toHaveBeenCalled() - expect(mocks.createWorktree).not.toHaveBeenCalled() - } - ) - it('aborts the actual trust prompt, releases its queue, and permits a fresh launch', async () => { useAppStore.setState({ trustedOrcaHooks: {} }) hostMocks.checkRuntimeHooks.mockResolvedValue({ hasHooks: true, hooks }) diff --git a/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-test-fixture.ts b/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-test-fixture.ts index af9479f7fff..05ece91b4cb 100644 --- a/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-test-fixture.ts +++ b/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-test-fixture.ts @@ -86,7 +86,7 @@ vi.mock('@/lib/workspace/activation/worktree-activation', () => ({ activateAndRevealWorktree: mocks.activateAndRevealWorktree })) -vi.mock('@/lib/ensure-hooks-confirmed', () => ({ +vi.mock('@/runtime/repo-hooks/ensure-hooks-confirmed', () => ({ ensureHooksConfirmed: vi.fn().mockResolvedValue('run'), ensureHooksApproved: vi.fn().mockResolvedValue({ decision: 'run' }) })) @@ -121,7 +121,7 @@ vi.mock('@/runtime/rpc/subscriptions/runtime-rpc-subscribe', () => ({ subscribeRuntimeRpc: hostMocks.subscribe })) -vi.mock('@/lib/new-workspace', () => ({ +vi.mock('@/lib/workspace/creation/new-workspace', () => ({ CLIENT_PLATFORM: 'win32', getWorkspaceSeedName: ({ explicitName }: { explicitName?: string }) => explicitName ?? '' })) diff --git a/src/renderer/src/lib/workspace-composer-initial-focus.ts b/src/renderer/src/lib/workspace/creation/workspace-composer-initial-focus.ts similarity index 100% rename from src/renderer/src/lib/workspace-composer-initial-focus.ts rename to src/renderer/src/lib/workspace/creation/workspace-composer-initial-focus.ts diff --git a/src/renderer/src/lib/workspace-create-error-format.ts b/src/renderer/src/lib/workspace/creation/workspace-create-error-format.ts similarity index 100% rename from src/renderer/src/lib/workspace-create-error-format.ts rename to src/renderer/src/lib/workspace/creation/workspace-create-error-format.ts diff --git a/src/renderer/src/lib/workspace/creation/worktree-creation-agent-seeds.ts b/src/renderer/src/lib/workspace/creation/worktree-creation-agent-seeds.ts index aa03f067bc2..fc83c0f8355 100644 --- a/src/renderer/src/lib/workspace/creation/worktree-creation-agent-seeds.ts +++ b/src/renderer/src/lib/workspace/creation/worktree-creation-agent-seeds.ts @@ -1,7 +1,7 @@ import { useAppStore } from '@/store/index' import { seedNativeChatAppliedSessionOptions } from '../../../../../shared/native-chat/input/native-chat-session-option-cache' import { seedNativeChatLaunchDraftForAgentTab } from '@/lib/agent-session/launch/prompt/agent-launch-prompt-delivery' -import { queueHookCommandsForFirstWorktreeTab } from '@/lib/hook-command-delayed-delivery' +import { queueHookCommandsForFirstWorktreeTab } from '@/lib/workspace/creation/setup/hook-command-delayed-delivery' import { runtimeEnvironmentIdOrLocalUnlessTwin } from '@/lib/workspace/ownership/worktree-runtime-owner' import { toWebTerminalSurfaceTabId } from '../../../../../shared/workspace-layout/terminal-surface-id' import type { WorktreeCreationRequest } from '@/lib/workspace/creation/pending-worktree-creation' diff --git a/src/renderer/src/lib/workspace/creation/worktree-creation-completion.ts b/src/renderer/src/lib/workspace/creation/worktree-creation-completion.ts index 87579aeeca0..d152a0b57c5 100644 --- a/src/renderer/src/lib/workspace/creation/worktree-creation-completion.ts +++ b/src/renderer/src/lib/workspace/creation/worktree-creation-completion.ts @@ -2,7 +2,7 @@ import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-ag import { parseExecutionHostId } from '../../../../../shared/execution-host' import { runtimeEnvironmentIdOrLocalUnlessTwin } from '@/lib/workspace/ownership/worktree-runtime-owner' import { useAppStore } from '@/store/index' -import { ensureAgentStartupInTerminal } from '@/lib/new-workspace' +import { ensureAgentStartupInTerminal } from '@/lib/workspace/creation/new-workspace' import { queueWorkspaceActivationTerminalFocus } from '@/lib/workspace/activation/workspace-activation-terminal-focus' import { seedAgentTabStateAfterWorktreeCreate } from '@/lib/workspace/creation/worktree-creation-agent-seeds' import type { ActivateAndRevealResult } from '@/lib/workspace/activation/worktree-activation-outcome' diff --git a/src/renderer/src/lib/workspace/creation/worktree-creation-flow-execute.ts b/src/renderer/src/lib/workspace/creation/worktree-creation-flow-execute.ts index 23955624b38..7a0a9ee9dc9 100644 --- a/src/renderer/src/lib/workspace/creation/worktree-creation-flow-execute.ts +++ b/src/renderer/src/lib/workspace/creation/worktree-creation-flow-execute.ts @@ -7,13 +7,13 @@ import { attachEphemeralVmRuntimeToWorkspace, cleanupEphemeralVmRuntimeForFailedCreate, prepareRequestForCreate -} from '@/lib/ephemeral-vm-worktree-creation' -import { getProvisionedRootCreateOptions } from '@/lib/provisioned-root-create-options' -import { releaseVmCreateCheckout } from '@/lib/vm-create-hidden-checkouts' +} from '@/lib/workspace/creation/ephemeral-vm-worktree-creation' +import { getProvisionedRootCreateOptions } from '@/lib/workspace/creation/provisioned-root-create-options' +import { releaseVmCreateCheckout } from '@/runtime/ephemeral-vm/vm-create-hidden-checkouts' import { formatWorkspaceCreateError, getWorkspaceCreateErrorToastMessage -} from '@/lib/workspace-create-error-format' +} from '@/lib/workspace/creation/workspace-create-error-format' import type { CreatedWorktreeResult } from '@/store/slices/worktrees/create/worktree-create-payload' import type { WorktreeCreationRequest } from '@/lib/workspace/creation/pending-worktree-creation' import { resolveBackendDraftStartup } from '@/lib/workspace/creation/worktree-draft-startup-view-mode' diff --git a/src/renderer/src/lib/workspace/creation/worktree-creation-flow.ts b/src/renderer/src/lib/workspace/creation/worktree-creation-flow.ts index ec144b00f0f..1df1bd2e86f 100644 --- a/src/renderer/src/lib/workspace/creation/worktree-creation-flow.ts +++ b/src/renderer/src/lib/workspace/creation/worktree-creation-flow.ts @@ -20,7 +20,7 @@ import { import { formatWorkspaceCreateError, getWorkspaceCreateErrorToastMessage -} from '@/lib/workspace-create-error-format' +} from '@/lib/workspace/creation/workspace-create-error-format' type ContinueBackgroundWorktreeCreationOptions = { revealCreationSurface?: boolean diff --git a/src/renderer/src/lib/workspace/creation/worktree-creation-hook-preparation.ts b/src/renderer/src/lib/workspace/creation/worktree-creation-hook-preparation.ts index 9a733dcdef2..e72fec54e3f 100644 --- a/src/renderer/src/lib/workspace/creation/worktree-creation-hook-preparation.ts +++ b/src/renderer/src/lib/workspace/creation/worktree-creation-hook-preparation.ts @@ -7,9 +7,9 @@ import type { WorktreeCreationRequest } from './pending-worktree-creation' import { ensureHooksConfirmed, readAndConfirmRuntimeIssueCommand -} from '../../ensure-hooks-confirmed' -import { confirmWorkspaceSetupDecision } from '../../workspace-setup-trust' -import { buildTrustedComposerIssueCommand } from '../../composer-issue-command' +} from '../../../runtime/repo-hooks/ensure-hooks-confirmed' +import { confirmWorkspaceSetupDecision } from './setup/workspace-setup-trust' +import { buildTrustedComposerIssueCommand } from './composer-issue-command' import { getInitialWorktreeCreationPhase } from './worktree-creation-flow-startup' export async function prepareWorktreeCreationHooks( diff --git a/src/renderer/src/lib/ephemeral-vm-environment-check-decision.ts b/src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-environment-check-decision.ts similarity index 100% rename from src/renderer/src/lib/ephemeral-vm-environment-check-decision.ts rename to src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-environment-check-decision.ts diff --git a/src/renderer/src/lib/ephemeral-vm-environment-check.test.ts b/src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-environment-check.test.ts similarity index 97% rename from src/renderer/src/lib/ephemeral-vm-environment-check.test.ts rename to src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-environment-check.test.ts index b4af3b7f4c9..95fcda5e62a 100644 --- a/src/renderer/src/lib/ephemeral-vm-environment-check.test.ts +++ b/src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-environment-check.test.ts @@ -19,7 +19,7 @@ const { callRuntimeRpc, supportsCapability, store } = vi.hoisted(() => { } }) -vi.mock('@/store', () => ({ useAppStore: { getState: store.getState } })) +vi.mock('@/store/index', () => ({ useAppStore: { getState: store.getState } })) vi.mock('sonner', () => ({ toast: { error: vi.fn(), warning: vi.fn() } })) vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ callRuntimeRpc })) vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', () => ({ diff --git a/src/renderer/src/lib/ephemeral-vm-environment-check.ts b/src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-environment-check.ts similarity index 96% rename from src/renderer/src/lib/ephemeral-vm-environment-check.ts rename to src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-environment-check.ts index e63b79b2680..647976eb0f2 100644 --- a/src/renderer/src/lib/ephemeral-vm-environment-check.ts +++ b/src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-environment-check.ts @@ -1,16 +1,16 @@ import { toast } from 'sonner' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { translate } from '@/i18n/i18n' import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' import { runtimeEnvironmentSupportsCapability } from '@/runtime/rpc/compatibility/runtime-capability-proof' import type { EnvironmentDoctorCheck, EnvironmentDoctorResult -} from '../../../shared/environment-doctor-types' +} from '../../../../shared/environment-doctor-types' import { ENVIRONMENT_DOCTOR_METHOD, ENVIRONMENT_DOCTOR_RUNTIME_CAPABILITY -} from '../../../shared/environment-doctor-runtime' +} from '../../../../shared/environment-doctor-runtime' import { awaitVmEnvironmentCheckDecision, beginVmEnvironmentCheckRun, diff --git a/src/renderer/src/lib/ephemeral-vm-error-copy.ts b/src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-error-copy.ts similarity index 97% rename from src/renderer/src/lib/ephemeral-vm-error-copy.ts rename to src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-error-copy.ts index 6e169290cad..e098ab7b24b 100644 --- a/src/renderer/src/lib/ephemeral-vm-error-copy.ts +++ b/src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-error-copy.ts @@ -3,8 +3,8 @@ import { EPHEMERAL_VM_FAILURE_COPY as EN, type EphemeralVmFailure, type EphemeralVmFailureCode -} from '../../../shared/ephemeral-vm-failure-copy' -import type { EphemeralVmRuntimeRecord } from '../../../shared/ephemeral-vm-runtimes' +} from '../../../../shared/ephemeral-vm-failure-copy' +import type { EphemeralVmRuntimeRecord } from '../../../../shared/ephemeral-vm-runtimes' type Params = Record diff --git a/src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.ts b/src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-failed-create-cleanup.ts similarity index 95% rename from src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.ts rename to src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-failed-create-cleanup.ts index 0c517c440b9..9e6ef721a71 100644 --- a/src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.ts +++ b/src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-failed-create-cleanup.ts @@ -1,5 +1,5 @@ import type { WorktreeCreationRequest } from '@/lib/workspace/creation/pending-worktree-creation' -import type { ExecutionHostId } from '../../../shared/execution-host' +import type { ExecutionHostId } from '../../../../shared/execution-host' type FailedCreateCleanupActions = { deleteProjectHostSetup: (setupId: string, hostId: ExecutionHostId) => Promise diff --git a/src/renderer/src/lib/ephemeral-vm-runtime-cleanup.ts b/src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-runtime-cleanup.ts similarity index 96% rename from src/renderer/src/lib/ephemeral-vm-runtime-cleanup.ts rename to src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-runtime-cleanup.ts index e8994722b85..67137546265 100644 --- a/src/renderer/src/lib/ephemeral-vm-runtime-cleanup.ts +++ b/src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-runtime-cleanup.ts @@ -3,8 +3,8 @@ import { toRuntimeExecutionHostId, toSshExecutionHostId, type ExecutionHostId -} from '../../../shared/execution-host' -import { composeWorktreeHostIdentity } from '../../../shared/worktree/host-qualified-identity' +} from '../../../../shared/execution-host' +import { composeWorktreeHostIdentity } from '../../../../shared/worktree/host-qualified-identity' import { refreshRuntimeEnvironmentCatalog } from '@/runtime/rpc/environment-revisions/runtime-environment-pairing-refresh' /** Destroy runtimes for removed workspaces and runtime-owned SSH targets. Share with project removal because SSH-mode main worktrees delete through that path; classify targets so callers purge only confirmed destruction. */ diff --git a/src/renderer/src/lib/ephemeral-vm-workspace-target.ts b/src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-workspace-target.ts similarity index 92% rename from src/renderer/src/lib/ephemeral-vm-workspace-target.ts rename to src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-workspace-target.ts index a735b615577..f2c77750b28 100644 --- a/src/renderer/src/lib/ephemeral-vm-workspace-target.ts +++ b/src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-workspace-target.ts @@ -2,22 +2,23 @@ import { toRuntimeExecutionHostId, toSshExecutionHostId, type ExecutionHostId -} from '../../../shared/execution-host' +} from '../../../../shared/execution-host' import type { ProjectHostSetupExistingFolderArgs, ProjectHostSetupResult -} from '../../../shared/project-types' +} from '../../../../shared/project-types' import { getEphemeralVmRecipeResultCheckoutMode, getEphemeralVmRecipeResultProjectRoot -} from '../../../shared/ephemeral-vm-recipes' -import type { EphemeralVmRecipeResultWarning } from '../../../shared/ephemeral-vm-recipe-diagnostics' +} from '../../../../shared/ephemeral-vm-recipes' +import type { EphemeralVmRecipeResultWarning } from '../../../../shared/ephemeral-vm-recipe-diagnostics' +import '../../../../shared/protocol-version' import { PROJECT_HOST_SETUP_RUNTIME_CAPABILITY, WORKTREE_PROVISIONED_ROOT_RUNTIME_CAPABILITY -} from '../../../shared/protocol-version' +} from '../../../../shared/worktree-runtime-capabilities' import { translate } from '@/i18n/i18n' -import { ephemeralVmErrorText } from '@/lib/ephemeral-vm-error-copy' +import { ephemeralVmErrorText } from '@/runtime/ephemeral-vm/ephemeral-vm-error-copy' import { assertRuntimeEnvironmentCapability } from '@/runtime/rpc/compatibility/runtime-capability-proof' export type PrepareEphemeralVmWorkspaceTargetArgs = { diff --git a/src/renderer/src/lib/recipe-vm-managed-host.ts b/src/renderer/src/runtime/ephemeral-vm/recipe-vm-managed-host.ts similarity index 87% rename from src/renderer/src/lib/recipe-vm-managed-host.ts rename to src/renderer/src/runtime/ephemeral-vm/recipe-vm-managed-host.ts index b2e85db0770..73e60ce03b4 100644 --- a/src/renderer/src/lib/recipe-vm-managed-host.ts +++ b/src/renderer/src/runtime/ephemeral-vm/recipe-vm-managed-host.ts @@ -1,8 +1,8 @@ -import { isRuntimeOwnedSshTargetId, parseExecutionHostId } from '../../../shared/execution-host' +import { isRuntimeOwnedSshTargetId, parseExecutionHostId } from '../../../../shared/execution-host' import { getManagedOrcadSshTargetId, type ManagedOrcadEnvironmentSummary -} from '../../../shared/execution-host/managed-orcad-execution-host' +} from '../../../../shared/execution-host/managed-orcad-execution-host' /** The hidden SSH target of the recipe VM whose managed server is `hostId`, or null. */ export function getRecipeVmSshTargetForHost( diff --git a/src/renderer/src/lib/vm-create-hidden-checkouts.test.ts b/src/renderer/src/runtime/ephemeral-vm/vm-create-hidden-checkouts.test.ts similarity index 94% rename from src/renderer/src/lib/vm-create-hidden-checkouts.test.ts rename to src/renderer/src/runtime/ephemeral-vm/vm-create-hidden-checkouts.test.ts index d56214a7ef6..1f87b210c4a 100644 --- a/src/renderer/src/lib/vm-create-hidden-checkouts.test.ts +++ b/src/renderer/src/runtime/ephemeral-vm/vm-create-hidden-checkouts.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { EMPTY_SIDEBAR_FEED_DOMAINS } from '../../../shared/sidebar-feed-client/sidebar-feed-snapshot' -import type { SidebarFeedDomains } from '../../../shared/sidebar-list/sidebar-feed-domains' +import { EMPTY_SIDEBAR_FEED_DOMAINS } from '../../../../shared/sidebar-feed-client/sidebar-feed-snapshot' +import type { SidebarFeedDomains } from '../../../../shared/sidebar-list/sidebar-feed-domains' import { hideVmCreateCheckout, readHiddenVmCheckouts, diff --git a/src/renderer/src/lib/vm-create-hidden-checkouts.ts b/src/renderer/src/runtime/ephemeral-vm/vm-create-hidden-checkouts.ts similarity index 87% rename from src/renderer/src/lib/vm-create-hidden-checkouts.ts rename to src/renderer/src/runtime/ephemeral-vm/vm-create-hidden-checkouts.ts index 6faf4a20a90..6942bd1c4c7 100644 --- a/src/renderer/src/lib/vm-create-hidden-checkouts.ts +++ b/src/renderer/src/runtime/ephemeral-vm/vm-create-hidden-checkouts.ts @@ -1,30 +1,25 @@ -import type { SidebarFeedDomains } from '../../../shared/sidebar-list/sidebar-feed-domains' +import type { SidebarFeedDomains } from '../../../../shared/sidebar-list/sidebar-feed-domains' import { indexPendingVmCheckouts, isPendingVmCheckout, type PendingVmCheckout, type PendingVmCheckoutIndex -} from '../../../shared/pending-vm-checkouts' +} from '../../../../shared/pending-vm-checkouts' -/** A VM's primary checkout, registered on its host before the create that owns it finishes. */ -export type HiddenVmCheckout = PendingVmCheckout type CheckoutRow = { repoId: string; path: string; isMainWorktree?: boolean } -/** What lists filter by: this window's pending VM checkouts and every other window's. */ -export type HiddenVmCheckouts = PendingVmCheckoutIndex - // Upper bound for a cleaned-up VM's rows to leave the lists (its host is retired asynchronously). const HIDDEN_AFTER_CLEANUP_MS = 60_000 // Keyed per hide, not per creation: a retry re-provisions under the same creation id while the // previous attempt's cleaned-up VM may still be listed. -let hides = new Map() +let hides = new Map() const activeHideByCreation = new Map() const cleanedHides = new Set() let nextHideId = 1 /** The other windows' sets as main last sent them; this window's own live in `hides`. */ -let otherWindows: HiddenVmCheckout[] = [] -let hidden: HiddenVmCheckouts = indexPendingVmCheckouts([]) +let otherWindows: PendingVmCheckout[] = [] +let hidden: PendingVmCheckoutIndex = indexPendingVmCheckouts([]) let detachMain: (() => void) | null = null const listeners = new Set<() => void>() @@ -41,7 +36,7 @@ function republish(): void { listeners.forEach((listener) => listener()) } -function publish(next: Map): void { +function publish(next: Map): void { hides = next // Main holds the source of truth for other windows and the paired phone's host lists. if (typeof window !== 'undefined') { @@ -86,7 +81,7 @@ function removeHide(hideId: number): void { * Why: a VM create registers the VM's project before its checks run and before the checkout is * adopted or a worktree is made; the pending row stands for it until the create finishes. */ -export function hideVmCreateCheckout(creationId: string, checkout: HiddenVmCheckout): void { +export function hideVmCreateCheckout(creationId: string, checkout: PendingVmCheckout): void { const hideId = nextHideId++ activeHideByCreation.set(creationId, hideId) publish(new Map(hides).set(hideId, { repoId: checkout.repoId, path: checkout.path })) @@ -127,14 +122,14 @@ export function subscribeHiddenVmCheckouts(listener: () => void): () => void { return () => listeners.delete(listener) } -export function readHiddenVmCheckouts(): HiddenVmCheckouts { +export function readHiddenVmCheckouts(): PendingVmCheckoutIndex { return hidden } /** The window's sidebar list without the primary checkouts of VMs whose creates are in progress. */ export function withoutHiddenVmWorktrees( worktrees: W[], - checkouts: HiddenVmCheckouts + checkouts: PendingVmCheckoutIndex ): W[] { if (checkouts.keys.size === 0) { return worktrees @@ -146,7 +141,7 @@ export function withoutHiddenVmWorktrees( /** Per-repo lists without pending VM checkouts; the same object when nothing matches. */ export function withoutHiddenVmWorktreesByRepo( worktreesByRepo: Record, - checkouts: HiddenVmCheckouts + checkouts: PendingVmCheckoutIndex ): Record { if (checkouts.keys.size === 0) { return worktreesByRepo @@ -168,7 +163,7 @@ export function withoutHiddenVmWorktreesByRepo( function withoutHiddenRows( rows: ReadonlyMap, - checkouts: HiddenVmCheckouts + checkouts: PendingVmCheckoutIndex ): ReadonlyMap { let kept: Map | null = null for (const [key, row] of rows) { @@ -183,7 +178,7 @@ function withoutHiddenRows( /** Main's rows without the primary checkouts of VMs whose creates are still in progress. */ export function withoutHiddenVmCheckouts( domains: SidebarFeedDomains, - checkouts: HiddenVmCheckouts + checkouts: PendingVmCheckoutIndex ): SidebarFeedDomains { if (checkouts.keys.size === 0) { return domains diff --git a/src/renderer/src/runtime/hosted-terminals/creation/agent-launch/web-runtime-agent-launch-options.test-fixture.ts b/src/renderer/src/runtime/hosted-terminals/creation/agent-launch/web-runtime-agent-launch-options.test-fixture.ts index 5c4d1a624bb..68b463d876e 100644 --- a/src/renderer/src/runtime/hosted-terminals/creation/agent-launch/web-runtime-agent-launch-options.test-fixture.ts +++ b/src/renderer/src/runtime/hosted-terminals/creation/agent-launch/web-runtime-agent-launch-options.test-fixture.ts @@ -78,8 +78,10 @@ vi.mock('@/hooks/useAgentDetectionTarget', () => ({ useAgentDetectionTargetForWorktree: () => null })) vi.mock('@/components/agent/AgentLaunchPicker', () => ({ AgentLaunchPicker: mocks.picker })) -vi.mock('@/lib/host-chat-program', () => ({ agentsOfferedForLaunch: () => ['claude'] })) -vi.mock('@/lib/host-chat-program-acquisition', () => ({ +vi.mock('@/lib/agent-session/launch/inventory/host-chat-program', () => ({ + agentsOfferedForLaunch: () => ['claude'] +})) +vi.mock('@/lib/agent-session/launch/inventory/host-chat-program-acquisition', () => ({ acquireAgentLaunchChoices: async () => ({ detected: ['claude'], offered: ['claude'] }) })) vi.mock('@/lib/agent-session/launch/new-tab/launch-agent-in-new-tab', () => ({ diff --git a/src/renderer/src/runtime/hosts/platform/execution-host-facts.test.ts b/src/renderer/src/runtime/hosts/platform/execution-host-facts.test.ts index 4c275b4845b..d8a7c8f3783 100644 --- a/src/renderer/src/runtime/hosts/platform/execution-host-facts.test.ts +++ b/src/renderer/src/runtime/hosts/platform/execution-host-facts.test.ts @@ -6,7 +6,7 @@ import { } from './execution-host-facts' import { getDefaultSettings } from '../../../../../shared/constants' -vi.mock('../../../lib/new-workspace', async (importOriginal) => ({ +vi.mock('../../../lib/workspace/creation/new-workspace', async (importOriginal) => ({ ...(await importOriginal>()), CLIENT_PLATFORM: 'win32' })) diff --git a/src/renderer/src/runtime/hosts/platform/execution-host-facts.ts b/src/renderer/src/runtime/hosts/platform/execution-host-facts.ts index 571d56746ea..bf2f6717ead 100644 --- a/src/renderer/src/runtime/hosts/platform/execution-host-facts.ts +++ b/src/renderer/src/runtime/hosts/platform/execution-host-facts.ts @@ -16,7 +16,7 @@ import { getConnectionIdFromState } from '../../../lib/workspace/ownership/connection-owner-resolution' import { getLocalProjectExecutionRuntimeContext } from '../../../lib/local-preflight-context' -import { CLIENT_PLATFORM } from '../../../lib/new-workspace' +import { CLIENT_PLATFORM } from '../../../lib/workspace/creation/new-workspace' import { getExecutionHostIdForWorktree, getResourceExecutionHostIdForWorktree, diff --git a/src/renderer/src/lib/ensure-hooks-confirmed.test.ts b/src/renderer/src/runtime/repo-hooks/ensure-hooks-confirmed.test.ts similarity index 98% rename from src/renderer/src/lib/ensure-hooks-confirmed.test.ts rename to src/renderer/src/runtime/repo-hooks/ensure-hooks-confirmed.test.ts index af75f28eec6..81048c4f31c 100644 --- a/src/renderer/src/lib/ensure-hooks-confirmed.test.ts +++ b/src/renderer/src/runtime/repo-hooks/ensure-hooks-confirmed.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { AppState } from '@/store/types' -import type { PersistedTrustedOrcaHooks } from '../../../shared/orca-yaml-hook-types' +import type { PersistedTrustedOrcaHooks } from '../../../../shared/orca-yaml-hook-types' import { __resetTrustPromptChainForTests, confirmCreatedWorktreeSetupContent, diff --git a/src/renderer/src/lib/ensure-hooks-confirmed.ts b/src/renderer/src/runtime/repo-hooks/ensure-hooks-confirmed.ts similarity index 95% rename from src/renderer/src/lib/ensure-hooks-confirmed.ts rename to src/renderer/src/runtime/repo-hooks/ensure-hooks-confirmed.ts index b0974dddf65..e4c4c9bc37e 100644 --- a/src/renderer/src/lib/ensure-hooks-confirmed.ts +++ b/src/renderer/src/runtime/repo-hooks/ensure-hooks-confirmed.ts @@ -1,12 +1,13 @@ import type { AppState } from '@/store/types' -import type { OrcaHooks } from '../../../shared/orca-yaml-hook-types' -import { resolveHookCommandSourcePolicy } from '../../../shared/hook-command-source-policy' -import { getSetupTrustContent } from '../../../shared/orca-hook-setup-config' +import type { OrcaHooks } from '../../../../shared/orca-yaml-hook-types' +import { resolveHookCommandSourcePolicy } from '../../../../shared/hook-command-source-policy' +import { getSetupTrustContent } from '../../../../shared/orca-hook-setup-config' import { canUseRepoWideTrust, isOrcaHookContentApproved -} from '../../../shared/orca-hook-trust-entries' -import { hashOrcaHookScript, type OrcaHookScriptKind } from './orca-hook-trust' +} from '../../../../shared/orca-hook-trust-entries' +import { hashOrcaHookScript } from './orca-hook-trust' +import type { OrcaHookTrustKind } from '../../../../shared/orca-hook-trust-entries' import { getVmRecipeTrustContent } from './vm-recipe-trust-content' import { getIssueCommandTrustContent, isUserOwnedIssueCommand } from './issue-command-trust-content' import { @@ -19,9 +20,7 @@ import { getRepoExecutionHostId, toRuntimeExecutionHostId, type ExecutionHostId -} from '../../../shared/execution-host' - -export type HookScriptKind = OrcaHookScriptKind +} from '../../../../shared/execution-host' const NEVER_CANCEL_TRUST_CHECK = (): boolean => false @@ -77,7 +76,7 @@ const RUN_ANY: HookTrustApproval = { decision: 'run' } async function confirmScriptContent( state: AppState, repoId: string, - scriptKind: HookScriptKind, + scriptKind: OrcaHookTrustKind, scriptContent: string, hostId?: ExecutionHostId, isCancelled: () => boolean = NEVER_CANCEL_TRUST_CHECK, @@ -257,7 +256,7 @@ export async function ensureHooksApproved( // Read current trust when dequeued so earlier prompts’ decisions apply. stateOrGetter: AppState | (() => AppState), repoId: string, - scriptKind: HookScriptKind, + scriptKind: OrcaHookTrustKind, hostId?: ExecutionHostId, runtimeOwnerEnvironmentId?: string | null, isCancelled: () => boolean = NEVER_CANCEL_TRUST_CHECK, diff --git a/src/renderer/src/lib/issue-command-trust-content.ts b/src/renderer/src/runtime/repo-hooks/issue-command-trust-content.ts similarity index 100% rename from src/renderer/src/lib/issue-command-trust-content.ts rename to src/renderer/src/runtime/repo-hooks/issue-command-trust-content.ts diff --git a/src/renderer/src/lib/orca-hook-trust.ts b/src/renderer/src/runtime/repo-hooks/orca-hook-trust.ts similarity index 85% rename from src/renderer/src/lib/orca-hook-trust.ts rename to src/renderer/src/runtime/repo-hooks/orca-hook-trust.ts index c3c57817396..7030d447f5d 100644 --- a/src/renderer/src/lib/orca-hook-trust.ts +++ b/src/renderer/src/runtime/repo-hooks/orca-hook-trust.ts @@ -1,7 +1,5 @@ -import { sha256 } from './sha256' -import type { OrcaHookTrustKind } from '../../../shared/orca-hook-trust-entries' - -export type OrcaHookScriptKind = OrcaHookTrustKind +import '../../lib/sha256' +import { sha256 } from '../../../../shared/sha256' export async function hashOrcaHookScript(content: string): Promise { const normalized = content.trim() diff --git a/src/renderer/src/lib/setup-script-prompt.ts b/src/renderer/src/runtime/repo-hooks/setup-script-prompt.ts similarity index 95% rename from src/renderer/src/lib/setup-script-prompt.ts rename to src/renderer/src/runtime/repo-hooks/setup-script-prompt.ts index ebf61228b63..29b01d3261b 100644 --- a/src/renderer/src/lib/setup-script-prompt.ts +++ b/src/renderer/src/runtime/repo-hooks/setup-script-prompt.ts @@ -1,8 +1,8 @@ -import { getDefaultRepoHookSettings } from '../../../shared/constants' -import { resolveHookCommandSourcePolicy } from '../../../shared/hook-command-source-policy' -import type { SetupScriptImportCandidate } from '../../../shared/workspace-setup/setup-script-imports' -import type { RepoHookSettings } from '../../../shared/orca-yaml-hook-types' -import type { Repo } from '../../../shared/repo-types' +import { getDefaultRepoHookSettings } from '../../../../shared/constants' +import { resolveHookCommandSourcePolicy } from '../../../../shared/hook-command-source-policy' +import type { SetupScriptImportCandidate } from '../../../../shared/workspace-setup/setup-script-imports' +import type { RepoHookSettings } from '../../../../shared/orca-yaml-hook-types' +import type { Repo } from '../../../../shared/repo-types' import type { HookCheckResult } from '@/runtime/repo-hooks/runtime-hooks-client' import { isRuntimeScopeForbiddenError } from '@/runtime/rpc/calls/runtime-rpc-result' import { hasEffectiveSetupCommand } from './setup-script-status' diff --git a/src/renderer/src/lib/setup-script-status.ts b/src/renderer/src/runtime/repo-hooks/setup-script-status.ts similarity index 81% rename from src/renderer/src/lib/setup-script-status.ts rename to src/renderer/src/runtime/repo-hooks/setup-script-status.ts index 99e926c3a7f..a630462502c 100644 --- a/src/renderer/src/lib/setup-script-status.ts +++ b/src/renderer/src/runtime/repo-hooks/setup-script-status.ts @@ -1,5 +1,5 @@ -import { resolveHookCommandSourcePolicy } from '../../../shared/hook-command-source-policy' -import type { Repo } from '../../../shared/repo-types' +import { resolveHookCommandSourcePolicy } from '../../../../shared/hook-command-source-policy' +import type { Repo } from '../../../../shared/repo-types' import type { HookCheckResult } from '@/runtime/repo-hooks/runtime-hooks-client' export function hasEffectiveSetupCommand(repo: Repo, hooksResult: HookCheckResult): boolean { diff --git a/src/renderer/src/lib/vm-recipe-trust-content.ts b/src/renderer/src/runtime/repo-hooks/vm-recipe-trust-content.ts similarity index 91% rename from src/renderer/src/lib/vm-recipe-trust-content.ts rename to src/renderer/src/runtime/repo-hooks/vm-recipe-trust-content.ts index 4f2f6c2ad4d..90d4d4807c5 100644 --- a/src/renderer/src/lib/vm-recipe-trust-content.ts +++ b/src/renderer/src/runtime/repo-hooks/vm-recipe-trust-content.ts @@ -1,4 +1,4 @@ -import type { OrcaHooks } from '../../../shared/orca-yaml-hook-types' +import type { OrcaHooks } from '../../../../shared/orca-yaml-hook-types' /** The environment recipe commands a vmRecipe trust approval covers. */ export function getVmRecipeTrustContent(yamlHooks: OrcaHooks | null): string { diff --git a/src/renderer/src/store/repos/all-host-repo-catalog-actions.ts b/src/renderer/src/store/repos/all-host-repo-catalog-actions.ts index 1131f8996f4..c3adece9f86 100644 --- a/src/renderer/src/store/repos/all-host-repo-catalog-actions.ts +++ b/src/renderer/src/store/repos/all-host-repo-catalog-actions.ts @@ -5,7 +5,7 @@ import { applyManualRepoOrder } from '../../../../shared/manual-repo-order' import { retainValidFilterRepoIds } from './repo-filter-selection' import { readRuntimeWorktreeVisibilitySnapshot } from '../slices/settings/worktree-visibility-owner-settings' import { getRepoHostIdentity } from '../../../../shared/repo-host-identity' -import { filterSetupScriptPromptDismissalsToValidRepos } from '@/lib/setup-script-prompt' +import { filterSetupScriptPromptDismissalsToValidRepos } from '@/runtime/repo-hooks/setup-script-prompt' import { getRepoExecutionHostId } from '../../../../shared/execution-host' import { isRemovedRuntimeHostId } from '../host-catalog/removed-runtime-host-rows' import type { FetchedRepoCatalog } from './repo-catalog-merge' diff --git a/src/renderer/src/store/repos/recipe-vm-project-removal.ts b/src/renderer/src/store/repos/recipe-vm-project-removal.ts index 12e8ec3cd31..8e3bfc2631f 100644 --- a/src/renderer/src/store/repos/recipe-vm-project-removal.ts +++ b/src/renderer/src/store/repos/recipe-vm-project-removal.ts @@ -5,8 +5,8 @@ import { } from '../../../../shared/execution-host' import type { Repo } from '../../../../shared/repo-types' import type { AppState } from '../types' -import { cleanupEphemeralVmRuntimesForDeleted } from '@/lib/ephemeral-vm-runtime-cleanup' -import { getRecipeVmSshTargetForHost } from '@/lib/recipe-vm-managed-host' +import { cleanupEphemeralVmRuntimesForDeleted } from '@/runtime/ephemeral-vm/ephemeral-vm-runtime-cleanup' +import { getRecipeVmSshTargetForHost } from '@/runtime/ephemeral-vm/recipe-vm-managed-host' import { selectWorktreesByRepo } from '../workspaces/catalog/workspace-record-fields' /** Destroy backing recipe VM before project removal to prevent leaks. Return false synchronously without a VM; resolve true if VM destruction also removed the owning managed server/catalog. */ diff --git a/src/renderer/src/store/repos/repo-add-actions.ts b/src/renderer/src/store/repos/repo-add-actions.ts index 6ff0b2f5b61..9d23fa52f60 100644 --- a/src/renderer/src/store/repos/repo-add-actions.ts +++ b/src/renderer/src/store/repos/repo-add-actions.ts @@ -7,7 +7,7 @@ import { getRepoHostIdentity } from '../../../../shared/repo-host-identity' import { callRuntimeRpc } from '../../runtime/rpc/calls/runtime-rpc-call' import { runtimeTargetForOwnerEnvironment } from '../../runtime/rpc/targets/runtime-client-target' import { defaultCreationHost } from '@/runtime/hosts/selection/default-creation-host' -import { markOnboardingProjectAdded } from '@/lib/onboarding-project-checklist' +import { markOnboardingProjectAdded } from '@/components/onboarding/onboarding-project-checklist' import { translate } from '@/i18n/i18n' import { getRepoExecutionHostId, @@ -215,7 +215,7 @@ export function createRepoAddActions( const { resolveDismissedOnboardingFolderAgentLaunch, revealOnboardingFolderWithAgentLaunch - } = await import('@/lib/onboarding-folder-agent-launch') + } = await import('@/components/onboarding/onboarding-folder-agent-launch') // Why: adding the first folder from Landing skips onboarding's completeRepo hook; carry the default agent into the first terminal here. const launch = await resolveDismissedOnboardingFolderAgentLaunch({ worktreeId: folderWorktree.id, diff --git a/src/renderer/src/store/repos/repo-catalog-actions.ts b/src/renderer/src/store/repos/repo-catalog-actions.ts index 00d3d85bdd9..f9cdd5d53fe 100644 --- a/src/renderer/src/store/repos/repo-catalog-actions.ts +++ b/src/renderer/src/store/repos/repo-catalog-actions.ts @@ -7,7 +7,7 @@ import { retainValidFilterRepoIds } from './repo-filter-selection' import { mergeSshRepoReadoptions, reconcileReadoptedSshRepoRows } from './superseded-ssh-repo-rows' import { getRepoHostIdentity } from '../../../../shared/repo-host-identity' import { runtimeTargetForOwnerEnvironment } from '../../runtime/rpc/targets/runtime-client-target' -import { filterSetupScriptPromptDismissalsToValidRepos } from '@/lib/setup-script-prompt' +import { filterSetupScriptPromptDismissalsToValidRepos } from '@/runtime/repo-hooks/setup-script-prompt' import { getRepoExecutionHostId } from '../../../../shared/execution-host' import { isRemovedRuntimeHostId } from '../host-catalog/removed-runtime-host-rows' import type { LocalRepoCatalogFetchOutcome } from './repo-catalog-fencing' diff --git a/src/renderer/src/store/repos/repos-all-hosts.test.ts b/src/renderer/src/store/repos/repos-all-hosts.test.ts index ad39e798e5d..57508de69f9 100644 --- a/src/renderer/src/store/repos/repos-all-hosts.test.ts +++ b/src/renderer/src/store/repos/repos-all-hosts.test.ts @@ -9,7 +9,7 @@ import { type RuntimeEnvironmentCallRequest } from '../../runtime/rpc/testing/runtime-compatibility-test-fixture' import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '../../runtime/rpc/compatibility/runtime-compatibility-cache' -import { getSetupScriptPromptDismissalKey } from '../../lib/setup-script-prompt' +import { getSetupScriptPromptDismissalKey } from '../../runtime/repo-hooks/setup-script-prompt' const localRepo: Repo = { id: 'local-repo', @@ -709,57 +709,4 @@ describe('fetchReposForAllHosts', () => { 'remote-repo': { all: { approvedAt: 1 } } }) }) - - it('starts remote repo catalog loads concurrently for all configured runtimes', async () => { - runtimeEnvironmentsList.mockResolvedValue([ - { id: 'env-1', name: 'first' }, - { id: 'env-2', name: 'second' } - ]) - const firstStatusResolvers = new Map void>() - let resolveBothStatusProbes = (): void => {} - const bothStatusProbesStarted = new Promise((resolve, reject) => { - const timeout = setTimeout( - () => reject(new Error('Timed out waiting for both runtime probes')), - 1_000 - ) - resolveBothStatusProbes = () => { - clearTimeout(timeout) - resolve() - } - }) - runtimeEnvironmentTransportCall.mockImplementation( - (args: RuntimeEnvironmentCallRequest & { selector?: string }) => { - if ( - args.method === 'status.get' && - args.selector && - !firstStatusResolvers.has(args.selector) - ) { - return new Promise((resolve) => { - firstStatusResolvers.set(args.selector!, resolve) - if (firstStatusResolvers.size === 2) { - resolveBothStatusProbes() - } - }) - } - return createCompatibleRuntimeStatusResponseIfNeeded(args) ?? runtimeEnvironmentCall(args) - } - ) - const store = createTestStore() - - const load = store.getState().fetchReposForAllHosts() - await bothStatusProbesStarted - - expect([...firstStatusResolvers.keys()].sort()).toEqual(['env-1', 'env-2']) - for (const resolve of firstStatusResolvers.values()) { - resolve(createCompatibleRuntimeStatusResponseIfNeeded({ method: 'status.get' })) - } - await load - - expect( - store - .getState() - .repos.map((repo) => `${repo.id}:${repo.executionHostId}`) - .sort() - ).toEqual(['local-repo:local', 'remote-repo:runtime:env-1', 'remote-repo:runtime:env-2']) - }) }) diff --git a/src/renderer/src/store/repos/runtime-repo-catalog-actions.ts b/src/renderer/src/store/repos/runtime-repo-catalog-actions.ts index c939f43d027..fa8046f1e24 100644 --- a/src/renderer/src/store/repos/runtime-repo-catalog-actions.ts +++ b/src/renderer/src/store/repos/runtime-repo-catalog-actions.ts @@ -6,7 +6,7 @@ import { applyManualRepoOrder } from '../../../../shared/manual-repo-order' import { retainValidFilterRepoIds } from './repo-filter-selection' import { readRuntimeWorktreeVisibilitySnapshot } from '../slices/settings/worktree-visibility-owner-settings' import { getRepoHostIdentity } from '../../../../shared/repo-host-identity' -import { filterSetupScriptPromptDismissalsToValidRepos } from '@/lib/setup-script-prompt' +import { filterSetupScriptPromptDismissalsToValidRepos } from '@/runtime/repo-hooks/setup-script-prompt' import { getRepoExecutionHostId } from '../../../../shared/execution-host' import { isRemovedRuntimeHostId } from '../host-catalog/removed-runtime-host-rows' import { diff --git a/src/renderer/src/store/repos/wsl-moved-repo-ui-retention.test.ts b/src/renderer/src/store/repos/wsl-moved-repo-ui-retention.test.ts index 5e8bf1ac59b..00bdf3f7058 100644 --- a/src/renderer/src/store/repos/wsl-moved-repo-ui-retention.test.ts +++ b/src/renderer/src/store/repos/wsl-moved-repo-ui-retention.test.ts @@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import '../../../../shared/constants' import type { Repo } from '../../../../shared/repo-types' import type { WslMovedProject } from '../../../../shared/wsl-move/wsl-moved-project' -import { getSetupScriptPromptDismissalKey } from '../../lib/setup-script-prompt' +import { getSetupScriptPromptDismissalKey } from '../../runtime/repo-hooks/setup-script-prompt' import { createTestStore } from '../testing/app-store-test-fixture' import { createUIStore, makePersistedUI } from '../slices/ui/ui-slice-test-harness' import './wsl-moved-repo-ui-retention' diff --git a/src/renderer/src/store/repos/wsl-moved-repo-ui-retention.ts b/src/renderer/src/store/repos/wsl-moved-repo-ui-retention.ts index d8a60056629..e4b4f561956 100644 --- a/src/renderer/src/store/repos/wsl-moved-repo-ui-retention.ts +++ b/src/renderer/src/store/repos/wsl-moved-repo-ui-retention.ts @@ -7,7 +7,7 @@ import type { WslMovedProject } from '../../../../shared/wsl-move/wsl-moved-proj import { getSetupScriptPromptDismissalRepoId, sanitizeSetupScriptPromptDismissals -} from '@/lib/setup-script-prompt' +} from '@/runtime/repo-hooks/setup-script-prompt' // Undefined in partial test stores and older state shapes; treated as no moved project. type MovedProjects = readonly WslMovedProject[] | undefined diff --git a/src/renderer/src/store/slices/agent-status/agent-status-authority-actions.ts b/src/renderer/src/store/slices/agent-status/agent-status-authority-actions.ts index 003ddff2310..e7c5ec02f16 100644 --- a/src/renderer/src/store/slices/agent-status/agent-status-authority-actions.ts +++ b/src/renderer/src/store/slices/agent-status/agent-status-authority-actions.ts @@ -1,7 +1,7 @@ import type { SleepingAgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-resume' import type { AgentStatusSlice } from './agent-status-slice-contract' import type { AgentStatusRuntime } from './agent-status-runtime' -import { rendererAgentStatusObservations } from '../../../lib/renderer-agent-status-observations' +import { rendererAgentStatusObservations } from '../../../lib/agent-status/evidence/renderer-agent-status-observations' import { resolveAgentPaneAuthorityKey, retireAgentPaneAuthorityAliases, diff --git a/src/renderer/src/store/slices/ui/ui-slice-contract-contextual.ts b/src/renderer/src/store/slices/ui/ui-slice-contract-contextual.ts index ac79e2c1a03..908340d0005 100644 --- a/src/renderer/src/store/slices/ui/ui-slice-contract-contextual.ts +++ b/src/renderer/src/store/slices/ui/ui-slice-contract-contextual.ts @@ -6,7 +6,7 @@ import type { import type { FeatureTipId, FeatureTipSeenId } from '../../../../../shared/feature-tips' import type { ChatUiLaunchTipVariant } from '../../../../../shared/native-chat/chat-ui-launch-tip-audience' import type { ContextualTourId } from '../../../../../shared/contextual-tours' -import type { OrcaHookScriptKind } from '../../../lib/orca-hook-trust' +import type { OrcaHookTrustKind } from '../../../../../shared/orca-hook-trust-entries' import type { SettingsNavigationTarget } from '../../../lib/settings-navigation-types' import type { ExecutionHostId } from '../../../../../shared/execution-host' @@ -101,7 +101,7 @@ export type UISliceContextual = { trustedOrcaHooks: PersistedTrustedOrcaHooks markOrcaHookScriptConfirmed: ( repoId: string, - kind: OrcaHookScriptKind, + kind: OrcaHookTrustKind, contentHash: string ) => void markOrcaHookRepoAlwaysTrusted: (repoId: string) => void diff --git a/src/renderer/src/store/slices/ui/ui-slice-hydration-actions.ts b/src/renderer/src/store/slices/ui/ui-slice-hydration-actions.ts index eb774947f02..7049b460e67 100644 --- a/src/renderer/src/store/slices/ui/ui-slice-hydration-actions.ts +++ b/src/renderer/src/store/slices/ui/ui-slice-hydration-actions.ts @@ -41,7 +41,7 @@ import { isReleaseChannel } from '../../../../../shared/release-channel' import { filterSetupScriptPromptDismissalsToValidRepos, sanitizeSetupScriptPromptDismissals -} from '../../../lib/setup-script-prompt' +} from '../../../runtime/repo-hooks/setup-script-prompt' import { isBundledPetId, DEFAULT_PET_ID } from '../../../components/pet/pet-models' import { getRepoHostIdentity } from '../../../../../shared/repo-host-identity' import { diff --git a/src/renderer/src/store/slices/ui/ui-slice-trust-actions.ts b/src/renderer/src/store/slices/ui/ui-slice-trust-actions.ts index fa7394c551f..546d1edcc22 100644 --- a/src/renderer/src/store/slices/ui/ui-slice-trust-actions.ts +++ b/src/renderer/src/store/slices/ui/ui-slice-trust-actions.ts @@ -1,5 +1,5 @@ import type { UISlice, UISliceGet, UISliceSet } from './ui-slice-contract' -import { getSetupScriptPromptDismissalKey } from '../../../lib/setup-script-prompt' +import { getSetupScriptPromptDismissalKey } from '../../../runtime/repo-hooks/setup-script-prompt' import { withOrcaHookRepoAlwaysTrusted, withOrcaHookScriptConfirmed diff --git a/src/renderer/src/store/slices/worktrees/create/created-worktree-setup-trust.ts b/src/renderer/src/store/slices/worktrees/create/created-worktree-setup-trust.ts index 5ad11346e93..2fc6b5c312f 100644 --- a/src/renderer/src/store/slices/worktrees/create/created-worktree-setup-trust.ts +++ b/src/renderer/src/store/slices/worktrees/create/created-worktree-setup-trust.ts @@ -1,7 +1,7 @@ import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import type { AppState } from '@/store/types' -import { confirmCreatedWorktreeSetupContent } from '@/lib/ensure-hooks-confirmed' +import { confirmCreatedWorktreeSetupContent } from '@/runtime/repo-hooks/ensure-hooks-confirmed' import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' import { runtimeEnvironmentSupportsCapability } from '@/runtime/rpc/compatibility/runtime-capability-proof' import { toRuntimeWorktreeSelector } from '@/runtime/rpc/targets/runtime-worktree-selector' diff --git a/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts b/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts index d60e0d19c0b..68ff5d39af6 100644 --- a/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts +++ b/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts @@ -1,10 +1,10 @@ import type { WorktreeSlice } from '../worktree-slice-contract' import type { WorktreeSliceGet, WorktreeSliceSet } from '../listing/worktree-slice-types' import type { AppState } from '../../../types' -import { cleanupFailedEphemeralVmWorkspace } from '@/lib/ephemeral-vm-failed-create-cleanup' +import { cleanupFailedEphemeralVmWorkspace } from '@/runtime/ephemeral-vm/ephemeral-vm-failed-create-cleanup' import { endWindowCreation } from '@/lib/sidebar-ended-creations' -import { settleVmCreateCheckoutAfterCleanup } from '@/lib/vm-create-hidden-checkouts' -import { cancelVmEnvironmentCheck } from '@/lib/ephemeral-vm-environment-check-decision' +import { settleVmCreateCheckoutAfterCleanup } from '@/runtime/ephemeral-vm/vm-create-hidden-checkouts' +import { cancelVmEnvironmentCheck } from '@/runtime/ephemeral-vm/ephemeral-vm-environment-check-decision' import { pendingCreationChatDraftScopeKey, type PendingWorktreeCreation diff --git a/src/renderer/src/store/slices/worktrees/teardown/host-qualified-worktree-removal.ts b/src/renderer/src/store/slices/worktrees/teardown/host-qualified-worktree-removal.ts index 5e4aa16b121..a6c3eb51fd2 100644 --- a/src/renderer/src/store/slices/worktrees/teardown/host-qualified-worktree-removal.ts +++ b/src/renderer/src/store/slices/worktrees/teardown/host-qualified-worktree-removal.ts @@ -16,7 +16,7 @@ import { getRepoIdFromWorktreeId } from '../../../../../../shared/worktree/id' import { appliedWorktreeCatalogVersionPatch } from '../listing/worktree-catalog-version-state' import { WORKTREE_REMOVAL_HOST_CHANGED_ERROR } from '../listing/worktree-slice-constants' import { translate } from '@/i18n/i18n' -import { cleanupEphemeralVmRuntimesForDeleted } from '@/lib/ephemeral-vm-runtime-cleanup' +import { cleanupEphemeralVmRuntimesForDeleted } from '@/runtime/ephemeral-vm/ephemeral-vm-runtime-cleanup' import { purgeOrphanedRuntimeSshProjects } from './orphaned-runtime-ssh-project-purge' import { completePreservedBranchCleanup } from './complete-preserved-branch-cleanup' diff --git a/src/renderer/src/store/slices/worktrees/teardown/remove-worktree.ts b/src/renderer/src/store/slices/worktrees/teardown/remove-worktree.ts index 0daa81fc50d..edf00dcb85a 100644 --- a/src/renderer/src/store/slices/worktrees/teardown/remove-worktree.ts +++ b/src/renderer/src/store/slices/worktrees/teardown/remove-worktree.ts @@ -3,7 +3,7 @@ import type { WorktreeSlice } from '../worktree-slice-contract' import type { WorktreeSliceGet, WorktreeSliceSet } from '../listing/worktree-slice-types' import type { RemoveWorktreeResult } from '../../../../../../shared/worktree/create-types' import { parseExecutionHostId } from '../../../../../../shared/execution-host' -import { ensureHooksConfirmed } from '@/lib/ensure-hooks-confirmed' +import { ensureHooksConfirmed } from '@/runtime/repo-hooks/ensure-hooks-confirmed' import { runtimeTargetForOwnerEnvironment } from '../../../../runtime/rpc/targets/runtime-client-target' import { forgetHugeRepoWarningDismissalsForWorktrees } from '@/lib/source-control/warnings/source-control-huge-repo-warning-dismissals' import { forgetWorktreeSleepIntent } from '@/lib/worktree-sleep-intent' diff --git a/src/renderer/src/store/slices/worktrees/teardown/removed-worktree-renderer-teardown.ts b/src/renderer/src/store/slices/worktrees/teardown/removed-worktree-renderer-teardown.ts index 7f156859b6f..14c803688ed 100644 --- a/src/renderer/src/store/slices/worktrees/teardown/removed-worktree-renderer-teardown.ts +++ b/src/renderer/src/store/slices/worktrees/teardown/removed-worktree-renderer-teardown.ts @@ -3,7 +3,7 @@ import type { WorktreeSliceGet, WorktreeSliceSet } from '../listing/worktree-sli import type { WorktreeCatalogVersion } from '../../../../../../shared/worktree/catalog-version' import { getRepoIdFromWorktreeId } from '../../../../../../shared/worktree/id' import { appliedWorktreeCatalogVersionPatch } from '../listing/worktree-catalog-version-state' -import { cleanupEphemeralVmRuntimesForDeleted } from '@/lib/ephemeral-vm-runtime-cleanup' +import { cleanupEphemeralVmRuntimesForDeleted } from '@/runtime/ephemeral-vm/ephemeral-vm-runtime-cleanup' import { forgetAgentStartupDeliveriesForTabs } from '@/lib/agent-session/launch/startup/agent-startup-delivery-guards' import { forgetForegroundTerminalTabs } from '@/lib/foreground-terminal-tabs' import { requestVirtualizedScrollAnchorRecord } from '@/hooks/requestVirtualizedScrollAnchorRecord' diff --git a/tests/e2e/launch-agent-in-new-tab-web-runtime.unit.test.ts b/tests/e2e/launch-agent-in-new-tab-web-runtime.unit.test.ts index ed590378077..7f58118b3e4 100644 --- a/tests/e2e/launch-agent-in-new-tab-web-runtime.unit.test.ts +++ b/tests/e2e/launch-agent-in-new-tab-web-runtime.unit.test.ts @@ -1,24 +1,14 @@ // @vitest-environment happy-dom -import { EVERY_AGENT_CHAT } from '../../src/shared/native-chat/every-agent-chat.test-fixture' -import { mocks, store } from './launch-agent-web-terminal.test-fixture' -import { createElement, useState } from 'react' -import { act, fireEvent, render, screen } from '@testing-library/react' -import { useTabAgentMenuLaunch } from '@/components/tab-bar/QuickLaunchButton' -import { STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY } from '../../src/shared/agent-session/structured-agent-session-surface-capabilities' -import { AGENT_SESSION_AGENTS_METHOD } from '../../src/shared/agent-session/agent-session-registered-agents' -import { pasteDraftWhenAgentReady } from '@/lib/agent-session/messaging/paste/agent-paste-draft' -import { newAgentPromptOutcome } from '@/lib/new-agent-prompt-outcome' + +import { mocks } from './launch-agent-web-terminal.test-fixture' + import { newAgentLaunchRequestId } from '@/lib/agent-session/launch/routing/agent-launch-request-id' import { nonRefusedAgentLaunch } from '@/lib/agent-session/launch/new-tab/agent-tab-launch-outcome.test-fixture' import { stubRuntimeEnvironmentBridge } from '@/runtime/rpc/testing/runtime-environment-bridge-fixture' -import { AGENT_LAUNCH_CHOICES_CAPABILITY } from '../../src/shared/agent-launch/contracts/agent-launch-runtime-capability' -import { OrcaRuntimeService } from '../../src/main/runtime/orca-runtime' -import { consumeOldHostPreparedCommand } from './prepared-action-launch.test-fixture' + import '@/runtime/agent-launch-settings/host-agent-launch-preferences-resource' -import { composeAgentLaunchProfile } from '../../src/shared/agent-launch/choices/tui-agent-launch-defaults' -import { projectAgentLaunchSettings } from '../../src/shared/agent-launch/choices/agent-launch-settings' + import { describe, expect, it, vi } from 'vitest' -import { CreateAgentSessionParams } from '../../src/shared/rpc-contract/agent-session-params' describe('launchAgentInNewTab paired web runtime', () => { it.each(['structured', 'legacy'] as const)( @@ -60,414 +50,4 @@ describe('launchAgentInNewTab paired web runtime', () => { expect(mocks.toastError).toHaveBeenCalledOnce() } ) - - it.each(['deadline', 'edited', 'authoritative', 'old', 'no-trust', 'old-client'] as const)( - 'delivers the actual %s operation once with the correct model owner and final result', - async (route) => { - vi.useFakeTimers() - try { - mocks.actualOperation = true - mocks.capability.mockImplementation( - async (_environmentId, capability) => - route !== 'old' && - capability !== 'agent-session.create-options.v1' && - !(route === 'no-trust' && capability === 'agent-session.trust-worktree.v1') - ) - store.runtimeStatusByEnvironmentId.get('web-runtime')!.status.capabilities = - route === 'old' ? [] : [AGENT_LAUNCH_CHOICES_CAPABILITY] - store.settings.agentLaunchChoices = { claude: { options: { effort: 'low' } } } - store.settings.agentDefaultArgs = { claude: '--verbose' } - store.settings.agentDefaultEnv = { claude: { KEEP: 'caller' } } - store.settings.agentCmdOverrides = { claude: 'cx' } - const hostSettings = { - agentCmdOverrides: { claude: '/host/claude' }, - agentPermissionDefault: 'own' as const, - agentLaunchChoices: { - claude: { - model: 'opus', - options: { effort: 'high' } - } - }, - agentDefaultEnv: { claude: { KEEP: 'host' } } - } - const pending = Promise.withResolvers<{ - settings: ReturnType - }>() - mocks.hostRpc.mockImplementation((_target, method) => - route === 'deadline' - ? pending.promise - : Promise.resolve({ - settings: - method === 'settings.get' - ? { ...hostSettings, ...composeAgentLaunchProfile(hostSettings) } - : projectAgentLaunchSettings(hostSettings) - }) - ) - const host = new OrcaRuntimeService( - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the final startup owner reads only this settings store. - { getSettings: () => hostSettings } as never - ) - Object.assign(host, { - resolveTerminalWorkspaceLaunchScope: vi.fn(async () => ({ - id: 'wt-1', - path: '/host', - connectionId: null, - repo: null, - folderWorkspace: null - })) - }) - const compiled = vi.spyOn(host, 'planAgentPaneLaunch') - const prepared = vi.fn(consumeOldHostPreparedCommand) - const spawn = vi - .spyOn(host, 'createTerminal') - .mockImplementation(async (_worktree, options) => { - await host.planAgentPaneLaunch('wt-1', options ?? {}) - return { - handle: 'created', - worktreeId: 'wt-1', - title: null, - tabId: 'host-tab', - paneKey: 'host-tab:leaf' - } - }) - const dispatch = vi.fn(async (request) => { - if (request.method === 'terminal.createAgentSession') { - return { - ok: true, - result: await host.createAgentSession(CreateAgentSessionParams.parse(request.params)) - } - } - if (request.method === 'session.tabs.createTerminal') { - await prepared(request.params) - return { ok: true, result: { tab: { id: 'host-tab', leafId: 'leaf' } } } - } - if (request.method === 'session.tabs.move') { - return { ok: true, result: {} } - } - throw new Error(`Unexpected operation ${request.method}`) - }) - stubRuntimeEnvironmentBridge({ call: dispatch }) - const { launchAgentInNewTab } = - await import('../../src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab') - const result = nonRefusedAgentLaunch( - launchAgentInNewTab({ - requestId: newAgentLaunchRequestId(), - agent: 'claude', - worktreeId: 'wt-1', - requestedSurface: 'terminal', - groupId: 'group-1', - activate: false, - agentArgs: '--verbose', - initialCwd: '/host-child', - ...(route !== 'old-client' ? { trustWorktreeId: 'repo::/host-child' } : {}), - ...(route === 'edited' ? { sessionOptions: { effort: 'high' } } : {}) - }) - ) - await vi.advanceTimersByTimeAsync(route === 'deadline' ? 3_000 : 0) - await expect(result?.terminalCompletion).resolves.toMatchObject({ - outcome: { status: 'created' }, - tabId: 'web-terminal-host-tab' - }) - const creates = () => - dispatch.mock.calls.filter(([request]) => - ['terminal.createAgentSession', 'session.tabs.createTerminal'].includes(request.method) - ) - expect(creates()).toHaveLength(1) - if (route !== 'old') { - expect(creates()[0][0]).toMatchObject({ - method: 'terminal.createAgentSession', - params: { - agent: 'claude', - agentArgs: route === 'edited' ? '--model opus --effort high --verbose' : '--verbose', - presentation: 'background' - } - }) - expect(creates()[0][0].params).not.toHaveProperty('launchPreferences') - expect(spawn).toHaveBeenCalledTimes(1) - expect(spawn.mock.calls[0]?.[1]).toMatchObject({ cwd: '/host-child' }) - if (route === 'old-client') { - expect(mocks.capability).not.toHaveBeenCalledWith( - 'web-runtime', - 'agent-session.trust-worktree.v1' - ) - } - if (route === 'no-trust' || route === 'old-client') { - expect(creates()[0][0].params).not.toHaveProperty('trustWorktreeId') - expect(spawn.mock.calls[0]?.[1]).not.toHaveProperty('trustWorktreeId') - } else { - expect(creates()[0][0].params.trustWorktreeId).toBe('repo::/host-child') - expect(spawn.mock.calls[0]?.[1]?.trustWorktreeId).toBe('repo::/host-child') - } - const plan = await compiled.mock.results[0].value - expect(plan).toMatchObject({ - command: expect.stringContaining("'opus'"), - env: { KEEP: 'host' }, - launchConfig: { - agentArgs: route === 'edited' ? '--model opus --effort high --verbose' : '--verbose' - } - }) - expect(plan?.command).toContain('/host/claude') - expect(plan?.command).toContain("'high'") - expect(plan?.command).not.toContain("'low'") - expect(prepared).not.toHaveBeenCalled() - } else { - expect(creates()[0][0]).toMatchObject({ - method: 'session.tabs.createTerminal', - params: { - command: expect.stringContaining('/host/claude'), - env: { KEEP: 'host' }, - launchConfig: { agentCommand: "/host/claude '--verbose'", agentArgs: '--verbose' }, - targetGroupId: 'group-1', - activate: false, - select: false, - navigation: 'caller' - } - }) - expect(creates()[0][0].params.command).toContain("'opus'") - expect(creates()[0][0].params.command).not.toContain('desktop') - expect(prepared).toHaveBeenCalledTimes(1) - expect(await prepared.mock.results[0].value).toMatchObject({ - command: creates()[0][0].params.command, - env: { KEEP: 'host' }, - launchConfig: { agentArgs: '--verbose' } - }) - expect(creates()[0][0].params).not.toHaveProperty('trustWorktreeId') - expect(spawn).not.toHaveBeenCalled() - } - if (route === 'deadline') { - pending.resolve({ settings: projectAgentLaunchSettings(hostSettings) }) - await vi.advanceTimersByTimeAsync(0) - expect(creates()).toHaveLength(1) - } - expect(mocks.createTab).not.toHaveBeenCalled() - expect(mocks.toastError).not.toHaveBeenCalled() - } finally { - vi.useRealTimers() - vi.restoreAllMocks() - } - } - ) - - it('settles ordinary QuickLaunch preparation independently of prompt observers', async () => { - mocks.actualOperation = true - const dispatch = vi.fn(async (request) => ({ - ok: true, - result: - request.method === 'session.tabs.createTerminal' - ? { tab: { id: 'host-tab', leafId: 'leaf' } } - : {} - })) - Object.assign(window, { api: { runtimeEnvironments: { call: dispatch } } }) - let pick = false - function QuickLaunch() { - const launch = useTabAgentMenuLaunch({ - worktreeId: 'wt-1', - groupId: 'group-1', - onFocusTerminal: vi.fn() - }) - return createElement( - 'button', - { - onClick: () => - launch( - { kind: 'cli', agent: 'claude', executionHostId: 'runtime:web-runtime' }, - pick - ? { agent: 'claude', surface: 'terminal', choices: { model: 'opus' } } - : undefined - ) - }, - 'Launch Claude' - ) - } - render(createElement(QuickLaunch)) - store.settings.agentDefaultArgs = { claude: "--model 'opus" } - await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Launch Claude' }))) - expect(mocks.toastError).not.toHaveBeenCalled() - expect( - dispatch.mock.calls.find(([r]) => r.method === 'session.tabs.createTerminal')?.[0].params - ).not.toHaveProperty('command') - dispatch.mockClear() - mocks.toastError.mockClear() - store.settings.agentDefaultArgs = {} - store.settings.agentCmdOverrides = { claude: 'claude --model sonnet' } - pick = true - await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Launch Claude' }))) - expect(mocks.toastError).toHaveBeenCalledOnce() - expect(dispatch).not.toHaveBeenCalled() - mocks.toastError.mockClear() - pick = false - store.settings.agentLaunchChoices = { claude: { model: 'opus' } } - await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Launch Claude' }))) - expect( - dispatch.mock.calls.filter(([r]) => r.method === 'session.tabs.createTerminal') - ).toHaveLength(1) - expect( - dispatch.mock.calls.find(([r]) => r.method === 'session.tabs.createTerminal')?.[0].params - .command - ).toBeUndefined() - expect(mocks.toastError).not.toHaveBeenCalled() - mocks.capability.mockRejectedValueOnce(new Error('private transport detail')) - await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Launch Claude' }))) - expect(mocks.toastError).not.toHaveBeenCalled() - expect(mocks.createTab).not.toHaveBeenCalled() - }) - - it.each(['submit-after-ready', 'draft'] as const)( - 'retains the %s prompt with one preparation notice', - async (promptDelivery) => { - mocks.actualOperation = true - store.settings.agentDefaultArgs = { claude: "--model 'opus" } - const handoff = vi.fn() - function PromptLaunch() { - const [prompt, setPrompt] = useState('keep this task') - const launch = useTabAgentMenuLaunch({ - worktreeId: 'wt-1', - groupId: 'group-1', - onFocusTerminal: vi.fn(), - prompt, - promptDelivery, - onPromptDelivered: () => setPrompt(''), - onPromptHandedOff: handoff - }) - return createElement( - 'div', - {}, - createElement('textarea', { 'aria-label': 'Task', value: prompt, readOnly: true }), - createElement( - 'button', - { - onClick: () => - launch({ kind: 'cli', agent: 'claude', executionHostId: 'runtime:web-runtime' }) - }, - 'Launch task' - ) - ) - } - render(createElement(PromptLaunch)) - await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Launch task' }))) - expect(mocks.toastError).toHaveBeenCalledExactlyOnceWith( - expect.stringMatching(/Claude.*try again/) - ) - expect(screen.getByRole('textbox', { name: 'Task' })).toHaveProperty( - 'value', - 'keep this task' - ) - expect(mocks.createWebRuntimeSessionTerminal).not.toHaveBeenCalled() - expect(mocks.createTab).not.toHaveBeenCalled() - expect(handoff).toHaveBeenCalledOnce() - await expect(handoff.mock.calls[0][0]).resolves.toEqual({ delivered: false }) - } - ) - - it.each(['created', 'late-answer'] as const)( - 'runs the real host wait and single terminal re-entry through %s settlement', - async (mode) => { - vi.useFakeTimers() - mocks.actualOperation = true - mocks.capability.mockResolvedValue(true) - vi.mocked(pasteDraftWhenAgentReady).mockResolvedValue(true) - store.settings.nativeChatProviders = { ...EVERY_AGENT_CHAT } - store.runtimeStatusByEnvironmentId.get('web-runtime')!.status = { - hostPlatform: 'linux', - runtimeId: 'runtime-1', - capabilities: [ - AGENT_LAUNCH_CHOICES_CAPABILITY, - STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY - ] - } - const listing = Promise.withResolvers<{ agents: [] }>() - mocks.hostRpc.mockImplementation((_target, method) => - method === AGENT_SESSION_AGENTS_METHOD - ? listing.promise - : Promise.reject(new Error('Host-owned launches need no desktop settings')) - ) - const dispatch = vi.fn(async (request) => ({ - ok: true, - result: - request.method === 'terminal.createAgentSession' - ? { terminal: { tabId: 'host-tab', paneKey: 'host-tab:leaf' } } - : {} - })) - stubRuntimeEnvironmentBridge({ call: dispatch }) - const { launchAgentInNewTab } = - await import('../../src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab') - // OpenCode has no built-in structured fallback without the owning host's catalog. - const result = nonRefusedAgentLaunch( - launchAgentInNewTab({ - requestId: newAgentLaunchRequestId(), - agent: 'opencode', - worktreeId: 'wt-1', - prompt: 'review this context', - promptDelivery: 'draft' - }) - ) - expect(mocks.hostRpc).toHaveBeenCalledWith( - expect.anything(), - AGENT_SESSION_AGENTS_METHOD, - {}, - expect.anything() - ) - expect(dispatch).not.toHaveBeenCalled() - if (mode === 'late-answer') { - await vi.advanceTimersByTimeAsync(3_000) - } else { - listing.resolve({ agents: [] }) - } - await vi.advanceTimersByTimeAsync(0) - await expect(result?.structuredSettlement).resolves.toMatchObject({ - kind: 'terminal' - }) - expect(result?.promptDeliveryResult).toBeDefined() - await expect(result?.promptDeliveryResult).resolves.toMatchObject({ - delivered: true - }) - const creates = () => - dispatch.mock.calls.filter(([r]) => r.method === 'terminal.createAgentSession') - expect(creates()).toHaveLength(1) - listing.resolve({ agents: [] }) - await vi.advanceTimersByTimeAsync(4_000) - expect(creates()).toHaveLength(1) - expect(mocks.toastError).not.toHaveBeenCalled() - expect(mocks.createTab).not.toHaveBeenCalled() - } - ) - - it('retains the prompt and reports once when delivery rejects after an accepted create', async () => { - mocks.actualOperation = true - const dispatch = vi.fn(async () => ({ - ok: true, - result: { tab: { id: 'host-tab', leafId: 'leaf' } } - })) - stubRuntimeEnvironmentBridge({ call: dispatch }) - vi.mocked(pasteDraftWhenAgentReady).mockRejectedValueOnce(new Error('paste transport failed')) - const { launchAgentInNewTab } = - await import('../../src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab') - const result = nonRefusedAgentLaunch( - launchAgentInNewTab({ - requestId: newAgentLaunchRequestId(), - agent: 'claude', - worktreeId: 'wt-1', - requestedSurface: 'terminal', - prompt: 'keep this task', - promptDelivery: 'submit-after-ready' - }) - ) - await expect(result?.terminalCompletion).resolves.toMatchObject({ - outcome: { status: 'created' }, - delivered: false, - failureNotified: true - }) - expect(result?.promptDeliveryResult).toBeDefined() - await expect( - newAgentPromptOutcome({ delivery: result!.promptDeliveryResult! }) - ).resolves.toEqual({ delivered: false }) - expect(mocks.toastError).toHaveBeenCalledExactlyOnceWith( - expect.stringMatching(/opened a terminal for Claude.*Send the prompt/) - ) - expect(store.seedNativeChatLaunchPrompt).toHaveBeenCalledWith( - expect.objectContaining({ text: 'keep this task' }) - ) - expect(store.markNativeChatLaunchPromptFailed).toHaveBeenCalledOnce() - expect(dispatch.mock.calls).toHaveLength(1) - }) }) diff --git a/tests/e2e/new-workspace-linked-item-project-switch.spec.ts b/tests/e2e/new-workspace-linked-item-project-switch.spec.ts index fdb79cb1d44..1888ca99579 100644 --- a/tests/e2e/new-workspace-linked-item-project-switch.spec.ts +++ b/tests/e2e/new-workspace-linked-item-project-switch.spec.ts @@ -8,7 +8,7 @@ import path from 'node:path' import type { Page } from '@stablyai/playwright-test' import { test, expect } from './helpers/orca-app' import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import type { LinkedWorkItemSummary } from '../../src/renderer/src/lib/new-workspace' +import type { LinkedWorkItemSummary } from '../../src/renderer/src/lib/workspace/creation/new-workspace' import type { TaskSourceContext } from '../../src/shared/work-items/task-source-context' const SECOND_PROJECT_NAME = 'linked-item-second-project' diff --git a/tests/e2e/terminal-agent-fork-draft-ownership.unit.test.ts b/tests/e2e/terminal-agent-fork-draft-ownership.unit.test.ts deleted file mode 100644 index ba02072b3dc..00000000000 --- a/tests/e2e/terminal-agent-fork-draft-ownership.unit.test.ts +++ /dev/null @@ -1,216 +0,0 @@ -// @vitest-environment happy-dom -import { mocks, store } from './launch-agent-web-terminal.test-fixture' -import { expect, it, vi } from 'vitest' -import { buildAgentSessionForkPrompt } from '@/lib/agent-session/context/agent-session-fork-context' -import { isWebRuntimeSessionActive } from '@/runtime/web-session-tabs-sync/identity/web-runtime-session-environment' -import { pasteDraftWhenAgentReady } from '@/lib/agent-session/messaging/paste/agent-paste-draft' -import { newAgentPromptOutcome } from '@/lib/new-agent-prompt-outcome' -import { projectAgentLaunchSettings } from '../../src/shared/agent-launch/choices/agent-launch-settings' -import { retainedPrefillHost } from './terminal-agent-fork-retained-prefill.test-fixture' -import { AGENT_SESSION_HOST_AUTHORITY_RUNTIME_CAPABILITY } from '../../src/shared/agent-session/agent-session-runtime-capabilities' -import { AGENT_LAUNCH_CHOICES_CAPABILITY } from '../../src/shared/agent-launch/contracts/agent-launch-runtime-capability' -import type * as SessionSnapshot from '@/runtime/web-session-tabs-sync/inventory/web-runtime-session-snapshot' - -const actualSnapshots = await vi.importActual( - '@/runtime/web-session-tabs-sync/inventory/web-runtime-session-snapshot' -) - -it.each(['local', 'web'] as const)( - 'settles the real fork draft independently of its created destination (%s)', - async (mode) => { - const local = mode === 'local' - const agent = 'codex' - const prompt = buildAgentSessionForkPrompt({ - capturedText: Array.from({ length: 50 }, (_, i) => `Assistant: context line ${i}`).join('\n'), - agentLabel: agent - })! - mocks.actualOperation = true - mocks.hostRpc.mockResolvedValue({ - settings: projectAgentLaunchSettings({ agentLaunchChoices: {} }) - }) - vi.mocked(isWebRuntimeSessionActive).mockReturnValue(!local) - store.repos = [{ ...store.repos[0], executionHostId: local ? 'local' : 'runtime:web-runtime' }] - store.settings.activeRuntimeEnvironmentId = local ? null : 'web-runtime' - mocks.createTab.mockReturnValue({ id: 'fork-tab' }) - const dispatch = vi.fn(async (_request: { params: { command?: string } }) => ({ - ok: true, - result: { tab: { id: 'host-tab', leafId: 'leaf' } } - })) - vi.stubGlobal('window', { - api: { - runtimeEnvironments: { call: dispatch }, - ui: { writeTerminalClipboardText: mocks.clipboard } - } - }) - const paste = Promise.withResolvers() - vi.mocked(pasteDraftWhenAgentReady).mockReturnValueOnce(paste.promise) - const focusSource = vi.fn() - const { startAgentSessionFork } = - await import('../../src/renderer/src/components/terminal-pane/session-fork/terminal-agent-session-fork') - const launcher = - await import('../../src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab') - const launched = vi.spyOn(launcher, 'launchAgentInNewTab') - const forking = startAgentSessionFork({ prompt, agent, worktreeId: 'wt-1', focusSource }) - await vi.waitFor(() => expect(pasteDraftWhenAgentReady).toHaveBeenCalledOnce()) - expect(mocks.toastSuccess).not.toHaveBeenCalled() - expect(mocks.clipboard).not.toHaveBeenCalled() - paste.resolve(false) - await expect(forking).resolves.toBe(true) - const result = launched.mock.results[0]?.value - expect(result?.promptDeliveryResult).toBeDefined() - await expect( - newAgentPromptOutcome({ delivery: result!.promptDeliveryResult! }) - ).resolves.toMatchObject({ delivered: false }) - if (!local) { - await expect(result?.terminalCompletion).resolves.toMatchObject({ - outcome: { status: 'created' }, - delivered: false - }) - } - expect(store.createWorktree).toHaveBeenCalledOnce() - expect(store.getKnownWorktreeById('wt-fork')).toBeDefined() - expect(store.seedNativeChatLaunchDraft).not.toHaveBeenCalled() - expect(mocks.clipboard).toHaveBeenCalledExactlyOnceWith(prompt) - expect(mocks.toastSuccess).not.toHaveBeenCalled() - expect(mocks.reveal).toHaveBeenLastCalledWith('wt-fork', { sidebarRevealBehavior: 'auto' }) - expect(mocks.createTab).toHaveBeenCalledTimes(local ? 1 : 0) - expect(dispatch).toHaveBeenCalledTimes(local ? 0 : 1) - expect(mocks.toastError).toHaveBeenCalledTimes(local ? 0 : 1) - } -) - -it.skipIf(process.platform === 'win32')( - 'keeps the actual POSIX inline fork input after binding failure, lost reply and same-process reclaim', - async () => { - const host = await retainedPrefillHost() - const snapshots = - await import('@/runtime/web-session-tabs-sync/inventory/web-runtime-session-snapshot') - vi.mocked(snapshots.refreshWebRuntimeSessionTabsSnapshot).mockImplementationOnce( - actualSnapshots.refreshWebRuntimeSessionTabsSnapshot - ) - const prompt = buildAgentSessionForkPrompt({ - capturedText: Array.from({ length: 50 }, (_, i) => `Assistant: context line ${i}`).join('\n'), - agentLabel: 'Claude' - })! - expect(prompt.split('\n')).toHaveLength(61) - mocks.actualOperation = true - store.folderWorkspaces = host.store - .getFolderWorkspaces() - .map((row) => ({ ...row, executionHostId: 'runtime:web-runtime' })) - store.projectGroups = host.store.getProjectGroups() - mocks.capability.mockImplementation( - async (_environment, capability) => - capability === AGENT_SESSION_HOST_AUTHORITY_RUNTIME_CAPABILITY || - capability === AGENT_LAUNCH_CHOICES_CAPABILITY - ) - mocks.hostRpc.mockResolvedValue({ - settings: projectAgentLaunchSettings(host.store.getSettings()) - }) - mocks.createTab.mockReturnValue({ id: 'unexpected-local-tab' }) - store.createWorktree.mockImplementationOnce(async () => { - const worktree = { - ...store.worktreesByRepo['repo-1'][0], - id: host.workspaceId, - path: host.root - } - store.worktreesByRepo = { 'repo-1': [...store.worktreesByRepo['repo-1'], worktree] } - return { worktree } - }) - vi.stubGlobal('window', { - api: { - runtimeEnvironments: { call: host.transport }, - ui: { writeTerminalClipboardText: mocks.clipboard } - } - }) - const focusSource = vi.fn() - const { startAgentSessionFork } = - await import('@/components/terminal-pane/session-fork/terminal-agent-session-fork') - const launcher = await import('@/lib/agent-session/launch/new-tab/launch-agent-in-new-tab') - const launched = vi.spyOn(launcher, 'launchAgentInNewTab') - const forking = startAgentSessionFork({ - prompt, - agent: 'claude', - worktreeId: 'wt-1', - focusSource - }) - void forking.catch(() => {}) - try { - await host.failBindingAfterHandoff(prompt) - await expect(forking).resolves.toBe(true) - expect(host.calls).toHaveLength(2) - expect(host.calls[1]).toEqual(host.calls[0]) - expect(host.calls[0]).toMatchObject({ prompt, promptDelivery: 'draft' }) - expect(host.create).toHaveBeenCalledOnce() - expect(host.compile).toHaveBeenCalledOnce() - expect(host.compile).toHaveBeenCalledWith( - expect.objectContaining({ prompt, promptDelivery: 'draft' }) - ) - expect(host.spawn).toHaveBeenCalledOnce() - expect(host.physicalSpawn).toHaveBeenCalledOnce() - const [inventory] = await host.provider.listProcesses() - expect(inventory).toMatchObject({ - worktreeId: host.workspaceId, - rootProcessId: host.process.pid - }) - expect(inventory?.terminalHandle).toEqual(expect.any(String)) - expect(host.create.mock.calls[0]?.[1]?.preAllocatedHandle).toBe(inventory?.terminalHandle) - expect(host.provider.getPtyProcess(inventory!.id)).toBe(host.process) - expect(host.replies).toEqual([ - { - disposition: 'replayed', - terminal: { - handle: inventory!.terminalHandle, - ptyId: inventory!.id, - worktreeId: host.workspaceId, - title: 'zsh', - surface: 'background' - } - } - ]) - expect(host.replies[0]?.terminal).not.toHaveProperty('tabId') - expect(host.replies[0]?.terminal).not.toHaveProperty('paneKey') - expect(host.events).toEqual([ - 'transport-1', - 'physical-spawn', - 'binding-pending', - 'startup-write', - 'binding-failed', - 'termination-failed', - 'host-failure-reply-lost', - 'transport-2', - 'reclaimed', - 'post-create-list-failed' - ]) - const result = launched.mock.results[0]?.value - await expect(result?.terminalCompletion).resolves.toMatchObject({ - outcome: { status: 'created' }, - delivered: true - }) - await expect(result?.promptDeliveryResult).resolves.toEqual({ - outcome: { status: 'created' }, - delivered: true, - failureNotified: false - }) - expect(host.writes).toHaveLength(1) - expect(store.createWorktree).toHaveBeenCalledOnce() - expect(store.getKnownWorktreeById(host.workspaceId)).toBeDefined() - expect( - host.store - .getFolderWorkspaces() - .filter((row) => row.id === host.workspaceId.slice('folder:'.length)) - ).toHaveLength(1) - expect(store.seedNativeChatLaunchDraft).not.toHaveBeenCalled() - expect(pasteDraftWhenAgentReady).not.toHaveBeenCalled() - expect(mocks.createTab).not.toHaveBeenCalled() - expect(mocks.clipboard).not.toHaveBeenCalled() - expect(mocks.toastError).not.toHaveBeenCalled() - expect(mocks.toastSuccess).toHaveBeenCalledExactlyOnceWith( - 'Top-level session fork opened in a new workspace' - ) - } finally { - host.releaseBinding() - host.exit() - await forking - } - } -) diff --git a/tests/e2e/terminal-agent-fork-retained-prefill.test-fixture.ts b/tests/e2e/terminal-agent-fork-retained-prefill.test-fixture.ts deleted file mode 100644 index 7df52a4b035..00000000000 --- a/tests/e2e/terminal-agent-fork-retained-prefill.test-fixture.ts +++ /dev/null @@ -1,259 +0,0 @@ -import { afterEach, expect, vi } from 'vitest' -import { mkdirSync, readFileSync } from 'node:fs' -import { join } from 'node:path' -import { fixture } from '../../src/main/persistence/loading-store/profile-state-delayed-authority-fixture' -import { OrcaRuntimeService } from '../../src/main/runtime/orca-runtime' -import { - LocalPtyProvider, - _resetLocalPtyProviderStateForTest -} from '../../src/main/providers/local-pty/local-pty-provider' -import { installPtyRuntimeController } from '../../src/main/ipc/pty/runtime/controller' -import { adoptStablePane } from '../../src/main/ipc/pty/pane/adopt-stable' -import { getLocalPtyProvider, setLocalPtyProvider } from '../../src/main/ipc/pty/provider/registry' -import { finishPtyShutdown } from '../../src/main/ipc/pty/provider/liveness' -import { - assertWorkspaceAcceptsNewPty, - resolvePtySpawnStartupCwd -} from '../../src/main/ipc/pty/host-env/spawn-cwd' -import { - noCodexResumeLaunch, - prepareCodexResumeHome, - resolveCodexResumeLaunch, - reconcileSharedRuntimeResumeHome, - stripSequencedStartupResumeArgv -} from '../../src/main/ipc/pty/host-env/codex-resume' -import { folderWorkspaceKey } from '../../src/shared/workspace-scope' -import type { - RuntimeCreateAgentSessionRequest, - RuntimeCreateAgentSessionResult -} from '../../src/shared/agent-session/agent-session-host-authority' -import type { PtyRuntimeControllerDeps } from '../../src/main/ipc/pty/runtime/controller-deps' -import type { ShellSpawnParams } from '../../src/main/providers/local-pty/local-pty-executable-spawn' -import { SHELL_READY_MARKER_PREFIX } from '../../src/main/pty/shell-startup/shell-ready-marker-scanner' -import * as startupStaging from '../../src/shared/startup-command-staging' -import { buildStartupCommandSubmission } from '../../src/shared/startup-command-submission' -import type * as PosixProcessTable from '../../src/main/pty/process-retirement/posix-pty-process-table' - -const physical = vi.hoisted(() => ({ spawn: vi.fn(), sweep: vi.fn() })) -vi.mock('node-pty', () => ({ spawn: physical.spawn })) -vi.mock('../../src/main/providers/local-pty/local-pty-runtime-spawn', async () => { - const { spawnShellWithFallback } = - await import('../../src/main/providers/local-pty/local-pty-executable-spawn') - return { - loadLocalPtyRuntimeSpawn: async () => (params: Omit) => - spawnShellWithFallback({ ...params, ptySpawn: physical.spawn }) - } -}) -vi.mock('../../src/main/pty/process-retirement/pty-descendant-termination', () => ({ - killWithDescendantSweep: (...args: unknown[]) => physical.sweep(...args) -})) -vi.mock( - '../../src/main/pty/process-retirement/posix-pty-process-table', - async (importOriginal) => ({ - ...(await importOriginal()), - readPosixPtyProcessTableSync: () => '', - readPosixPtyProcessTable: async () => '' - }) -) - -const previousProvider = getLocalPtyProvider() -afterEach(() => { - _resetLocalPtyProviderStateForTest() - setLocalPtyProvider(previousProvider) - vi.unstubAllEnvs() -}) - -export async function retainedPrefillHost() { - const { store } = await fixture() - const root = store.getSettings().workspaceDir - mkdirSync(root, { recursive: true }) - for (const key of [ - 'HOME', - 'USERPROFILE', - 'XDG_CONFIG_HOME', - 'XDG_DATA_HOME', - 'XDG_STATE_HOME', - 'XDG_CACHE_HOME', - 'CLAUDE_CONFIG_DIR', - 'CODEX_HOME', - 'ORCA_USER_DATA_PATH' - ]) { - const path = join(root, key.toLowerCase()) - mkdirSync(path, { recursive: true }) - vi.stubEnv(key, path) - } - vi.stubEnv('SHELL', '/bin/zsh') - vi.stubEnv('ORCA_DISABLE_MACOS_LOGIN_SHELL', '1') - store.updateSettings({ - agentLaunchChoices: {}, - agentPermissionDefault: 'ask', - agentDefaultArgs: { claude: '' }, - agentDefaultEnv: { claude: {} } - }) - const group = store.createProjectGroup({ - name: 'Fork', - parentPath: root, - createdFrom: 'folder-scan' - }) - const folder = store.createFolderWorkspace({ - projectGroupId: group.id, - name: 'Context fork', - folderPath: root - }) - const workspaceId = folderWorkspaceKey(folder.id) - await store.flushPendingOrThrowAsync() - const events: string[] = [] - const dataListeners = new Set<(data: string) => void>() - let exit: ((event: { exitCode: number }) => void) | undefined - const process = { - pid: 3621019, - process: 'zsh', - onData: vi.fn((listener: (data: string) => void) => { - dataListeners.add(listener) - return { dispose: () => dataListeners.delete(listener) } - }), - onExit: vi.fn((listener: (event: { exitCode: number }) => void) => { - exit = listener - return { - dispose: () => { - exit = undefined - } - } - }), - write: vi.fn((data: string) => { - events.push('startup-write') - writes.push(data) - }), - resize: vi.fn(), - pause: vi.fn(), - resume: vi.fn(), - kill: vi.fn(() => { - events.push('termination-failed') - throw new Error('controlled physical termination failure') - }) - } - const writes: string[] = [] - physical.spawn.mockReset().mockImplementation(() => { - events.push('physical-spawn') - return process - }) - physical.sweep - .mockReset() - .mockImplementation(async (_pid: number, signalRoot: () => void) => signalRoot()) - const provider = new LocalPtyProvider({ - getDefaultShell: () => '/bin/zsh', - isHistoryEnabled: () => false - }) - setLocalPtyProvider(provider) - const runtime = new OrcaRuntimeService(store, undefined, { getLocalProvider: () => provider }) - const deps: PtyRuntimeControllerDeps = { - runtime, - store, - getSettings: () => store.getSettings(), - adoptStablePane: (args) => adoptStablePane(runtime, store, args), - getLocalPtyStartupPromise: () => undefined, - getLocalPtyProviderStartupPromise: () => undefined, - prepareCodexResumeHome: (args) => prepareCodexResumeHome(undefined, args), - noCodexResumeLaunch, - resolveCodexResumeLaunch, - reconcileSharedRuntimeResumeHome, - stripSequencedStartupResumeArgv, - assertWorkspaceAcceptsNewPty: (...args) => assertWorkspaceAcceptsNewPty(store, ...args), - resolvePtySpawnStartupCwd: (...args) => resolvePtySpawnStartupCwd(store, ...args), - requestSerializedBuffer: async () => null, - shutdownProviderAndDetectExit: async (owner, id, options) => { - await owner.shutdown(id, options) - return true - }, - rememberSyntheticKillExit: () => {}, - rememberRetiredRejectedPty: () => {}, - sendPtyExitToRenderer: () => {}, - sendPtySpawnedToRenderer: () => {}, - finishPtyShutdown, - trustedTerminalHandleEnv: new Set(), - retiredRejectedPtyIds: new Map() - } - installPtyRuntimeController(deps) - const compiler = await import('../../src/main/opencode/opencode-model-startup-plan') - const compile = vi.spyOn(compiler, 'buildExecutionHostAgentStartupPlan') - const binding = Promise.withResolvers() - void binding.promise.catch(() => {}) - const persist = vi.spyOn(store, 'persistPtyBinding').mockImplementation(async () => { - events.push('binding-pending') - return binding.promise - }) - const create = vi.spyOn(runtime, 'createTerminal') - const spawn = vi.spyOn(provider, 'spawn') - const stage = vi.spyOn(startupStaging, 'stageStartupCommand') - const calls: RuntimeCreateAgentSessionRequest[] = [] - const replies: RuntimeCreateAgentSessionResult[] = [] - const transport = vi.fn( - async ({ method, params }: { method: string; params: RuntimeCreateAgentSessionRequest }) => { - if (method === 'session.tabs.list') { - events.push('post-create-list-failed') - throw new Error('controlled post-create transport disconnect') - } - expect(method).toBe('terminal.createAgentSession') - calls.push(params) - events.push(`transport-${calls.length}`) - try { - const result = await runtime.createAgentSession(params, { clientId: 'paired-fork' }) - events.push('reclaimed') - replies.push(result) - return { ok: true, result } - } catch (error) { - events.push('host-failure-reply-lost') - expect(calls).toHaveLength(1) - expect(error).toMatchObject({ agentSessionOperationOutcome: 'unknown' }) - throw new Error('controlled lost transport reply') - } - } - ) - return { - store, - workspaceId, - root, - process, - provider, - events, - writes, - calls, - replies, - transport, - compile, - create, - spawn, - persist, - physicalSpawn: physical.spawn, - releaseBinding() { - binding.reject(new Error('controlled binding disk failure')) - }, - async failBindingAfterHandoff(prompt: string) { - await vi.waitFor(() => expect(persist).toHaveBeenCalledOnce()) - expect(writes).toEqual([]) - // Real shell readiness and startup write execute while the actual disk await is held. - const listeners = Array.from(dataListeners) - for (const listener of listeners) { - listener(`${SHELL_READY_MARKER_PREFIX}\x07$ `) - } - await vi.waitFor(() => expect(writes).toHaveLength(1), { timeout: 3000 }) - expect(stage).toHaveBeenCalledOnce() - const staged = stage.mock.results[0]?.value - expect(staged?.delivery).toBe('staged') - expect(staged?.scriptPath).toBeDefined() - const command = stage.mock.calls[0]![0].command - expect(command).toBe(spawn.mock.calls[0]?.[0].command) - expect(command).toContain('--prefill') - expect(command).toContain(prompt) - expect(readFileSync(staged!.scriptPath!, 'utf8')).toContain(`${command}\n`) - expect(writes[0]).toBe( - buildStartupCommandSubmission(staged!.command, { bracketedPasteSafe: false }) - ) - events.push('binding-failed') - binding.reject(new Error('controlled binding disk failure')) - }, - exit() { - exit?.({ exitCode: 0 }) - } - } -}