From d34ea8a6c14e623dddeb5710cb7816f618d4af09 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:30:13 -0800 Subject: [PATCH] fix(workspaces): close review gaps in folder project setup - Whole-project trust sends an explicit run for folder creates the policy would run, since it carries no content hash. - Folder setup skips file access for a skipped setup and never starts a stopped WSL distro for a create nobody started; removal does the same. - Runtime folder creates return the trust mismatch, so the window re-asks. - The composer hides folder setup controls on hosts without worktree.folder-setup.v1 and keeps their old explicit skip. - Hook checks read a folder only on the host that owns it. - Git archive hooks get the removed workspace's id; WSL hooks blank inherited pane identity too. - Runner files are written through the drive path WSL needs for its drive mounts, and kept out of git status with .orca/.gitignore. - The CLI's older-host warning covers --agent creates and --json output. --- .../handlers/folder-setup-support-warning.ts | 37 +++++++++---- .../handlers/worktree-create-agent-launch.ts | 19 ++++++- src/cli/handlers/worktree.ts | 18 +++---- .../register-worktree-hook-check-handler.ts | 12 ++++- .../create/folder-workspace-creation.ts | 3 +- .../removal/execute-worktree-removal.ts | 3 +- .../runtime-repository-hooks-commands.ts | 9 ++-- .../runtime-folder-worktree-create.ts | 4 ++ .../creation/runtime-folder-worktree-setup.ts | 17 ++++-- ...ntime-registered-local-worktree-removal.ts | 3 +- .../removal/workspace-registration-removal.ts | 3 ++ .../folder-setup-runner-files.ts | 12 ++++- src/main/workspace-hooks/hook-orca-cli-env.ts | 11 ++-- src/main/workspace-hooks/hooks.ts | 2 +- .../setup-hook-env-vars.test.ts | 27 ++++++++++ .../workspace-hooks/setup-hook-env-vars.ts | 7 ++- .../workspace-hooks/worktree-runner-script.ts | 16 ++++-- .../removal/folder-workspace-archive-hook.ts | 11 +++- .../settings/repository/RepositoryPane.tsx | 2 +- .../composer-submit-orchestration.ts | 1 + .../composer-state/derived-composer-state.ts | 10 ++-- .../src/hooks/composer-state/derived-model.ts | 2 + .../quick-submit-input-contract.ts | 1 + .../quick-submit-preparation.ts | 9 +++- .../use-folder-setup-supported.ts | 20 ++++--- .../src/lib/workspace-setup-trust.test.ts | 52 +++++++++++++++++++ src/renderer/src/lib/workspace-setup-trust.ts | 40 ++++++++++++-- 27 files changed, 282 insertions(+), 69 deletions(-) create mode 100644 src/main/workspace-hooks/setup-hook-env-vars.test.ts rename src/renderer/src/{components/settings/repository/execution => lib}/use-folder-setup-supported.ts (66%) create mode 100644 src/renderer/src/lib/workspace-setup-trust.test.ts diff --git a/src/cli/handlers/folder-setup-support-warning.ts b/src/cli/handlers/folder-setup-support-warning.ts index f0b8ce50bfe..35ac1902463 100644 --- a/src/cli/handlers/folder-setup-support-warning.ts +++ b/src/cli/handlers/folder-setup-support-warning.ts @@ -3,20 +3,35 @@ import type { RuntimeStatus } from '../../shared/runtime-types' import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR } from '../../shared/worktree/id' import { WORKTREE_FOLDER_SETUP_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities' +const FOLDER_SETUP_UNSUPPORTED_WARNING = + 'Setup did not run: this host runs an older Orca without folder workspace setup. Update Orca on that host to run it.' + /** An older host makes folder workspaces without running setup; say so rather than imply it ran. */ -export async function warnIfFolderSetupUnsupported( +export async function folderSetupUnsupportedWarning( client: RuntimeClient, worktreeId: string | undefined, - setupRequested: boolean, - json: boolean -): Promise { - if (json || !setupRequested || !worktreeId?.includes(FOLDER_WORKSPACE_INSTANCE_SEPARATOR)) { - return + create: { setupDecision?: unknown; runHooks?: unknown } +): Promise { + const setupRequested = create.setupDecision === 'run' || create.runHooks === true + if (!setupRequested || !worktreeId?.includes(FOLDER_WORKSPACE_INSTANCE_SEPARATOR)) { + return null } const status = await client.call('status.get').catch(() => null) - if (status && !status.result.capabilities?.includes(WORKTREE_FOLDER_SETUP_RUNTIME_CAPABILITY)) { - console.error( - 'warning: Setup did not run: this host runs an older Orca without folder workspace setup. Update Orca on that host to run it.' - ) - } + return status && !status.result.capabilities?.includes(WORKTREE_FOLDER_SETUP_RUNTIME_CAPABILITY) + ? FOLDER_SETUP_UNSUPPORTED_WARNING + : null +} + +/** Joins the warning onto a create result, so text output and --json both carry it. */ +export async function withFolderSetupSupportWarning< + T extends { worktree?: { id?: string }; warning?: string } +>( + client: RuntimeClient, + result: T, + create: { setupDecision?: unknown; runHooks?: unknown } +): Promise { + const warning = await folderSetupUnsupportedWarning(client, result.worktree?.id, create) + return warning + ? { ...result, warning: result.warning ? `${result.warning} ${warning}` : warning } + : result } diff --git a/src/cli/handlers/worktree-create-agent-launch.ts b/src/cli/handlers/worktree-create-agent-launch.ts index 05f24c713ef..494ee350859 100644 --- a/src/cli/handlers/worktree-create-agent-launch.ts +++ b/src/cli/handlers/worktree-create-agent-launch.ts @@ -1,5 +1,9 @@ // Use agent.launch for surface/model/effort; older hosts fall back to the create startup terminal. +import { + folderSetupUnsupportedWarning, + withFolderSetupSupportWarning +} from './folder-setup-support-warning' import type { AgentLaunchResult } from '../../shared/agent-launch/contracts/agent-launch-intent' import { AGENT_LAUNCH_LOCAL_PRESENTATION_RUNTIME_CAPABILITY, @@ -65,7 +69,7 @@ export async function createWorktreeWithAgent(args: { startupPrompt: launch.prompt?.text ?? '', launchSource: 'cli' } - const created = await withSetupDecisionRecovery( + const response = await withSetupDecisionRecovery( withCliAgentLaunchRecovery( client.call('worktree.create', params), { @@ -74,6 +78,10 @@ export async function createWorktreeWithAgent(args: { } ) ) + const created = { + ...response, + result: await withFolderSetupSupportWarning(client, response.result, create) + } printHookWarning(created.result, json) printLineageSummary(created.result, json) printResult(created, json, formatWorktreeShow) @@ -93,6 +101,15 @@ export async function createWorktreeWithAgent(args: { launch.operationId !== undefined ) const worktree = await showLaunchedWorktree(client, launched.result.worktreeId) + const setupWarning = await folderSetupUnsupportedWarning( + client, + launched.result.worktreeId, + create + ) + if (setupWarning) { + // stderr keeps --json output parseable while still reporting the skipped setup. + console.error(`warning: ${setupWarning}`) + } const result: WorktreeAgentLaunchResult = { ...(worktree ? { diff --git a/src/cli/handlers/worktree.ts b/src/cli/handlers/worktree.ts index 36366c3381b..5f4acb7f34b 100644 --- a/src/cli/handlers/worktree.ts +++ b/src/cli/handlers/worktree.ts @@ -1,4 +1,4 @@ -import { warnIfFolderSetupUnsupported } from './folder-setup-support-warning' +import { withFolderSetupSupportWarning } from './folder-setup-support-warning' import { withWorktreeSelectorRecovery } from '../worktree-selector-recovery' import type { RuntimeWorktreeListResult, @@ -208,15 +208,13 @@ export const WORKTREE_HANDLERS: Record = { const result = await withSetupDecisionRecovery( callNamingParentEnvironment(client, 'worktree.create', create) ) - printHookWarning(result.result, json) - await warnIfFolderSetupUnsupported( - client, - result.result.worktree?.id, - setupDecision === 'run' || flags.get('run-hooks') === true, - json - ) - printLineageSummary(result.result, json) - printResult(result, json, formatWorktreeShow) + const created = { + ...result, + result: await withFolderSetupSupportWarning(client, result.result, create) + } + printHookWarning(created.result, json) + printLineageSummary(created.result, json) + printResult(created, json, formatWorktreeShow) }, 'worktree set': async ({ flags, client, cwd, json }) => { assertWorktreeParentFlagsCompatible( diff --git a/src/main/ipc/hooks/register-worktree-hook-check-handler.ts b/src/main/ipc/hooks/register-worktree-hook-check-handler.ts index 3feb478acfa..ae5ac61df6f 100644 --- a/src/main/ipc/hooks/register-worktree-hook-check-handler.ts +++ b/src/main/ipc/hooks/register-worktree-hook-check-handler.ts @@ -1,6 +1,11 @@ import { ipcMain } from 'electron' -import { getRepoDialableSshTargetId, type ExecutionHostId } from '../../../shared/execution-host' +import { + getRepoDialableSshTargetId, + isRepoOnCatalogHost, + type ExecutionHostId +} from '../../../shared/execution-host' import { scopeHooksToRepoKind } from '../../../shared/folder-workspace-hooks' +import { isFolderRepo } from '../../../shared/repo-kind' import { hasHooksFile, loadHooks, hasUnrecognizedOrcaYamlKeys } from '../../workspace-hooks/hooks' import { resolveRepoForExecutionHost } from '../worktrees/repo-host-ownership' import { blockedWslDistroForPath } from '../../wsl/filesystem/wsl-unc-access-gate' @@ -23,6 +28,11 @@ export function registerWorktreeHookCheckHandler(context: WorktreeIpcContext): v mayNeedUpdate: false } } + // A folder owned by another host has no hooks here; its own host reports them. + if (isFolderRepo(repo) && !isRepoOnCatalogHost(repo)) { + return { status: 'ok', hasHooks: false, hooks: null, mayNeedUpdate: false } + } + if (getRepoDialableSshTargetId(repo)) { return { status: 'error', diff --git a/src/main/ipc/worktrees/create/folder-workspace-creation.ts b/src/main/ipc/worktrees/create/folder-workspace-creation.ts index a2d9d9e649b..b3225c00f54 100644 --- a/src/main/ipc/worktrees/create/folder-workspace-creation.ts +++ b/src/main/ipc/worktrees/create/folder-workspace-creation.ts @@ -72,7 +72,8 @@ export async function createFolderWorkspace( const worktree = mergeFolderWorkspace(repo, worktreeId, meta) // The window opens the Setup tab from `setup`, as for a new worktree. const prepared = await prepareFolderWorktreeSetup({ - request: args, + // A desktop create is the user's act, as for a new worktree. + request: { ...args, wslUserAct: true }, repo, worktree, settings: store.getSettings(), diff --git a/src/main/ipc/worktrees/removal/execute-worktree-removal.ts b/src/main/ipc/worktrees/removal/execute-worktree-removal.ts index deed7b0be72..45cd106494f 100644 --- a/src/main/ipc/worktrees/removal/execute-worktree-removal.ts +++ b/src/main/ipc/worktrees/removal/execute-worktree-removal.ts @@ -179,7 +179,8 @@ export async function executeWorktreeRemoval( canonicalWorktreePath, repo, undefined, - localWorktreeGitOptions + localWorktreeGitOptions, + { identity: { worktreeId: args.worktreeId } } ) archiveHookOverride = gateWorktreeRemovalOnArchiveHook({ worktreePath: canonicalWorktreePath, diff --git a/src/main/runtime/repositories/runtime-repository-hooks-commands.ts b/src/main/runtime/repositories/runtime-repository-hooks-commands.ts index 148a30b81fd..844dc691151 100644 --- a/src/main/runtime/repositories/runtime-repository-hooks-commands.ts +++ b/src/main/runtime/repositories/runtime-repository-hooks-commands.ts @@ -1,4 +1,4 @@ -import { getRepoDialableSshTargetId } from '../../../shared/execution-host' +import { getRepoDialableSshTargetId, isRepoOnCatalogHost } from '../../../shared/execution-host' import { scopeHooksToRepoKind } from '../../../shared/folder-workspace-hooks' import { windowsFsPath } from '../../wsl/filesystem/wsl-unc-drive-fs-path' import { readFile } from 'node:fs/promises' @@ -30,8 +30,8 @@ export class RuntimeRepositoryHooksCommands { async getRepoHooks(repoSelector: string) { const repo = await this.deps.resolveRepo(repoSelector) const connectionId = getRepoDialableSshTargetId(repo) - // Why: an `ssh:` repo is not served here; it reports no hooks file. - if (connectionId) { + // Why: an `ssh:` repo is not served here, nor a folder another host owns; neither reports hooks. + if (connectionId || (isFolderRepo(repo) && !isRepoOnCatalogHost(repo))) { return { hasHooksFile: false, hooks: null, @@ -62,6 +62,9 @@ export class RuntimeRepositoryHooksCommands { async checkRepoHooks(repoSelector: string, options: { background?: boolean } = {}) { const repo = await this.deps.resolveRepo(repoSelector) + if (isFolderRepo(repo) && !isRepoOnCatalogHost(repo)) { + return { status: 'ok' as const, hasHooks: false, hooks: null, mayNeedUpdate: false } + } const connectionId = getRepoDialableSshTargetId(repo) if (connectionId) { return { status: 'error' as const, hasHooks: false, hooks: null, mayNeedUpdate: false } diff --git a/src/main/runtime/workspaces/creation/runtime-folder-worktree-create.ts b/src/main/runtime/workspaces/creation/runtime-folder-worktree-create.ts index ad0c8c0ebe5..1aecde1f210 100644 --- a/src/main/runtime/workspaces/creation/runtime-folder-worktree-create.ts +++ b/src/main/runtime/workspaces/creation/runtime-folder-worktree-create.ts @@ -276,6 +276,10 @@ export async function createRuntimeFolderWorktree(args: { ...(preparedSetup && request.awaitTerminalProvisioning ? { setupReceipt: buildRuntimeSetupReceipt(preparedSetup, false, null) } : {}), + // The window re-asks with this content, then runs the approved setup. + ...(preparedSetup?.setupTrustMismatch + ? { setupTrustMismatch: preparedSetup.setupTrustMismatch } + : {}), ...(warning ? { warning } : {}) } } diff --git a/src/main/runtime/workspaces/creation/runtime-folder-worktree-setup.ts b/src/main/runtime/workspaces/creation/runtime-folder-worktree-setup.ts index 633666f28ea..7e1595156b6 100644 --- a/src/main/runtime/workspaces/creation/runtime-folder-worktree-setup.ts +++ b/src/main/runtime/workspaces/creation/runtime-folder-worktree-setup.ts @@ -17,8 +17,10 @@ import type { import type { RuntimeManagedWorktreeCreateArgs } from './runtime-managed-worktree-create-types' import { buildRuntimeSetupReceipt, - prepareRuntimeLocalWorktreeSetup + prepareRuntimeLocalWorktreeSetup, + resolveRuntimeSetupDecision } from './runtime-local-worktree-setup' +import { blockedWslDistroForPath } from '../../../wsl/filesystem/wsl-unc-access-gate' export type RuntimeFolderWorktreeSetupDeps = { runtimeTarget: () => { wslDistro?: string } | undefined @@ -32,17 +34,24 @@ type PreparedFolderSetup = Awaited[0]['request'] + request: Parameters[0]['request'] & { + wslUserAct?: true + } repo: Repo worktree: Pick settings: ReturnType runtimeTarget: () => { wslDistro?: string } | undefined shouldUseSetupRunner: boolean }): Promise { - const { repo, worktree } = args - if (!isRepoOnCatalogHost(repo)) { + const { repo, worktree, request } = args + // A skipped setup needs no file access, so metadata-only creates stay metadata-only. + if (!isRepoOnCatalogHost(repo) || resolveRuntimeSetupDecision(request) === 'skip') { return undefined } + // Only a create someone started may start the folder's stopped WSL distro. + if (!request.wslUserAct && (await blockedWslDistroForPath(repo.path))) { + return { warning: "Setup did not run because the folder's WSL distro isn't running." } + } try { return await prepareRuntimeLocalWorktreeSetup({ request: args.request, diff --git a/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts b/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts index 3ef174772f6..cb942c3efbb 100644 --- a/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts +++ b/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts @@ -101,7 +101,8 @@ async function acceptRuntimeRegisteredLocalWorktreeRemoval(args: { canonicalPath, repo, undefined, - args.hasLocalOptions ? localOptions : undefined + args.hasLocalOptions ? localOptions : undefined, + { identity: { worktreeId: args.target.id } } ) archiveHookOverride = gateWorktreeRemovalOnArchiveHook({ worktreePath: canonicalPath, diff --git a/src/main/runtime/workspaces/removal/workspace-registration-removal.ts b/src/main/runtime/workspaces/removal/workspace-registration-removal.ts index 0090c5ac466..2a8c12a6d04 100644 --- a/src/main/runtime/workspaces/removal/workspace-registration-removal.ts +++ b/src/main/runtime/workspaces/removal/workspace-registration-removal.ts @@ -9,6 +9,7 @@ import { isRepoOnCatalogHost, parseExecutionHostId } from '../../../../shared/ex import type { RemoveWorktreeResult } from '../../../../shared/worktree/create-types' import { readWorktreeMetaForRepo } from '../../../persistence/host-qualified-worktree-meta' import { getEffectiveHooks } from '../../../workspace-hooks/hooks' +import { blockedWslDistroForPath } from '../../../wsl/filesystem/wsl-unc-access-gate' import { getLocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' import { gateFolderWorkspaceRemovalOnArchiveHook, @@ -130,9 +131,11 @@ export async function removeOrphanOrFolderWorktree({ allowFailure: archive.allowFailedArchiveHook, runtimeTarget: () => getLocalProjectWorktreeGitOptions(store, repo) }) + // Without --run-hooks, look at the folder only to warn, and never start its stopped WSL distro for that. const archiveSkipped = !archive.runHooks && isRepoOnCatalogHost(repo) && + !(await blockedWslDistroForPath(repo.path)) && Boolean(getEffectiveHooks(repo)?.scripts.archive) // Use the resolved SSH owner, including executionHostId-only rows; runtime-nested targets belong to that environment's namespace. const folderHost = parseExecutionHostId(removalHostId) diff --git a/src/main/workspace-hooks/folder-setup-runner-files.ts b/src/main/workspace-hooks/folder-setup-runner-files.ts index 7a3a4ee7f5c..614d568e967 100644 --- a/src/main/workspace-hooks/folder-setup-runner-files.ts +++ b/src/main/workspace-hooks/folder-setup-runner-files.ts @@ -1,7 +1,8 @@ import { randomUUID } from 'node:crypto' -import { readdir, unlink } from 'node:fs/promises' +import { readdir, unlink, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR } from '../../shared/worktree/id' +import { windowsFsPath } from '../wsl/filesystem/wsl-unc-drive-fs-path' const FOLDER_RUNNER_DIR = '.orca' @@ -27,12 +28,19 @@ export function newFolderSetupRunnerPath( ) } +/** A folder may itself be a Git checkout; keep its runners out of `git status` without editing its files. */ +export async function ignoreFolderSetupRunners(runnerDirFsPath: string): Promise { + await writeFile(join(runnerDirFsPath, '.gitignore'), 'setup-runner-*\n.gitignore\n', { + flag: 'wx' + }).catch(() => undefined) +} + /** Call after the workspace's processes stopped, so no running script loses its file. */ export async function removeFolderSetupRunnerFiles( folderPath: string, worktreeId: string ): Promise { - const dir = join(folderPath, FOLDER_RUNNER_DIR) + const dir = windowsFsPath(join(folderPath, FOLDER_RUNNER_DIR)) const prefix = runnerPrefix(worktreeId) const names: string[] = await readdir(dir).catch((): string[] => []) await Promise.all( diff --git a/src/main/workspace-hooks/hook-orca-cli-env.ts b/src/main/workspace-hooks/hook-orca-cli-env.ts index 03ab7e4c8c3..503f1c84e36 100644 --- a/src/main/workspace-hooks/hook-orca-cli-env.ts +++ b/src/main/workspace-hooks/hook-orca-cli-env.ts @@ -41,10 +41,14 @@ export function applyHostHookOrcaCliEnv(env: Record) Object.assign(env, childEnv) } -/** The guest env and a script prefix that puts the managed WSL CLI first on PATH. */ +/** + * The guest env and a script prefix that puts the managed WSL CLI first on PATH. Inherited pane + * identity is blanked, since wsl.exe would otherwise carry the host's values in through WSLENV. + */ export function wslHookOrcaCliEnv(): { env: Record; scriptPrefix: string } { + const blankedIdentity = Object.fromEntries(INHERITED_PANE_IDENTITY_KEYS.map((key) => [key, ''])) if (!hasAppEnvironment()) { - return { env: {}, scriptPrefix: '' } + return { env: blankedIdentity, scriptPrefix: '' } } const app = getAppEnvironment() const userDataPath = app.getPath('userData') @@ -54,10 +58,11 @@ export function wslHookOrcaCliEnv(): { env: Record; scriptPrefix ...(process.resourcesPath ? { resourcesPath: process.resourcesPath } : {}) }) if (!managedCliDir) { - return { env: {}, scriptPrefix: '' } + return { env: blankedIdentity, scriptPrefix: '' } } return { env: { + ...blankedIdentity, ORCA_WSL_CLI_DIR: toLinuxPath(managedCliDir), ORCA_CLI_COMMAND: getWslCliCommandName(app.isPackaged()), ORCA_USER_DATA_PATH: toLinuxPath(userDataPath) diff --git a/src/main/workspace-hooks/hooks.ts b/src/main/workspace-hooks/hooks.ts index 937198cbfe5..e43a6899f12 100644 --- a/src/main/workspace-hooks/hooks.ts +++ b/src/main/workspace-hooks/hooks.ts @@ -210,7 +210,7 @@ export function runHook( // Forward unattended Git flags to WSL; keep host askpass out of the guest. const guardedEnv = promptGuardShellEnv(wslEnv) const wslCli = wslHookOrcaCliEnv() - const guestEnv: Record = { ...wslEnv, ...wslCli.env } + const guestEnv: Record = { ...wslCli.env, ...wslEnv } for (const [key, value] of Object.entries(guardedEnv)) { if (value !== undefined && (key === 'GIT_TERMINAL_PROMPT' || key === 'GCM_INTERACTIVE')) { guestEnv[key] = value diff --git a/src/main/workspace-hooks/setup-hook-env-vars.test.ts b/src/main/workspace-hooks/setup-hook-env-vars.test.ts new file mode 100644 index 00000000000..d1e362dd95e --- /dev/null +++ b/src/main/workspace-hooks/setup-hook-env-vars.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest' +import type { Repo } from '../../shared/repo-types' +import { getSetupEnvVars } from './setup-hook-env-vars' + +const folder: Repo = { + id: 'repo', + path: '/code/acme', + displayName: 'acme', + badgeColor: '', + addedAt: 0, + kind: 'folder' +} + +describe('getSetupEnvVars', () => { + it('names a folder workspace by its own name and id, which `orca worktree create` reads', () => { + const env = getSetupEnvVars(folder, '/code/acme', { + worktreeId: 'repo::/code/acme::workspace:1', + displayName: 'Fix login' + }) + expect(env).toMatchObject({ + ORCA_WORKSPACE_NAME: 'Fix login', + ORCA_WORKTREE_ID: 'repo::/code/acme::workspace:1', + ORCA_WORKSPACE_ID: 'repo::/code/acme::workspace:1', + ORCA_ROOT_PATH: '/code/acme' + }) + }) +}) diff --git a/src/main/workspace-hooks/setup-hook-env-vars.ts b/src/main/workspace-hooks/setup-hook-env-vars.ts index 9181db25d5f..de466f4aa93 100644 --- a/src/main/workspace-hooks/setup-hook-env-vars.ts +++ b/src/main/workspace-hooks/setup-hook-env-vars.ts @@ -6,7 +6,8 @@ import { isFolderRepo } from '../../shared/repo-kind' /** The workspace a hook runs for; folder workspaces share one directory, so the path can't name them. */ export type HookWorkspaceIdentity = { worktreeId: string - displayName: string + /** Names a folder workspace; a worktree's name is its directory's. */ + displayName?: string } // Keep WSL path translation in pty/wsl-orca-env.ts in sync; names and policies are not paths. @@ -26,7 +27,9 @@ export function getSetupEnvVars( ORCA_ROOT_PATH: repo.path, ORCA_WORKTREE_PATH: worktreePath, ORCA_WORKSPACE_NAME: - identity && isFolderRepo(repo) ? identity.displayName : getRuntimePathBasename(worktreePath), + identity?.displayName && isFolderRepo(repo) + ? identity.displayName + : getRuntimePathBasename(worktreePath), // Same values a pane sets, so `orca worktree create` in the hook attaches to this workspace. ...(identity ? { ORCA_WORKSPACE_ID: identity.worktreeId, ORCA_WORKTREE_ID: identity.worktreeId } diff --git a/src/main/workspace-hooks/worktree-runner-script.ts b/src/main/workspace-hooks/worktree-runner-script.ts index f214394cdc5..1fe1c783225 100644 --- a/src/main/workspace-hooks/worktree-runner-script.ts +++ b/src/main/workspace-hooks/worktree-runner-script.ts @@ -14,6 +14,7 @@ import { readWorktreeGitPath } from '../git/worktrees/catalog/worktree-git-path' import { resolveWslWorktreeGitPath } from '../git/worktrees/catalog/wsl-worktree-git-path' import { knownWslAutomountRoots } from '../wsl/filesystem/wsl-automount-root' import { isWslPath } from '../wsl/filesystem/unc-path-access' +import { windowsFsPath } from '../wsl/filesystem/wsl-unc-drive-fs-path' import { toWindowsWslPath, toLinuxPath } from '../../shared/wsl-paths' import { getHookRuntimeTarget, @@ -25,7 +26,7 @@ import { getSetupRunnerEnvVars, type HookWorkspaceIdentity } from './setup-hook-env-vars' -import { newFolderSetupRunnerPath } from './folder-setup-runner-files' +import { ignoreFolderSetupRunners, newFolderSetupRunnerPath } from './folder-setup-runner-files' import { isFolderRepo } from '../../shared/repo-kind' import { buildPosixRunnerScript, buildWindowsRunnerScript } from './setup-runner-script-text' @@ -112,14 +113,19 @@ async function createWorktreeRunnerScript(args: { ) : await resolveGitRunnerScriptPath(worktreePath, runnerBaseName, runnerExtension, runtimeTarget) - await mkdir(dirname(runnerScriptPath), { recursive: true }) + // Write through the drive path when WSL refuses its drive mounts over UNC; launch keeps the UNC spelling. + const runnerFsPath = windowsFsPath(runnerScriptPath) + await mkdir(dirname(runnerFsPath), { recursive: true }) + if (isFolderRepo(repo)) { + await ignoreFolderSetupRunners(dirname(runnerFsPath)) + } if (runnerShell.family === 'cmd') { - await writeFile(runnerScriptPath, buildWindowsRunnerScript(script), 'utf-8') + await writeFile(runnerFsPath, buildWindowsRunnerScript(script), 'utf-8') } else { - await writeFile(runnerScriptPath, buildPosixRunnerScript(script), 'utf-8') + await writeFile(runnerFsPath, buildPosixRunnerScript(script), 'utf-8') if (!nativeWindowsWorktree) { - await chmod(runnerScriptPath, 0o755) + await chmod(runnerFsPath, 0o755) } } diff --git a/src/main/workspaces/removal/folder-workspace-archive-hook.ts b/src/main/workspaces/removal/folder-workspace-archive-hook.ts index 2485b85cbfe..cdcd627ad7e 100644 --- a/src/main/workspaces/removal/folder-workspace-archive-hook.ts +++ b/src/main/workspaces/removal/folder-workspace-archive-hook.ts @@ -5,6 +5,7 @@ import { removeFolderSetupRunnerFiles } from '../../workspace-hooks/folder-setup import { getEffectiveHooks, runHook } from '../../workspace-hooks/hooks' import type { HookRuntimeTarget } from '../../workspace-hooks/hook-runtime-target' import { gateWorktreeRemovalOnArchiveHook } from './worktree-archive-hook-gate' +import { blockedWslDistroForPath } from '../../wsl/filesystem/wsl-unc-access-gate' /** * Run a folder workspace's archive script before anything is torn down, as worktree removal does. @@ -34,7 +35,13 @@ export async function gateFolderWorkspaceRemovalOnArchiveHook(args: { /** Runner files are per launch; drop this workspace's once its processes have stopped. */ export function removeFolderWorkspaceRunnerFiles(repo: Repo, worktreeId: string): void { - if (isRepoOnCatalogHost(repo)) { - void removeFolderSetupRunnerFiles(repo.path, worktreeId) + if (!isRepoOnCatalogHost(repo)) { + return } + // A stopped distro keeps its leftover runners rather than starting for cleanup. + void blockedWslDistroForPath(repo.path) + .then((blocked) => (blocked ? undefined : removeFolderSetupRunnerFiles(repo.path, worktreeId))) + .catch((error: unknown) => { + console.warn(`[hooks] could not clean setup runners in ${repo.path}:`, error) + }) } diff --git a/src/renderer/src/components/settings/repository/RepositoryPane.tsx b/src/renderer/src/components/settings/repository/RepositoryPane.tsx index 35444bb9248..bf249b99ff5 100644 --- a/src/renderer/src/components/settings/repository/RepositoryPane.tsx +++ b/src/renderer/src/components/settings/repository/RepositoryPane.tsx @@ -5,7 +5,7 @@ import type { Project, ProjectUpdateArgs } from '../../../../../shared/project-t import type { Repo } from '../../../../../shared/repo-types' import type { SourceControlAiSettingsPatch } from '../../../../../shared/source-control/ai/settings/source-control-ai-settings-types' import { getRepoKindLabel, isFolderRepo } from '../../../../../shared/repo-kind' -import { useFolderSetupSupported } from './execution/use-folder-setup-supported' +import { useFolderSetupSupported } from '@/lib/use-folder-setup-supported' import { getRepoExecutionHostId, type ExecutionHostId } from '../../../../../shared/execution-host' import { Label } from '../../ui/label' import { useShallow } from 'zustand/react/shallow' diff --git a/src/renderer/src/hooks/composer-state/composer-submit-orchestration.ts b/src/renderer/src/hooks/composer-state/composer-submit-orchestration.ts index 42e2a840e12..f16e989d1b7 100644 --- a/src/renderer/src/hooks/composer-state/composer-submit-orchestration.ts +++ b/src/renderer/src/hooks/composer-state/composer-submit-orchestration.ts @@ -87,6 +87,7 @@ export function useComposerSubmitOrchestration( setAdvancedOpen: target.asyncComposerState.setAdvancedOpen, settings: target.composerTargetStore.settings, setupConfig: target.derivedComposerState.setupConfig, + setupSupported: target.derivedComposerState.setupSupported, setupDecision: target.asyncComposerState.setupDecision, setupPolicy: target.derivedComposerState.setupPolicy, smartNameMode: target.workspaceIdentityState.smartNameMode 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 566397470e0..07e17080d0a 100644 --- a/src/renderer/src/hooks/composer-state/derived-composer-state.ts +++ b/src/renderer/src/hooks/composer-state/derived-composer-state.ts @@ -1,3 +1,4 @@ +import { useFolderSetupSupported } from '@/lib/use-folder-setup-supported' import type { DerivedComposerStateInput } from './composer-target-input-contracts' import { useMemo } from 'react' @@ -119,11 +120,13 @@ export function useDerivedComposerState(input: DerivedComposerStateInput) { const currentYamlHooks = checkedHooksContextKey === selectedRepoHookContextKey ? yamlHooks : null + const setupSupported = useFolderSetupSupported(selectedRepo) const setupConfig = useMemo( - () => (selectedRepo ? getSetupConfig(selectedRepo, currentYamlHooks) : null), - [currentYamlHooks, selectedRepo] + () => (selectedRepo && setupSupported ? getSetupConfig(selectedRepo, currentYamlHooks) : null), + [currentYamlHooks, selectedRepo, setupSupported] ) const isSetupCheckPending = + setupSupported && Boolean(selectedRepo) && Boolean(selectedRepoHookContextKey) && checkedHooksContextKey !== selectedRepoHookContextKey @@ -136,7 +139,7 @@ export function useDerivedComposerState(input: DerivedComposerStateInput) { selectedRepo, setupConfig, setupDecision, - selectedRepoIsGit, + setupSupported, isSetupCheckPending ) const linkedWorkItemProvider = linkedWorkItem ? getLinkedWorkItemProvider(linkedWorkItem) : null @@ -239,6 +242,7 @@ export function useDerivedComposerState(input: DerivedComposerStateInput) { effectiveLinkedPR, currentYamlHooks, setupConfig, + setupSupported, setupPolicy, linkedWorkItemProvider, requiresExplicitSetupChoice, diff --git a/src/renderer/src/hooks/composer-state/derived-model.ts b/src/renderer/src/hooks/composer-state/derived-model.ts index 2e05511fbd7..0f2df8b61ce 100644 --- a/src/renderer/src/hooks/composer-state/derived-model.ts +++ b/src/renderer/src/hooks/composer-state/derived-model.ts @@ -15,6 +15,8 @@ export type ComposerDerivedModel = { effectiveLinkedPR: number | null currentYamlHooks: OrcaHooks | null setupConfig: SetupConfig | null + /** False for a folder project whose host predates folder setup; its setup controls stay hidden. */ + setupSupported: boolean setupPolicy: SetupRunPolicy linkedWorkItemProvider: 'github' | 'gitlab' | 'linear' | 'jira' | null requiresExplicitSetupChoice: boolean diff --git a/src/renderer/src/hooks/composer-state/quick-submit-input-contract.ts b/src/renderer/src/hooks/composer-state/quick-submit-input-contract.ts index ea5fa328e69..6de6c8c2217 100644 --- a/src/renderer/src/hooks/composer-state/quick-submit-input-contract.ts +++ b/src/renderer/src/hooks/composer-state/quick-submit-input-contract.ts @@ -22,6 +22,7 @@ export type QuickSubmitPreparationInput = Pick< | 'setAdvancedOpen' | 'settings' | 'setupConfig' + | 'setupSupported' | 'setupDecision' | 'setupPolicy' | 'smartNameMode' 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 a1cd70f639f..053e1d34b21 100644 --- a/src/renderer/src/hooks/composer-state/quick-submit-preparation.ts +++ b/src/renderer/src/hooks/composer-state/quick-submit-preparation.ts @@ -41,6 +41,7 @@ export function useQuickSubmitPreparation(input: QuickSubmitPreparationInput) { setAdvancedOpen, settings, setupConfig, + setupSupported, setupDecision, setupPolicy, smartNameMode @@ -77,6 +78,7 @@ export function useQuickSubmitPreparation(input: QuickSubmitPreparationInput) { let submitResolvedSetupDecision = resolvedSetupDecision if ( + setupSupported && setupPolicy === 'ask' && selectedRepoHookContextKey && checkedHooksContextKey !== selectedRepoHookContextKey @@ -103,8 +105,10 @@ export function useQuickSubmitPreparation(input: QuickSubmitPreparationInput) { return null } - // Folder projects inherit too; a host without folder setup ignores it for them. - const effectiveSetupDecision: SetupDecision = submitResolvedSetupDecision ?? 'inherit' + // A folder host that predates folder setup keeps the old explicit skip. + const effectiveSetupDecision: SetupDecision = setupSupported + ? (submitResolvedSetupDecision ?? 'inherit') + : 'skip' const submitLinkedWorkItemProvider = submitLinkedWorkItem ? getLinkedWorkItemProvider(submitLinkedWorkItem) : null @@ -219,6 +223,7 @@ export function useQuickSubmitPreparation(input: QuickSubmitPreparationInput) { setAdvancedOpen, settings, setupConfig, + setupSupported, setupDecision, setupPolicy, smartNameMode, diff --git a/src/renderer/src/components/settings/repository/execution/use-folder-setup-supported.ts b/src/renderer/src/lib/use-folder-setup-supported.ts similarity index 66% rename from src/renderer/src/components/settings/repository/execution/use-folder-setup-supported.ts rename to src/renderer/src/lib/use-folder-setup-supported.ts index 42ab580ae75..2669bd83228 100644 --- a/src/renderer/src/components/settings/repository/execution/use-folder-setup-supported.ts +++ b/src/renderer/src/lib/use-folder-setup-supported.ts @@ -1,17 +1,15 @@ import { useEffect, useState } from 'react' -import { - getRepoExecutionHostId, - parseExecutionHostId -} from '../../../../../../shared/execution-host' -import { isFolderRepo } from '../../../../../../shared/repo-kind' -import type { Repo } from '../../../../../../shared/repo-types' -import { WORKTREE_FOLDER_SETUP_RUNTIME_CAPABILITY } from '../../../../../../shared/worktree-runtime-capabilities' +import { getRepoExecutionHostId, parseExecutionHostId } from '../../../shared/execution-host' +import { isFolderRepo } from '../../../shared/repo-kind' +import type { Repo } from '../../../shared/repo-types' +import { WORKTREE_FOLDER_SETUP_RUNTIME_CAPABILITY } from '../../../shared/worktree-runtime-capabilities' import { runtimeEnvironmentSupportsCapability } from '@/runtime/rpc/compatibility/runtime-capability-proof' /** Folder setup runs only on hosts that report it; older hosts would save scripts that never run. */ -export function useFolderSetupSupported(repo: Repo): boolean { - const host = parseExecutionHostId(getRepoExecutionHostId(repo)) - const environmentId = isFolderRepo(repo) && host?.kind === 'runtime' ? host.environmentId : null +export function useFolderSetupSupported(repo: Repo | null | undefined): boolean { + const host = repo ? parseExecutionHostId(getRepoExecutionHostId(repo)) : null + const environmentId = + repo && isFolderRepo(repo) && host?.kind === 'runtime' ? host.environmentId : null const [supportedEnvironmentId, setSupportedEnvironmentId] = useState(null) useEffect(() => { if (!environmentId) { @@ -32,7 +30,7 @@ export function useFolderSetupSupported(repo: Repo): boolean { cancelled = true } }, [environmentId]) - if (!isFolderRepo(repo)) { + if (!repo || !isFolderRepo(repo)) { return true } // An unserved SSH folder runs no hooks; its files aren't on a host Orca runs scripts on. diff --git a/src/renderer/src/lib/workspace-setup-trust.test.ts b/src/renderer/src/lib/workspace-setup-trust.test.ts new file mode 100644 index 00000000000..7926a8f3ce0 --- /dev/null +++ b/src/renderer/src/lib/workspace-setup-trust.test.ts @@ -0,0 +1,52 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { AppState } from '@/store/types' +import { __resetTrustPromptChainForTests } from './ensure-hooks-confirmed' +import { confirmWorkspaceSetupDecision } from './workspace-setup-trust' + +const hooksCheckMock = vi.fn() + +function stateWithRepoWideTrust(kind: 'git' | 'folder'): AppState { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the trust check reads only trustedOrcaHooks, repos and openModal + return { + trustedOrcaHooks: { 'repo-1': { all: { approvedAt: 1 } } }, + repos: [{ id: 'repo-1', displayName: 'acme', kind }], + openModal: () => { + throw new Error('repo-wide trust must not prompt') + } + } as unknown as AppState +} + +describe('confirmWorkspaceSetupDecision under whole-project trust', () => { + beforeEach(() => { + hooksCheckMock.mockReset().mockResolvedValue({ + status: 'ok', + hasHooks: true, + hooks: { scripts: { setup: 'make bootstrap' } }, + mayNeedUpdate: false + }) + vi.stubGlobal('window', { api: { hooks: { check: hooksCheckMock } } }) + __resetTrustPromptChainForTests() + }) + + it('asks a folder host to run setup outright, since the trust carries no content hash', async () => { + const result = await confirmWorkspaceSetupDecision( + stateWithRepoWideTrust('folder'), + 'repo-1', + 'inherit', + 'local', + () => false + ) + expect(result).toMatchObject({ setupDecision: 'run', trustDecision: 'run' }) + }) + + it('leaves a git create on the project policy', async () => { + const result = await confirmWorkspaceSetupDecision( + stateWithRepoWideTrust('git'), + 'repo-1', + 'inherit', + 'local', + () => false + ) + expect(result).toMatchObject({ setupDecision: 'inherit', trustDecision: 'run' }) + }) +}) diff --git a/src/renderer/src/lib/workspace-setup-trust.ts b/src/renderer/src/lib/workspace-setup-trust.ts index a2c60c6e1d2..9fccc8fc59a 100644 --- a/src/renderer/src/lib/workspace-setup-trust.ts +++ b/src/renderer/src/lib/workspace-setup-trust.ts @@ -1,5 +1,6 @@ import type { AppState } from '@/store/types' -import type { ExecutionHostId } from '../../../shared/execution-host' +import { getRepoExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' +import { isFolderRepo } from '../../../shared/repo-kind' 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' @@ -14,7 +15,8 @@ export async function confirmWorkspaceSetupDecision boolean, signal?: AbortSignal ): Promise< - ({ setupDecision: T | 'skip'; trustDecision: 'run' | 'skip' } & ApprovedSetupHashes) | 'cancelled' + | ({ setupDecision: T | 'skip' | 'run'; trustDecision: 'run' | 'skip' } & ApprovedSetupHashes) + | 'cancelled' > { const trust = await settleComposerSubmit( ensureHooksApproved( @@ -32,11 +34,17 @@ export async function confirmWorkspaceSetupDecision 0 ? { approvedSetupHashes } : {}) } } + +/** + * Whole-project trust carries no content hash, and a folder host skips unhashed shared setup as an + * older client's. Say "run" outright where the project's policy would run it anyway. + */ +function explicitFolderRunUnderRepoTrust( + state: AppState, + repoId: string, + ownerHostId: ExecutionHostId | undefined, + decision: T +): T | 'run' { + if (decision !== undefined && decision !== 'inherit') { + return decision + } + const repo = state.repos.find( + (candidate) => + candidate.id === repoId && (!ownerHostId || getRepoExecutionHostId(candidate) === ownerHostId) + ) + return repo && + isFolderRepo(repo) && + (repo.hookSettings?.setupRunPolicy ?? 'run-by-default') === 'run-by-default' + ? 'run' + : decision +}