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.
This commit is contained in:
Brennan Benson
2026-11-08 16:30:13 -08:00
parent 3fbe9a73b7
commit d34ea8a6c1
27 changed files with 282 additions and 69 deletions
@@ -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<void> {
if (json || !setupRequested || !worktreeId?.includes(FOLDER_WORKSPACE_INSTANCE_SEPARATOR)) {
return
create: { setupDecision?: unknown; runHooks?: unknown }
): Promise<string | null> {
const setupRequested = create.setupDecision === 'run' || create.runHooks === true
if (!setupRequested || !worktreeId?.includes(FOLDER_WORKSPACE_INSTANCE_SEPARATOR)) {
return null
}
const status = await client.call<RuntimeStatus>('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<T> {
const warning = await folderSetupUnsupportedWarning(client, result.worktree?.id, create)
return warning
? { ...result, warning: result.warning ? `${result.warning} ${warning}` : warning }
: result
}
@@ -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<RuntimeWorktreeCreateResult>('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
? {
+8 -10
View File
@@ -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<string, CommandHandler> = {
const result = await withSetupDecisionRecovery(
callNamingParentEnvironment<RuntimeWorktreeCreateResult>(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(
@@ -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',
@@ -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(),
@@ -179,7 +179,8 @@ export async function executeWorktreeRemoval(
canonicalWorktreePath,
repo,
undefined,
localWorktreeGitOptions
localWorktreeGitOptions,
{ identity: { worktreeId: args.worktreeId } }
)
archiveHookOverride = gateWorktreeRemovalOnArchiveHook({
worktreePath: canonicalWorktreePath,
@@ -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 }
@@ -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 } : {})
}
}
@@ -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<ReturnType<typeof prepareRuntimeLocalWorktree
* The workspace already exists, so a setup problem becomes a warning, never a failed create.
*/
export async function prepareFolderWorktreeSetup(args: {
request: Parameters<typeof prepareRuntimeLocalWorktreeSetup>[0]['request']
request: Parameters<typeof prepareRuntimeLocalWorktreeSetup>[0]['request'] & {
wslUserAct?: true
}
repo: Repo
worktree: Pick<Worktree, 'id' | 'path' | 'displayName'>
settings: ReturnType<RuntimeStore['getSettings']>
runtimeTarget: () => { wslDistro?: string } | undefined
shouldUseSetupRunner: boolean
}): Promise<PreparedFolderSetup | { warning: string } | undefined> {
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,
@@ -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,
@@ -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)
@@ -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<void> {
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<void> {
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(
@@ -41,10 +41,14 @@ export function applyHostHookOrcaCliEnv(env: Record<string, string | undefined>)
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<string, string>; 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<string, string>; 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)
+1 -1
View File
@@ -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<string, string> = { ...wslEnv, ...wslCli.env }
const guestEnv: Record<string, string> = { ...wslCli.env, ...wslEnv }
for (const [key, value] of Object.entries(guardedEnv)) {
if (value !== undefined && (key === 'GIT_TERMINAL_PROMPT' || key === 'GCM_INTERACTIVE')) {
guestEnv[key] = value
@@ -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'
})
})
})
@@ -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 }
@@ -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)
}
}
@@ -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)
})
}
@@ -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'
@@ -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
@@ -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,
@@ -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
@@ -22,6 +22,7 @@ export type QuickSubmitPreparationInput = Pick<
| 'setAdvancedOpen'
| 'settings'
| 'setupConfig'
| 'setupSupported'
| 'setupDecision'
| 'setupPolicy'
| 'smartNameMode'
@@ -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,
@@ -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<string | null>(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.
@@ -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' })
})
})
+36 -4
View File
@@ -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<T extends SetupDecision | un
isCancelled: () => 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<T extends SetupDecision | un
return 'cancelled'
}
const { decision: trustDecision, approvedContentHash } = trust.value
const state = typeof stateOrGetter === 'function' ? stateOrGetter() : stateOrGetter
if (trustDecision !== 'run' || approvedContentHash === undefined) {
return { setupDecision: trustDecision === 'skip' ? 'skip' : decision, trustDecision }
return {
setupDecision:
trustDecision === 'skip'
? 'skip'
: explicitFolderRunUnderRepoTrust(state, repoId, ownerHostId, decision),
trustDecision
}
}
// The host runs shared setup only if the created branch's content hashes to one of these.
const state = typeof stateOrGetter === 'function' ? stateOrGetter() : stateOrGetter
const approvedSetupHashes = approvedOrcaHookContentHashes(
state.trustedOrcaHooks,
repoId,
@@ -49,3 +57,27 @@ export async function confirmWorkspaceSetupDecision<T extends SetupDecision | un
...(approvedSetupHashes.length > 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<T extends SetupDecision | undefined>(
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
}