diff --git a/src/cli/handlers/folder-setup-support-warning.ts b/src/cli/handlers/folder-setup-support-warning.ts new file mode 100644 index 00000000000..f0b8ce50bfe --- /dev/null +++ b/src/cli/handlers/folder-setup-support-warning.ts @@ -0,0 +1,22 @@ +import type { RuntimeClient } from '../runtime-client' +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' + +/** An older host makes folder workspaces without running setup; say so rather than imply it ran. */ +export async function warnIfFolderSetupUnsupported( + client: RuntimeClient, + worktreeId: string | undefined, + setupRequested: boolean, + json: boolean +): Promise { + if (json || !setupRequested || !worktreeId?.includes(FOLDER_WORKSPACE_INSTANCE_SEPARATOR)) { + return + } + 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.' + ) + } +} diff --git a/src/cli/handlers/worktree.ts b/src/cli/handlers/worktree.ts index d1ff9d7bf72..36366c3381b 100644 --- a/src/cli/handlers/worktree.ts +++ b/src/cli/handlers/worktree.ts @@ -1,3 +1,4 @@ +import { warnIfFolderSetupUnsupported } from './folder-setup-support-warning' import { withWorktreeSelectorRecovery } from '../worktree-selector-recovery' import type { RuntimeWorktreeListResult, @@ -208,6 +209,12 @@ export const WORKTREE_HANDLERS: Record = { 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) }, 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 fae4e6ce384..3feb478acfa 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,6 @@ import { ipcMain } from 'electron' import { getRepoDialableSshTargetId, type ExecutionHostId } from '../../../shared/execution-host' -import { isFolderRepo } from '../../../shared/repo-kind' +import { scopeHooksToRepoKind } from '../../../shared/folder-workspace-hooks' 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,10 +23,6 @@ export function registerWorktreeHookCheckHandler(context: WorktreeIpcContext): v mayNeedUpdate: false } } - if (isFolderRepo(repo)) { - return { status: 'ok', hasHooks: false, hooks: null, mayNeedUpdate: false } - } - if (getRepoDialableSshTargetId(repo)) { return { status: 'error', @@ -53,7 +49,7 @@ export function registerWorktreeHookCheckHandler(context: WorktreeIpcContext): v } const has = hasHooksFile(repo.path) - const hooks = has ? loadHooks(repo.path) : null + const hooks = scopeHooksToRepoKind(repo, has ? loadHooks(repo.path) : null) // Well-formed unknown keys may come from a newer Orca; suggest updating instead of parse repair. const mayNeedUpdate = has && !hooks && hasUnrecognizedOrcaYamlKeys(repo.path) return { diff --git a/src/main/ipc/worktrees/create/folder-workspace-creation.ts b/src/main/ipc/worktrees/create/folder-workspace-creation.ts index b35dad3b48c..a2d9d9e649b 100644 --- a/src/main/ipc/worktrees/create/folder-workspace-creation.ts +++ b/src/main/ipc/worktrees/create/folder-workspace-creation.ts @@ -7,12 +7,17 @@ import type { CreateWorktreeArgsWithSystemProvenance } from '../ipc-context-sche import { getFolderWorkspaceInstanceId, mergeFolderWorkspace } from '../folder-workspace-model' import { resolveWorktreeCreateDisplayNameRequest } from '../../worktree-display-name' import { hostWorktreeTargetForRepo } from '../../../persistence/host-qualified-worktree-meta' +import { + isPreparedFolderSetup, + prepareFolderWorktreeSetup +} from '../../../runtime/workspaces/creation/runtime-folder-worktree-setup' +import { getLocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' -export function createFolderWorkspace( +export async function createFolderWorkspace( args: CreateWorktreeArgsWithSystemProvenance, repo: Repo, store: Store -): CreateWorktreeResult { +): Promise { const now = Date.now() const instanceId = randomUUID() const worktreeId = getFolderWorkspaceInstanceId(repo, instanceId) @@ -64,5 +69,21 @@ export function createFolderWorkspace( ? { linkedTaskSourceContext: args.linkedTaskSourceContext } : {}) }) - return { worktree: mergeFolderWorkspace(repo, worktreeId, meta) } + 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, + repo, + worktree, + settings: store.getSettings(), + runtimeTarget: () => getLocalProjectWorktreeGitOptions(store, repo), + shouldUseSetupRunner: true + }) + const setup = isPreparedFolderSetup(prepared) ? prepared : undefined + return { + worktree, + ...(setup?.setup ? { setup: setup.setup } : {}), + ...(setup?.setupTrustMismatch ? { setupTrustMismatch: setup.setupTrustMismatch } : {}), + ...(prepared?.warning ? { warning: prepared.warning } : {}) + } } diff --git a/src/main/ipc/worktrees/create/register-worktree-create-handlers.ts b/src/main/ipc/worktrees/create/register-worktree-create-handlers.ts index b8caf67061b..60a43933f42 100644 --- a/src/main/ipc/worktrees/create/register-worktree-create-handlers.ts +++ b/src/main/ipc/worktrees/create/register-worktree-create-handlers.ts @@ -67,8 +67,8 @@ export function registerWorktreeCreateHandlers(context: WorktreeIpcContext): voi try { // Track operational failures; malformed IPC rejected above is outside the creation funnel. if (isFolderRepo(repo)) { - // Folder creation only registers metadata, so it needs no filesystem host route. - result = createFolderWorkspace(createArgs, repo, store) + // Folder creation registers metadata; its setup prep checks ownership itself. + result = await createFolderWorkspace(createArgs, repo, store) } else { // Resolve executionHostId-only SSH ownership before any local Git operation. const createRoute = requireWorktreeCreateRoute(repo) diff --git a/src/main/ipc/worktrees/removal/remove-folder-workspace.ts b/src/main/ipc/worktrees/removal/remove-folder-workspace.ts index 18e01cf0e7a..67783f1742e 100644 --- a/src/main/ipc/worktrees/removal/remove-folder-workspace.ts +++ b/src/main/ipc/worktrees/removal/remove-folder-workspace.ts @@ -13,6 +13,12 @@ import { getFolderWorkspaceRootId } from '../folder-workspace-model' import { preservedBranchCleanupByScope } from './preserved-branch-cleanup' import { removeWorktreeMetadataAndTransientState } from './worktree-removal-ownership' import { teardownStops } from '../../../runtime/workspaces/removal/owned-session-teardown-policy' +import { + gateFolderWorkspaceRemovalOnArchiveHook, + removeFolderWorkspaceRunnerFiles +} from '../../../workspaces/removal/folder-workspace-archive-hook' +import { readWorktreeMetaForRepo } from '../../../persistence/host-qualified-worktree-meta' +import { getLocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' export async function removeFolderWorkspace( context: WorktreeIpcContext, @@ -25,6 +31,19 @@ export async function removeFolderWorkspace( if (args.worktreeId === getFolderWorkspaceRootId(repo)) { throw new Error('Cannot delete the project root workspace. Remove the folder project instead.') } + // Archive failure must refuse before watcher, PTY or metadata teardown (#19334). + const archiveHookOverride = await gateFolderWorkspaceRemovalOnArchiveHook({ + repo, + worktreeId: args.worktreeId, + displayName: + ( + readWorktreeMetaForRepo(store, args.worktreeId, repo) ?? + store.getWorktreeMeta(args.worktreeId) + )?.displayName ?? repo.displayName, + runArchive: !args.skipArchive, + allowFailure: args.allowFailedArchiveHook === true, + runtimeTarget: () => getLocalProjectWorktreeGitOptions(store, repo) + }) const ownerHost = parseExecutionHostId(removalHostId) const gate = await runtime.acquireFileWatcherRemoval( repo.path, @@ -62,8 +81,9 @@ export async function removeFolderWorkspace( preservedBranchCleanupByScope.delete( preservedBranchCleanupScopeKey({ worktreeId: args.worktreeId, hostId: removalHostId }) ) + removeFolderWorkspaceRunnerFiles(repo, args.worktreeId) notifyWorktreesChanged(mainWindow, repoId) - return {} + return archiveHookOverride ? { archiveHookOverride } : {} } finally { await gate.finish(false) } diff --git a/src/main/runtime/repositories/runtime-repository-hooks-commands.ts b/src/main/runtime/repositories/runtime-repository-hooks-commands.ts index fd36b658d24..148a30b81fd 100644 --- a/src/main/runtime/repositories/runtime-repository-hooks-commands.ts +++ b/src/main/runtime/repositories/runtime-repository-hooks-commands.ts @@ -1,4 +1,5 @@ import { getRepoDialableSshTargetId } 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' import type { Repo } from '../../../shared/repo-types' @@ -40,8 +41,8 @@ export class RuntimeRepositoryHooksCommands { } const hasFile = hasHooksFile(repo.path) const hooks = getEffectiveHooks(repo) - const sharedHooks = hasFile ? loadHooks(repo.path) : null - const setupConfig = isFolderRepo(repo) ? null : getSetupConfig(repo, sharedHooks) + const sharedHooks = scopeHooksToRepoKind(repo, hasFile ? loadHooks(repo.path) : null) + const setupConfig = getSetupConfig(repo, sharedHooks) return { hasHooksFile: hasFile, hooks, @@ -61,9 +62,6 @@ export class RuntimeRepositoryHooksCommands { async checkRepoHooks(repoSelector: string, options: { background?: boolean } = {}) { const repo = await this.deps.resolveRepo(repoSelector) - if (isFolderRepo(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 } @@ -83,7 +81,7 @@ export class RuntimeRepositoryHooksCommands { } } const has = hasHooksFile(repo.path) - const hooks = has ? loadHooks(repo.path) : null + const hooks = scopeHooksToRepoKind(repo, has ? loadHooks(repo.path) : null) return { status: 'ok' as const, hasHooks: has, @@ -123,10 +121,6 @@ function archiveTrust( repo: Repo, sharedHooks: OrcaHooks | null ): { contentHash: string; scriptContent: string } | null { - // Folder removal never runs hooks. - if (isFolderRepo(repo)) { - return null - } const localArchive = repo.hookSettings?.scripts.archive?.trim() const policy = resolveHookCommandSourcePolicy(repo.hookSettings?.commandSourcePolicy, { hasLocalScript: Boolean(localArchive) diff --git a/src/main/runtime/workspaces/creation/created-worktree-approved-setup.test.ts b/src/main/runtime/workspaces/creation/created-worktree-approved-setup.test.ts index f9d48b5b9a5..00a59d16492 100644 --- a/src/main/runtime/workspaces/creation/created-worktree-approved-setup.test.ts +++ b/src/main/runtime/workspaces/creation/created-worktree-approved-setup.test.ts @@ -22,7 +22,12 @@ let repo: Repo const provisionManagedWorktreeTerminals = vi.fn() function runtimeFor() { - const worktree = { id: `repo::${worktreePath}`, repoId: 'repo', path: worktreePath } + const worktree = { + id: `repo::${worktreePath}`, + repoId: 'repo', + path: worktreePath, + displayName: 'w' + } return { showManagedWorktree: vi.fn(async () => worktree), requireStore: () => ({ diff --git a/src/main/runtime/workspaces/creation/created-worktree-approved-setup.ts b/src/main/runtime/workspaces/creation/created-worktree-approved-setup.ts index e8edb207a0c..7147cc3b6c3 100644 --- a/src/main/runtime/workspaces/creation/created-worktree-approved-setup.ts +++ b/src/main/runtime/workspaces/creation/created-worktree-approved-setup.ts @@ -1,4 +1,6 @@ import { isFolderRepo } from '../../../../shared/repo-kind' +import { isRepoOnCatalogHost } from '../../../../shared/execution-host' +import { scopeHooksToRepoKind } from '../../../../shared/folder-workspace-hooks' import { getSetupRunnerCommandPlatformForPath } from '../../../../shared/agent-launch/startup/setup-runner-command' import type { RunApprovedWorktreeSetupResult } from '../../../../shared/worktree/create-types' import { @@ -20,7 +22,9 @@ import type { RuntimeStore } from '../../construction/runtime-store-contract' import type { WorktreeTerminalProvisioningArgs } from '../startup/runtime-worktree-terminal-provisioning' type ApprovedSetupRuntime = { - showManagedWorktree: (selector: string) => Promise> + showManagedWorktree: ( + selector: string + ) => Promise> requireStore: () => Pick provisionManagedWorktreeTerminals: (args: WorktreeTerminalProvisioningArgs) => Promise } @@ -38,10 +42,10 @@ export async function runApprovedCreatedWorktreeSetup( const worktree = await runtime.showManagedWorktree(worktreeSelector) const store = runtime.requireStore() const repo = store.getRepo(worktree.repoId) - if (!repo || isFolderRepo(repo)) { + if (!repo || (isFolderRepo(repo) && !isRepoOnCatalogHost(repo))) { return { status: 'not_configured' } } - const yamlHooks = loadHooks(worktree.path) + const yamlHooks = scopeHooksToRepoKind(repo, loadHooks(worktree.path)) const mismatch = checkCreatedWorktreeSetupTrust(repo, yamlHooks, 'run', { approvedSetupHash }) if (mismatch) { return { status: 'mismatch', setupTrustMismatch: mismatch } @@ -54,7 +58,8 @@ export async function runApprovedCreatedWorktreeSetup( setupScript, getLocalProjectWorktreeGitOptions(store, repo), resolveSetupRunnerShell(store.getSettings()), - yamlHooks?.setupAgentStartupPolicy + yamlHooks?.setupAgentStartupPolicy, + { worktreeId: worktree.id, displayName: worktree.displayName } ) : undefined // The create already opened the command-less default tabs. 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 7cf2c36ab43..ad0c8c0ebe5 100644 --- a/src/main/runtime/workspaces/creation/runtime-folder-worktree-create.ts +++ b/src/main/runtime/workspaces/creation/runtime-folder-worktree-create.ts @@ -7,7 +7,6 @@ import { shouldSeedWorktreePrimaryTerminal } from '../../../../shared/worktree-f import { randomUUID } from 'node:crypto' import { getProjectHostSetupWorktreeMeta } from '../../../../shared/project-host-setup-lookup' import { resolveWorktreeCreateDisplayNameRequest } from '../../../ipc/worktree-display-name' -import type { RuntimeTerminalCreate } from '../../../../shared/runtime-terminal-create-contract' import type { CreateWorktreeResult } from '../../../../shared/worktree/create-types' import type { Repo } from '../../../../shared/repo-types' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' @@ -19,27 +18,24 @@ import { } from '../catalog/runtime-folder-workspace' import type { RuntimeManagedWorktreeCreateArgs } from './runtime-managed-worktree-create-types' import type { RuntimeStore } from '../../construction/runtime-store-contract' -import type { TerminalCreateOptions } from '../../terminal/launch/terminal-create-options' import type { WorktreeStartupDraftPaste, WorktreeStartupFollowup } from '../startup/runtime-worktree-agent-startup' import { hostWorktreeTargetForRepo } from '../../../persistence/host-qualified-worktree-meta' +import type { RuntimeLocalWorktreeTerminalPorts } from '../startup/runtime-local-worktree-terminal-startup' +import { + isPreparedFolderSetup, + prepareFolderWorktreeSetup, + startRuntimeFolderWorktreeSetupTerminals, + type RuntimeFolderWorktreeSetupDeps +} from './runtime-folder-worktree-setup' +import { buildRuntimeSetupReceipt } from './runtime-local-worktree-setup' type RuntimeFolderWorktreeCreateDeps = { store: RuntimeStore - ptySpawnAvailable: boolean - provisionInBackground?: () => boolean - createTerminal: ( - selector: string, - options: TerminalCreateOptions - ) => Promise - pasteDraft: (handle: string, draft: WorktreeStartupDraftPaste) => void - sendFollowup: ( - handle: string, - followup: WorktreeStartupFollowup, - terminal: RuntimeTerminalCreate - ) => void + /** The same terminal operations a worktree create uses; folder startup and setup share them. */ + terminals: RuntimeLocalWorktreeTerminalPorts invalidateResolvedWorktrees: () => void notifyWorktreesChanged: (repoId: string) => void emitCreated: (event: { @@ -55,6 +51,8 @@ type RuntimeFolderWorktreeCreateDeps = { startup?: WorktreeStartupLaunch, providesInitialSurface?: boolean ) => void + /** Absent where this host can't run the folder's setup script. */ + setup?: RuntimeFolderWorktreeSetupDeps } export async function createRuntimeFolderWorktree(args: { @@ -150,18 +148,47 @@ export async function createRuntimeFolderWorktree(args: { path: worktree.path, branch: worktree.branch }) + const setupResult = deps.setup + ? await prepareFolderWorktreeSetup({ + request, + repo, + worktree, + settings, + runtimeTarget: deps.setup.runtimeTarget, + shouldUseSetupRunner: deps.setup.shouldUseSetupRunner + }) + : undefined + const preparedSetup = isPreparedFolderSetup(setupResult) ? setupResult : undefined + if (preparedSetup?.setup && deps.setup) { + return { + worktree: folderCreateResultWorktree(worktree), + ...(await startRuntimeFolderWorktreeSetupTerminals({ + request, + repo, + worktree, + prepared: preparedSetup, + startup: args.startup, + startupFollowup: args.startupFollowup, + startupLaunchRuntime: args.startupLaunchRuntime, + createdWithAgent: args.createdWithAgent, + promisedAgentChat: args.promisedAgentChat, + draftPaste: args.draftPaste, + terminals: deps.terminals + })) + } + } const shouldActivate = request.activate === true || request.runHooks === true - let warning: string | undefined + let warning: string | undefined = setupResult?.warning let didSpawnStartup = false let startupTerminal: CreateWorktreeResult['startupTerminal'] // Main owns failed agent startup too, so its pane can show the reason without a terminal service. - if (args.startup && (deps.ptySpawnAvailable || ORCA_LAYOUT_OWNER_IS_MAIN)) { + if (args.startup && (deps.terminals.canSpawn || ORCA_LAYOUT_OWNER_IS_MAIN)) { try { const launchRuntime = args.startupLaunchRuntime if (launchRuntime instanceof Error && !ORCA_LAYOUT_OWNER_IS_MAIN) { throw launchRuntime } - const terminal = await deps.createTerminal(`id:${worktree.id}`, { + const terminal = await deps.terminals.createTerminal(`id:${worktree.id}`, { command: args.startup.command, ...(request.startupCwd ? { cwd: request.startupCwd } : {}), ...paneIdentity(request.startupPaneKey), @@ -182,10 +209,10 @@ export async function createRuntimeFolderWorktree(args: { }) request.onStartupTerminalCreated?.(terminal) if (args.draftPaste) { - deps.pasteDraft(terminal.handle, args.draftPaste) + deps.terminals.pasteDraft(terminal.handle, args.draftPaste) } if (args.startupFollowup) { - deps.sendFollowup(terminal.handle, args.startupFollowup, terminal) + deps.terminals.sendFollowup(terminal.handle, args.startupFollowup, terminal) } didSpawnStartup = true startupTerminal = { @@ -220,8 +247,8 @@ export async function createRuntimeFolderWorktree(args: { ) } if ( - (!shouldActivate || deps.provisionInBackground?.() === true) && - deps.ptySpawnAvailable && + (!shouldActivate || deps.terminals.provisionInBackground?.() === true) && + deps.terminals.canSpawn && shouldSeedWorktreePrimaryTerminal({ // Failed agents retain their panes; do not seed a shell beside them. hasPrimarySurface: didSpawnStartup || (ORCA_LAYOUT_OWNER_IS_MAIN && Boolean(args.startup)), @@ -230,7 +257,7 @@ export async function createRuntimeFolderWorktree(args: { }) ) { try { - await deps.createTerminal(`id:${worktree.id}`, { surfaceOwner: false }) + await deps.terminals.createTerminal(`id:${worktree.id}`, { surfaceOwner: false }) } catch (error) { const message = readableWslDistroHoldText( formatTerminalStartFailure(error) ?? @@ -244,20 +271,29 @@ export async function createRuntimeFolderWorktree(args: { } } return { - worktree: { - ...worktree, - parentWorktreeId: null, - childWorktreeIds: [], - lineage: null, - git: { - path: worktree.path, - head: worktree.head, - branch: worktree.branch, - isBare: worktree.isBare, - isMainWorktree: worktree.isMainWorktree - } - }, + worktree: folderCreateResultWorktree(worktree), ...(startupTerminal ? { startupTerminal } : {}), + ...(preparedSetup && request.awaitTerminalProvisioning + ? { setupReceipt: buildRuntimeSetupReceipt(preparedSetup, false, null) } + : {}), ...(warning ? { warning } : {}) } } + +function folderCreateResultWorktree( + worktree: ReturnType +): CreateWorktreeResult['worktree'] { + return { + ...worktree, + parentWorktreeId: null, + childWorktreeIds: [], + lineage: null, + git: { + path: worktree.path, + head: worktree.head, + branch: worktree.branch, + isBare: worktree.isBare, + isMainWorktree: worktree.isMainWorktree + } + } +} diff --git a/src/main/runtime/workspaces/creation/runtime-folder-worktree-setup.ts b/src/main/runtime/workspaces/creation/runtime-folder-worktree-setup.ts new file mode 100644 index 00000000000..633666f28ea --- /dev/null +++ b/src/main/runtime/workspaces/creation/runtime-folder-worktree-setup.ts @@ -0,0 +1,123 @@ +import { isRepoOnCatalogHost } from '../../../../shared/execution-host' +import type { Repo } from '../../../../shared/repo-types' +import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' +import type { AgentLaunchRuntime } from '../../../../shared/agent-launch/startup/agent-launch-runtime' +import type { CreateWorktreeResult } from '../../../../shared/worktree/create-types' +import type { Worktree } from '../../../../shared/worktree/types' +import type { WorktreeStartupLaunch } from '../../../../shared/worktree/launch-types' +import type { RuntimeStore } from '../../construction/runtime-store-contract' +import { + startRuntimeLocalWorktreeTerminals, + type RuntimeLocalWorktreeTerminalPorts +} from '../startup/runtime-local-worktree-terminal-startup' +import type { + WorktreeStartupDraftPaste, + WorktreeStartupFollowup +} from '../startup/runtime-worktree-agent-startup' +import type { RuntimeManagedWorktreeCreateArgs } from './runtime-managed-worktree-create-types' +import { + buildRuntimeSetupReceipt, + prepareRuntimeLocalWorktreeSetup +} from './runtime-local-worktree-setup' + +export type RuntimeFolderWorktreeSetupDeps = { + runtimeTarget: () => { wslDistro?: string } | undefined + shouldUseSetupRunner: boolean +} + +type PreparedFolderSetup = Awaited> + +/** + * Only the host whose catalog holds the folder may read its orca.yaml or write runners there. + * The workspace already exists, so a setup problem becomes a warning, never a failed create. + */ +export async function prepareFolderWorktreeSetup(args: { + request: Parameters[0]['request'] + repo: Repo + worktree: Pick + settings: ReturnType + runtimeTarget: () => { wslDistro?: string } | undefined + shouldUseSetupRunner: boolean +}): Promise { + const { repo, worktree } = args + if (!isRepoOnCatalogHost(repo)) { + return undefined + } + try { + return await prepareRuntimeLocalWorktreeSetup({ + request: args.request, + repo, + worktreePath: worktree.path, + settings: args.settings, + runtimeTarget: args.runtimeTarget(), + shouldUseSetupRunner: args.shouldUseSetupRunner, + identity: { worktreeId: worktree.id, displayName: worktree.displayName } + }) + } catch (error) { + console.error(`[hooks] setup preparation failed for ${worktree.path}:`, error) + const message = error instanceof Error ? error.message : String(error) + return { warning: `Setup did not run for this folder workspace: ${message}` } + } +} + +export function isPreparedFolderSetup( + value: PreparedFolderSetup | { warning: string } | undefined +): value is PreparedFolderSetup { + return value !== undefined && 'effectiveDecision' in value +} + +/** Folder workspaces start setup and agents exactly as worktrees do, Setup-before-agent order included. */ +export async function startRuntimeFolderWorktreeSetupTerminals(args: { + request: RuntimeManagedWorktreeCreateArgs + repo: Repo + worktree: Worktree + prepared: PreparedFolderSetup + startup?: WorktreeStartupLaunch + startupFollowup?: WorktreeStartupFollowup + startupLaunchRuntime?: AgentLaunchRuntime | Error + createdWithAgent?: TuiAgent + promisedAgentChat?: boolean + draftPaste?: WorktreeStartupDraftPaste + terminals: RuntimeLocalWorktreeTerminalPorts +}): Promise> { + const { request, prepared } = args + const started = await startRuntimeLocalWorktreeTerminals({ + request, + repo: args.repo, + worktree: args.worktree, + setup: prepared.setup, + startup: args.startup, + startupFollowup: args.startupFollowup, + startupLaunchRuntime: args.startupLaunchRuntime, + createdWithAgent: args.createdWithAgent, + promisedAgentChat: args.promisedAgentChat, + draftPaste: args.draftPaste, + warning: prepared.warning, + ports: args.terminals + }) + return { + ...(started.returnedSetup ? { setup: started.returnedSetup } : {}), + ...(request.awaitTerminalProvisioning + ? { + setupReceipt: buildRuntimeSetupReceipt( + prepared, + started.didSpawnSetup, + started.setupTerminalHandle + ) + } + : {}), + ...(started.didSpawnStartup && started.startupTerminalHandle + ? { + startupTerminal: { + spawned: true, + handle: started.startupTerminalHandle, + ...(started.startupTerminalTabId ? { tabId: started.startupTerminalTabId } : {}), + ...(started.startupTerminalPaneKey ? { paneKey: started.startupTerminalPaneKey } : {}), + ...(started.startupTerminalPtyId ? { ptyId: started.startupTerminalPtyId } : {}), + surface: 'background' as const + } + } + : {}), + ...(started.warning ? { warning: started.warning } : {}) + } +} diff --git a/src/main/runtime/workspaces/creation/runtime-local-worktree-setup-trust.test.ts b/src/main/runtime/workspaces/creation/runtime-local-worktree-setup-trust.test.ts index fbc1ac7d2e7..97ce8e12fcb 100644 --- a/src/main/runtime/workspaces/creation/runtime-local-worktree-setup-trust.test.ts +++ b/src/main/runtime/workspaces/creation/runtime-local-worktree-setup-trust.test.ts @@ -21,8 +21,6 @@ const repo: Repo = { id: 'repo', path: '/primary', displayName: 'r', badgeColor: function prepare(approvedSetupHash?: string, approvedSetupHashes?: string[]) { return prepareRuntimeLocalWorktreeSetup({ request: { - repoSelector: 'id:repo', - name: 'w', setupDecision: 'run', ...(approvedSetupHash !== undefined ? { approvedSetupHash } : {}), ...(approvedSetupHashes ? { approvedSetupHashes } : {}) @@ -82,4 +80,42 @@ describe('created worktree setup trust', () => { expect(runner.createSetupRunnerScript).toHaveBeenCalledOnce() expect(result.setupTrustMismatch).toBeUndefined() }) + + describe('folder projects', () => { + const folderRepo: Repo = { ...repo, kind: 'folder' } + const identity = { worktreeId: 'repo::/acme::workspace:1', displayName: 'Fix login' } + const prepareFolder = (setupDecision: 'run' | 'inherit', approvedSetupHash?: string) => + prepareRuntimeLocalWorktreeSetup({ + request: { + setupDecision, + ...(approvedSetupHash !== undefined ? { approvedSetupHash } : {}) + }, + repo: folderRepo, + worktreePath, + settings: getDefaultSettings(tmpdir()), + runtimeTarget: undefined, + shouldUseSetupRunner: true, + identity + }) + + it('skips shared setup from an older client that sent no approval', async () => { + writeFileSync(join(worktreePath, 'orca.yaml'), 'scripts:\n setup: make bootstrap\n') + const result = await prepareFolder('inherit') + expect(runner.createSetupRunnerScript).not.toHaveBeenCalled() + expect(result.setup).toBeUndefined() + expect(result.warning).toContain('pass --setup run') + }) + + it('runs approved shared setup for the workspace, without default tabs', async () => { + writeFileSync( + join(worktreePath, 'orca.yaml'), + 'scripts:\n setup: make bootstrap\ndefaultTabs:\n - title: dev\n command: pnpm dev\n' + ) + const result = await prepareFolder('run', sha256('make bootstrap')) + expect(runner.createSetupRunnerScript).toHaveBeenCalledOnce() + expect(runner.createSetupRunnerScript.mock.calls[0][6]).toEqual(identity) + expect(result.defaultTabs).toBeUndefined() + expect(result.setupTrustMismatch).toBeUndefined() + }) + }) }) diff --git a/src/main/runtime/workspaces/creation/runtime-local-worktree-setup.ts b/src/main/runtime/workspaces/creation/runtime-local-worktree-setup.ts index 794d1b1de73..2a3cf1dda61 100644 --- a/src/main/runtime/workspaces/creation/runtime-local-worktree-setup.ts +++ b/src/main/runtime/workspaces/creation/runtime-local-worktree-setup.ts @@ -15,8 +15,12 @@ import { } from '../../../workspace-hooks/effective-hook-config' import { checkCreatedWorktreeSetupTrust, - defaultTabsWithoutCommands + defaultTabsWithoutCommands, + folderSharedSetupLacksApproval } from '../../../workspace-hooks/created-worktree-setup-trust' +import type { HookWorkspaceIdentity } from '../../../workspace-hooks/setup-hook-env-vars' +import { scopeHooksToRepoKind } from '../../../../shared/folder-workspace-hooks' +import { isFolderRepo } from '../../../../shared/repo-kind' import type { RuntimeManagedWorktreeCreateArgs } from './runtime-managed-worktree-create-types' import type { RuntimeStore } from '../../construction/runtime-store-contract' @@ -28,13 +32,18 @@ export function resolveRuntimeSetupDecision( } export async function prepareRuntimeLocalWorktreeSetup(args: { - request: RuntimeManagedWorktreeCreateArgs + request: Pick< + RuntimeManagedWorktreeCreateArgs, + 'runHooks' | 'setupDecision' | 'approvedSetupHash' | 'approvedSetupHashes' + > repo: Repo worktreePath: string settings: ReturnType runtimeTarget: { wslDistro?: string } | undefined shouldUseSetupRunner: boolean warning?: string + /** Required for folder workspaces, whose shared directory can't name the workspace. */ + identity?: HookWorkspaceIdentity }): Promise<{ setup?: CreateWorktreeResult['setup'] defaultTabs?: CreateWorktreeResult['defaultTabs'] @@ -48,7 +57,7 @@ export async function prepareRuntimeLocalWorktreeSetup(args: { const { request, repo, worktreePath, settings } = args let warning = args.warning let setup: CreateWorktreeResult['setup'] - const yamlHooks = loadHooks(worktreePath) + const yamlHooks = scopeHooksToRepoKind(repo, loadHooks(worktreePath)) const hooks = getEffectiveHooks(repo, worktreePath) const effectiveDecision = resolveRuntimeSetupDecision(request) const setupTrustMismatch = checkCreatedWorktreeSetupTrust( @@ -57,12 +66,20 @@ export async function prepareRuntimeLocalWorktreeSetup(args: { effectiveDecision, request ) + const lacksFolderApproval = + isFolderRepo(repo) && + folderSharedSetupLacksApproval(repo, yamlHooks, effectiveDecision, request) // Only the approved content may run; the client re-prompts with the branch's. - const runDecision = setupTrustMismatch ? 'skip' : effectiveDecision + const runDecision = setupTrustMismatch || lacksFolderApproval ? 'skip' : effectiveDecision if (setupTrustMismatch) { // Automations have no prompt to re-ask; the host log is their record of the skip. console.warn(`[hooks] setup skipped for ${worktreePath}: it differs from the approved content`) } + if (lacksFolderApproval) { + const skipped = + 'orca.yaml setup skipped for this folder workspace because it was not approved; pass --setup run to run it.' + warning = warning ? `${warning} Also ${skipped}` : skipped + } let defaultTabs: CreateWorktreeResult['defaultTabs'] try { const launch = getDefaultTabsLaunch(yamlHooks, repo, runDecision) @@ -92,14 +109,21 @@ export async function prepareRuntimeLocalWorktreeSetup(args: { hooks.scripts.setup, args.runtimeTarget, resolveSetupRunnerShell(settings), - yamlHooks?.setupAgentStartupPolicy + yamlHooks?.setupAgentStartupPolicy, + args.identity ) } catch (error) { console.error(`[hooks] Failed to prepare setup runner for ${worktreePath}:`, error) + if (isFolderRepo(repo)) { + const failed = `Setup did not run: Orca could not write its setup file in ${worktreePath}.` + warning = warning ? `${warning} Also ${failed}` : failed + } } } else { didStartInProcessSetupHook = true - void runHook('setup', worktreePath, repo, worktreePath, args.runtimeTarget).then((result) => { + void runHook('setup', worktreePath, repo, worktreePath, args.runtimeTarget, { + identity: args.identity + }).then((result) => { if (!result.success) { console.error(`[hooks] setup hook failed for ${worktreePath}:`, result.output) } diff --git a/src/main/runtime/workspaces/creation/workspace-creation.ts b/src/main/runtime/workspaces/creation/workspace-creation.ts index 6dea38dd8f6..c921f5bc2f5 100644 --- a/src/main/runtime/workspaces/creation/workspace-creation.ts +++ b/src/main/runtime/workspaces/creation/workspace-creation.ts @@ -15,6 +15,8 @@ import { resolveWorktreeCreateRoute } from '../../../workspaces/creation/worktre import { ExecutionHostNotDispatchableError } from '../../../providers/execution-host-provider-dispatch' import { SshHostNotServedError } from '../../../providers/ssh-host-not-served-error' import { createRuntimeFolderWorktree } from './runtime-folder-worktree-create' +import type { RuntimeNavigationTarget } from '../../../../shared/runtime-navigation' +import type { Worktree } from '../../../../shared/worktree/types' import { createRuntimeLocalManagedWorktree } from './runtime-local-worktree-create' import type { PreparationRearmHolder } from '../../../workspaces/creation/preparation/worktree-create-preparation' import { @@ -22,7 +24,10 @@ import { prepareRuntimeLocalWorktreeSetup } from './runtime-local-worktree-setup' import { invalidateAuthorizedRootsCacheForRepo } from '../../../ipc/worktrees/removal/registered-worktree-roots-scoped-invalidation' -import { startRuntimeLocalWorktreeTerminals } from '../startup/runtime-local-worktree-terminal-startup' +import { + startRuntimeLocalWorktreeTerminals, + type RuntimeLocalWorktreeTerminalPorts +} from '../startup/runtime-local-worktree-terminal-startup' import { trackRuntimeWorkspaceCreate } from '../../../workspaces/creation/workspace-create-telemetry' import type { RuntimeWorkspaceCreateEvents } from '../../../workspaces/creation/workspace-create-telemetry' import { @@ -128,17 +133,15 @@ export abstract class OrcaRuntimeWithCreateManagedWorktree extends OrcaRuntimeWi draftPaste: effectiveDraftPaste, deps: { store, - ptySpawnAvailable: Boolean(this.ptyController?.spawn), - provisionInBackground: () => this.shouldProvisionWorktreeInBackground(args.navigation), - createTerminal: (selector, options) => - this.createTerminal(selector, { ...options, ...wslUserAct(args) }), - pasteDraft: (handle, draft) => this.pasteStartupDraftWhenReady(handle, draft), - sendFollowup: (handle, followup, terminal) => - void this.deliverStartupFollowup(handle, followup, { terminalCreation: terminal }), + terminals: this.localWorktreeTerminalPorts(args, activationCallbacks.local), invalidateResolvedWorktrees: () => this.invalidateResolvedWorktreeCache(), notifyWorktreesChanged: (repoId) => this.notifyWorktreesChanged(repoId), emitCreated: (event) => this.emitWorktreeLifecycle(event), - activate: activationCallbacks.folder + activate: activationCallbacks.folder, + setup: { + runtimeTarget: () => this.getLocalGitExecutionOptionArgs(repo)[0], + shouldUseSetupRunner: this.canUseSetupRunner(effectiveStartup) + } } }) } @@ -195,10 +198,7 @@ export abstract class OrcaRuntimeWithCreateManagedWorktree extends OrcaRuntimeWi worktreePath, settings: createSettings, runtimeTarget: this.getLocalGitExecutionOptionArgs(repo)[0], - shouldUseSetupRunner: - this.authoritativeWindowId !== null || - Boolean(effectiveStartup) || - Boolean(this.ptyController?.spawn), + shouldUseSetupRunner: this.canUseSetupRunner(effectiveStartup), warning: [includeCopyWarning, addResult.upstreamWarning].filter(Boolean).join(' ') || undefined }) @@ -234,18 +234,7 @@ export abstract class OrcaRuntimeWithCreateManagedWorktree extends OrcaRuntimeWi promisedAgentChat: args.promisedAgentChat, draftPaste: effectiveDraftPaste, warning, - ports: { - canSpawn: Boolean(this.ptyController?.spawn), - provisionInBackground: () => this.shouldProvisionWorktreeInBackground(args.navigation), - createTerminal: (selector, options) => - this.createTerminal(selector, { ...options, ...wslUserAct(args) }, worktree), - pasteDraft: (handle, draft) => this.pasteStartupDraftWhenReady(handle, draft), - sendFollowup: (handle, followup, terminal) => - void this.deliverStartupFollowup(handle, followup, { terminalCreation: terminal }), - provision: (options) => - this.provisionManagedWorktreeTerminals({ ...options, ...wslUserAct(args) }, worktree), - activate: activationCallbacks.local - } + ports: this.localWorktreeTerminalPorts(args, activationCallbacks.local, worktree) }) warning = terminalWarning this.emitWorktreeLifecycle({ @@ -298,4 +287,32 @@ export abstract class OrcaRuntimeWithCreateManagedWorktree extends OrcaRuntimeWi : {}) } } + + // A window, an agent or a PTY host can show setup in a terminal; otherwise it runs in-process. + private canUseSetupRunner(startup: unknown): boolean { + return ( + this.authoritativeWindowId !== null || Boolean(startup) || Boolean(this.ptyController?.spawn) + ) + } + + private localWorktreeTerminalPorts( + args: { navigation?: RuntimeNavigationTarget; wslUserAct?: true }, + activate: RuntimeLocalWorktreeTerminalPorts['activate'], + worktree?: Worktree + ): RuntimeLocalWorktreeTerminalPorts { + return { + canSpawn: Boolean(this.ptyController?.spawn), + provisionInBackground: () => this.shouldProvisionWorktreeInBackground(args.navigation), + createTerminal: (selector, options) => + worktree + ? this.createTerminal(selector, { ...options, ...wslUserAct(args) }, worktree) + : this.createTerminal(selector, { ...options, ...wslUserAct(args) }), + pasteDraft: (handle, draft) => this.pasteStartupDraftWhenReady(handle, draft), + sendFollowup: (handle, followup, terminal) => + void this.deliverStartupFollowup(handle, followup, { terminalCreation: terminal }), + provision: (options) => + this.provisionManagedWorktreeTerminals({ ...options, ...wslUserAct(args) }, worktree), + activate + } + } } diff --git a/src/main/runtime/workspaces/removal/workspace-registration-removal.ts b/src/main/runtime/workspaces/removal/workspace-registration-removal.ts index f4f502f1233..0090c5ac466 100644 --- a/src/main/runtime/workspaces/removal/workspace-registration-removal.ts +++ b/src/main/runtime/workspaces/removal/workspace-registration-removal.ts @@ -5,7 +5,15 @@ import type { Repo } from '../../../../shared/repo-types' import type { ExecutionHostId } from '../../../../shared/execution-host' import type { WorktreeTeardownRuntime } from './worktree-teardown' import { splitWorktreeId, splitWorktreeIdForFilesystem } from '../../../../shared/worktree/id' -import { parseExecutionHostId } from '../../../../shared/execution-host' +import { isRepoOnCatalogHost, parseExecutionHostId } from '../../../../shared/execution-host' +import type { RemoveWorktreeResult } from '../../../../shared/worktree/create-types' +import { readWorktreeMetaForRepo } from '../../../persistence/host-qualified-worktree-meta' +import { getEffectiveHooks } from '../../../workspace-hooks/hooks' +import { getLocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' +import { + gateFolderWorkspaceRemovalOnArchiveHook, + removeFolderWorkspaceRunnerFiles +} from '../../../workspaces/removal/folder-workspace-archive-hook' import { invalidateAuthorizedRootsCache } from '../../../ipc/worktrees/removal/registered-worktree-roots-cache' import { isFolderRepo } from '../../../../shared/repo-kind' import { getRuntimeFolderWorkspaceRootId } from '../catalog/runtime-folder-workspace' @@ -33,7 +41,8 @@ export async function removeOrphanOrFolderWorktree({ removalTarget, cleanupHostId, removalHostId, - repo + repo, + archive }: { runtime: WorkspaceRegistrationRemovalRuntime store: RuntimeStore @@ -41,7 +50,9 @@ export async function removeOrphanOrFolderWorktree({ cleanupHostId?: ExecutionHostId removalHostId?: ExecutionHostId repo?: Repo -}): Promise<{ warning?: string } | undefined> { + /** Same opt-in as worktree removal: archive runs only when the caller asked for hooks. */ + archive: { runHooks: boolean; allowFailedArchiveHook: boolean } +}): Promise<(RemoveWorktreeResult & { warning?: string }) | undefined> { if (!repo) { const orphanHost = parseExecutionHostId(store.getWorktreeMeta(removalTarget.id)?.hostId) if (cleanupHostId && orphanHost?.id !== cleanupHostId) { @@ -106,6 +117,23 @@ export async function removeOrphanOrFolderWorktree({ if (removalTarget.id === getRuntimeFolderWorkspaceRootId(repo)) { throw new Error('Cannot delete the project root workspace. Remove the folder project instead.') } + // Archive failure must refuse before watcher, PTY or metadata teardown (#19334). + const archiveHookOverride = await gateFolderWorkspaceRemovalOnArchiveHook({ + repo, + worktreeId: removalTarget.id, + displayName: + ( + readWorktreeMetaForRepo(store, removalTarget.id, repo) ?? + store.getWorktreeMeta(removalTarget.id) + )?.displayName ?? repo.displayName, + runArchive: archive.runHooks, + allowFailure: archive.allowFailedArchiveHook, + runtimeTarget: () => getLocalProjectWorktreeGitOptions(store, repo) + }) + const archiveSkipped = + !archive.runHooks && + isRepoOnCatalogHost(repo) && + 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) const folderConnectionId = folderHost?.kind === 'ssh' ? folderHost.targetId : null @@ -121,10 +149,19 @@ export async function removeOrphanOrFolderWorktree({ folderConnectionId ) await runtime.removeWorktreeMetadataAndHistory(store, removalTarget.id, removalHostId) + removeFolderWorkspaceRunnerFiles(repo, removalTarget.id) runtime.preservedBranchCleanup.delete(removalTarget.id, cleanupHostId) runtime.invalidateResolvedWorktreeCache() runtime.notifyWorktreesChanged(repo.id) - return {} + return { + ...(archiveHookOverride ? { archiveHookOverride } : {}), + ...(archiveSkipped + ? { + warning: + 'orca.yaml archive hook skipped for this folder workspace; pass --run-hooks to run it.' + } + : {}) + } } finally { await gate.finish(false) } diff --git a/src/main/runtime/workspaces/removal/workspace-removal.ts b/src/main/runtime/workspaces/removal/workspace-removal.ts index 110f3210a12..f4b8967642b 100644 --- a/src/main/runtime/workspaces/removal/workspace-removal.ts +++ b/src/main/runtime/workspaces/removal/workspace-removal.ts @@ -77,10 +77,7 @@ export abstract class OrcaRuntimeWithRemoveManagedWorktree extends RuntimeWorksp allowFailedArchiveHook = false, hostId } = options - if (!this.store) { - throw new Error('runtime_unavailable') - } - const store = this.store + const store = this.requireStore() const cleanupHostId = parseExecutionHostId(hostId)?.id const removalTarget = await this.resolveWorktreeRemovalTarget(worktreeSelector, cleanupHostId) // The repo row names the host; a caller may omit hostId for a worktree on another host. @@ -144,7 +141,8 @@ export abstract class OrcaRuntimeWithRemoveManagedWorktree extends RuntimeWorksp removalTarget, cleanupHostId, removalHostId, - repo + repo, + archive: { runHooks, allowFailedArchiveHook } }) if (orphanOrFolderResult) { return orphanOrFolderResult diff --git a/src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.ts b/src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.ts index 0e2ee76b7d1..dade1601abc 100644 --- a/src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.ts +++ b/src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.ts @@ -23,7 +23,7 @@ import type { WorktreeTerminalProvisioningArgs } from './runtime-worktree-terminal-provisioning' -type Ports = { +export type RuntimeLocalWorktreeTerminalPorts = { canSpawn: boolean provisionInBackground?: () => boolean createTerminal: ( @@ -76,7 +76,7 @@ export async function startRuntimeLocalWorktreeTerminals(args: { promisedAgentChat?: boolean draftPaste?: WorktreeStartupDraftPaste warning?: string - ports: Ports + ports: RuntimeLocalWorktreeTerminalPorts }): Promise { const { request, repo, worktree, defaultTabs, startup, ports } = args let { setup } = args diff --git a/src/main/workspace-hooks/created-worktree-setup-trust.ts b/src/main/workspace-hooks/created-worktree-setup-trust.ts index 9cd6393cf5d..f9b4fdcd706 100644 --- a/src/main/workspace-hooks/created-worktree-setup-trust.ts +++ b/src/main/workspace-hooks/created-worktree-setup-trust.ts @@ -39,6 +39,28 @@ export function checkCreatedWorktreeSetupTrust( return matches ? undefined : { contentHash, scriptContent } } +/** + * Older clients send no approval hash. A folder's shared setup never ran before folder setup + * existed, so it needs an approval or an explicit run rather than starting unseen. + */ +export function folderSharedSetupLacksApproval( + repo: Repo, + createdYamlHooks: OrcaHooks | null, + decision: SetupDecision | undefined, + approved: ApprovedSetupHashes +): boolean { + if (approved.approvedSetupHash !== undefined || approved.approvedSetupHashes !== undefined) { + return false + } + if (decision === 'run') { + return false + } + const policy = resolveHookCommandSourcePolicy(repo.hookSettings?.commandSourcePolicy, { + hasLocalScript: Boolean(repo.hookSettings?.scripts.setup?.trim()) + }) + return policy !== 'local-only' && Boolean(getSetupTrustContent(createdYamlHooks)) +} + function wouldRunSetup(repo: Repo, decision: SetupDecision | undefined): boolean { try { return shouldRunSetupForCreate(repo, decision) diff --git a/src/main/workspace-hooks/folder-setup-runner-files.test.ts b/src/main/workspace-hooks/folder-setup-runner-files.test.ts new file mode 100644 index 00000000000..bde4b093645 --- /dev/null +++ b/src/main/workspace-hooks/folder-setup-runner-files.test.ts @@ -0,0 +1,45 @@ +import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { newFolderSetupRunnerPath, removeFolderSetupRunnerFiles } from './folder-setup-runner-files' + +const WORKSPACE_A = 'repo::/acme::workspace:11111111-1111-4111-8111-111111111111' +const WORKSPACE_B = 'repo::/acme::workspace:22222222-2222-4222-8222-222222222222' + +let folder: string + +beforeEach(() => { + folder = mkdtempSync(join(tmpdir(), 'orca-folder-runner-')) +}) + +afterEach(() => { + rmSync(folder, { recursive: true, force: true }) +}) + +function writeRunner(worktreeId: string): string { + const path = newFolderSetupRunnerPath(folder, worktreeId, 'sh') + mkdirSync(dirname(path), { recursive: true }) + writeFileSync(path, 'echo setup\n') + return path +} + +describe('folder setup runner files', () => { + it('gives every launch its own file, so a later launch never rewrites a running script', () => { + const first = writeRunner(WORKSPACE_A) + const second = writeRunner(WORKSPACE_A) + expect(first).not.toBe(second) + expect(dirname(first)).toBe(join(folder, '.orca')) + }) + + it("removes only the removed workspace's runners", async () => { + writeRunner(WORKSPACE_A) + writeRunner(WORKSPACE_A) + const kept = writeRunner(WORKSPACE_B) + writeFileSync(join(folder, '.orca', 'issue-command'), 'claude') + await removeFolderSetupRunnerFiles(folder, WORKSPACE_A) + expect(readdirSync(join(folder, '.orca')).sort()).toEqual( + ['issue-command', kept.split(/[\\/]/).pop()!].sort() + ) + }) +}) diff --git a/src/main/workspace-hooks/folder-setup-runner-files.ts b/src/main/workspace-hooks/folder-setup-runner-files.ts new file mode 100644 index 00000000000..67d27a77270 --- /dev/null +++ b/src/main/workspace-hooks/folder-setup-runner-files.ts @@ -0,0 +1,47 @@ +import { randomUUID } from 'node:crypto' +import { readdir, unlink } from 'node:fs/promises' +import { join } from 'node:path' +import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR } from '../../shared/worktree/id' + +const FOLDER_RUNNER_DIR = '.orca' + +function runnerPrefix(worktreeId: string): string { + const separatorIdx = worktreeId.lastIndexOf(FOLDER_WORKSPACE_INSTANCE_SEPARATOR) + const instance = + separatorIdx === -1 + ? 'root' + : worktreeId.slice(separatorIdx + FOLDER_WORKSPACE_INSTANCE_SEPARATOR.length) + return `setup-runner-${instance.replace(/[^A-Za-z0-9-]/g, '_')}-` +} + +/** A fresh file per launch: workspaces share the folder, and bash/cmd re-read a runner by offset while it runs. */ +export function newFolderSetupRunnerPath( + folderPath: string, + worktreeId: string, + extension: 'sh' | 'cmd' +): string { + return join( + folderPath, + FOLDER_RUNNER_DIR, + `${runnerPrefix(worktreeId)}${randomUUID()}.${extension}` + ) +} + +/** 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 prefix = runnerPrefix(worktreeId) + const names = await readdir(dir).catch(() => [] as string[]) + await Promise.all( + names + .filter((name) => name.startsWith(prefix)) + .map((name) => + unlink(join(dir, name)).catch((error: unknown) => { + console.warn(`[hooks] could not remove setup runner ${name} in ${dir}:`, error) + }) + ) + ) +} diff --git a/src/main/workspace-hooks/hook-archive-timeout-observation.test.ts b/src/main/workspace-hooks/hook-archive-timeout-observation.test.ts index 7a22d7f5c61..c81ae6d2897 100644 --- a/src/main/workspace-hooks/hook-archive-timeout-observation.test.ts +++ b/src/main/workspace-hooks/hook-archive-timeout-observation.test.ts @@ -15,7 +15,7 @@ async function runArchive(script: string, timeoutMs = 400) { const dir = mkdtempSync(join(tmpdir(), 'orca-hook-deadline-')) writeFileSync(join(dir, 'orca.yaml'), `scripts:\n archive: |\n ${script}\n`) try { - return await runHook('archive', dir, REPO, dir, undefined, timeoutMs) + return await runHook('archive', dir, REPO, dir, undefined, { timeoutMs }) } finally { rmSync(dir, { recursive: true, force: true }) } diff --git a/src/main/workspace-hooks/hook-orca-cli-env.ts b/src/main/workspace-hooks/hook-orca-cli-env.ts new file mode 100644 index 00000000000..03ab7e4c8c3 --- /dev/null +++ b/src/main/workspace-hooks/hook-orca-cli-env.ts @@ -0,0 +1,67 @@ +import { getAppEnvironment, hasAppEnvironment } from '../../shared/app-environment' +import { toLinuxPath } from '../../shared/wsl-paths' +import { prependOrcaCliDirToChildPath } from '../cli/orca-cli-child-path' +import { getManagedWslCliDir, getWslCliCommandName } from '../cli/wsl-managed-cli' +import { WSL_MANAGED_CLI_PATH_RESTORE } from '../wsl/execution/wsl-managed-cli-path-restore' + +// A hook isn't a pane: an Orca started from an Orca terminal must not lend that pane's identity. +const INHERITED_PANE_IDENTITY_KEYS = [ + 'ORCA_TERMINAL_HANDLE', + 'ORCA_PANE_KEY', + 'ORCA_TAB_ID', + 'ORCA_AGENT_LAUNCH_TOKEN', + 'ORCA_WORKSPACE_ID', + 'ORCA_WORKTREE_ID' +] as const + +/** Give an in-process hook this app's `orca` CLI, as terminals get it. */ +export function applyHostHookOrcaCliEnv(env: Record): void { + for (const key of INHERITED_PANE_IDENTITY_KEYS) { + delete env[key] + } + if (!hasAppEnvironment()) { + return + } + const app = getAppEnvironment() + const userDataPath = app.getPath('userData') + const childEnv = Object.fromEntries( + Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined) + ) + childEnv.ORCA_USER_DATA_PATH = userDataPath + prependOrcaCliDirToChildPath(childEnv, { + isPackaged: app.isPackaged(), + userDataPath, + resourcesPath: process.resourcesPath ?? null + }) + for (const key of Object.keys(env)) { + if (!(key in childEnv)) { + delete env[key] + } + } + Object.assign(env, childEnv) +} + +/** The guest env and a script prefix that puts the managed WSL CLI first on PATH. */ +export function wslHookOrcaCliEnv(): { env: Record; scriptPrefix: string } { + if (!hasAppEnvironment()) { + return { env: {}, scriptPrefix: '' } + } + const app = getAppEnvironment() + const userDataPath = app.getPath('userData') + const managedCliDir = getManagedWslCliDir({ + isPackaged: app.isPackaged(), + userDataPath, + ...(process.resourcesPath ? { resourcesPath: process.resourcesPath } : {}) + }) + if (!managedCliDir) { + return { env: {}, scriptPrefix: '' } + } + return { + env: { + ORCA_WSL_CLI_DIR: toLinuxPath(managedCliDir), + ORCA_CLI_COMMAND: getWslCliCommandName(app.isPackaged()), + ORCA_USER_DATA_PATH: toLinuxPath(userDataPath) + }, + scriptPrefix: `${WSL_MANAGED_CLI_PATH_RESTORE}\n` + } +} diff --git a/src/main/workspace-hooks/hook-termination-real-process.test.ts b/src/main/workspace-hooks/hook-termination-real-process.test.ts index fc8d02cce38..fc4123fd6e5 100644 --- a/src/main/workspace-hooks/hook-termination-real-process.test.ts +++ b/src/main/workspace-hooks/hook-termination-real-process.test.ts @@ -27,7 +27,7 @@ async function survivorsAfterDeadline( ) let pids: number[] = [] try { - const result = await runHook('archive', dir, REPO, dir, undefined, 400) + const result = await runHook('archive', dir, REPO, dir, undefined, { timeoutMs: 400 }) expect(result.success).toBe(false) expect(existsSync(pidFile)).toBe(true) pids = readFileSync(pidFile, 'utf8').trim().split(/\s+/).map(Number) diff --git a/src/main/workspace-hooks/hooks.ts b/src/main/workspace-hooks/hooks.ts index 94a74cc949d..937198cbfe5 100644 --- a/src/main/workspace-hooks/hooks.ts +++ b/src/main/workspace-hooks/hooks.ts @@ -4,7 +4,8 @@ import { parseOrcaYaml } from '../../shared/orca-yaml' import { resolveHookCommandSourcePolicy } from '../../shared/hook-command-source-policy' import { getEffectiveHooksFromConfig } from './effective-hook-config' import { getHookRuntimeTarget, getHookWslContext } from './hook-runtime-target' -import { getSetupEnvVars } from './setup-hook-env-vars' +import { getSetupEnvVars, type HookWorkspaceIdentity } from './setup-hook-env-vars' +import { applyHostHookOrcaCliEnv, wslHookOrcaCliEnv } from './hook-orca-cli-env' import { iterateLfScriptLines } from './setup-runner-script-text' import { promptGuardShellEnv } from '../git/command-runner/git-process-env' import { dropIncoherentCondaActivationEnv } from '../pty/shell-startup/conda-activation-env' @@ -185,9 +186,10 @@ export function runHook( repo: Repo, hooksPath?: string, projectRuntime?: ProjectExecutionRuntimeResolution | HookRuntimeTarget, - timeoutMs: number = HOOK_TIMEOUT + options: { identity?: HookWorkspaceIdentity; timeoutMs?: number } = {} // Failed hooks without an observed exit are unverifiable to the removal gate (#19334). ): Promise<{ success: boolean; output: string; exitCode?: number }> { + const timeoutMs = options.timeoutMs ?? HOOK_TIMEOUT const hooks = getEffectiveHooks(repo, hooksPath) const script = hooks?.scripts[hookName] @@ -200,14 +202,15 @@ export function runHook( if (wslInfo) { // WSL hooks need Linux paths for ORCA_* values, including Windows UNC paths. - const envVars = getSetupEnvVars(repo, cwd) + const envVars = getSetupEnvVars(repo, cwd, options.identity) const wslEnv: Record = {} for (const [key, value] of Object.entries(envVars)) { wslEnv[key] = toLinuxPath(value) } // Forward unattended Git flags to WSL; keep host askpass out of the guest. const guardedEnv = promptGuardShellEnv(wslEnv) - const guestEnv: Record = { ...wslEnv } + const wslCli = wslHookOrcaCliEnv() + const guestEnv: Record = { ...wslEnv, ...wslCli.env } for (const [key, value] of Object.entries(guardedEnv)) { if (value !== undefined && (key === 'GIT_TERMINAL_PROMPT' || key === 'GCM_INTERACTIVE')) { guestEnv[key] = value @@ -217,7 +220,7 @@ export function runHook( return runWslProcess({ distro: wslInfo.distro ?? undefined, loginPath: 'preferred', - script, + script: `${wslCli.scriptPrefix}${script}`, // Match native Bash hook semantics; sh would reject Bash-only scripts inside WSL. shell: 'bash', cwd: wslInfo.linuxPath, @@ -228,7 +231,9 @@ export function runHook( .catch((error: unknown) => hookSpawnFailure(error, { hookName, cwd })) } - const shellHookEnv: NodeJS.ProcessEnv = { ...process.env, ...getSetupEnvVars(repo, cwd) } + const shellHookEnv: NodeJS.ProcessEnv = { ...process.env } + applyHostHookOrcaCliEnv(shellHookEnv) + Object.assign(shellHookEnv, getSetupEnvVars(repo, cwd, options.identity)) dropIncoherentCondaActivationEnv(shellHookEnv) return new Promise((resolve) => { diff --git a/src/main/workspace-hooks/setup-hook-env-vars.ts b/src/main/workspace-hooks/setup-hook-env-vars.ts index 77bcdcaf148..9181db25d5f 100644 --- a/src/main/workspace-hooks/setup-hook-env-vars.ts +++ b/src/main/workspace-hooks/setup-hook-env-vars.ts @@ -1,6 +1,13 @@ import { getRuntimePathBasename } from '../../shared/cross-platform-path' import { TERMINAL_GIT_CREDENTIAL_GUARD_POLICY_ENV } from '../../shared/shell/launch/terminal-git-credential-guard' import type { Repo } from '../../shared/repo-types' +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 +} // Keep WSL path translation in pty/wsl-orca-env.ts in sync; names and policies are not paths. export const SETUP_RUNNER_PATH_ENV_KEYS = [ @@ -10,20 +17,33 @@ export const SETUP_RUNNER_PATH_ENV_KEYS = [ 'GHOSTX_ROOT_PATH' ] as const -export function getSetupEnvVars(repo: Repo, worktreePath: string): Record { +export function getSetupEnvVars( + repo: Repo, + worktreePath: string, + identity?: HookWorkspaceIdentity +): Record { return { ORCA_ROOT_PATH: repo.path, ORCA_WORKTREE_PATH: worktreePath, - ORCA_WORKSPACE_NAME: getRuntimePathBasename(worktreePath), + ORCA_WORKSPACE_NAME: + identity && 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 } + : {}), // Legacy conductor.json compatibility. CONDUCTOR_ROOT_PATH: repo.path, GHOSTX_ROOT_PATH: repo.path } } -export function getSetupRunnerEnvVars(repo: Repo, worktreePath: string): Record { +export function getSetupRunnerEnvVars( + repo: Repo, + worktreePath: string, + identity?: HookWorkspaceIdentity +): Record { return { - ...getSetupEnvVars(repo, worktreePath), + ...getSetupEnvVars(repo, worktreePath, identity), // Unattended setup always needs credential protection, regardless of user opt-out. [TERMINAL_GIT_CREDENTIAL_GUARD_POLICY_ENV]: 'guard' } diff --git a/src/main/workspace-hooks/worktree-runner-script.ts b/src/main/workspace-hooks/worktree-runner-script.ts index cc3ca4c067d..f214394cdc5 100644 --- a/src/main/workspace-hooks/worktree-runner-script.ts +++ b/src/main/workspace-hooks/worktree-runner-script.ts @@ -1,4 +1,4 @@ -import { mkdirSync, writeFileSync, chmodSync } from 'node:fs' +import { chmod, mkdir, writeFile } from 'node:fs/promises' import { dirname } from 'node:path' import { shouldWaitForSetupBeforeAgentStartup } from '../../shared/agent-launch/startup/setup-agent-startup-policy' import { @@ -20,7 +20,13 @@ import { getHookWslContext, type HookRuntimeTarget } from './hook-runtime-target' -import { SETUP_RUNNER_PATH_ENV_KEYS, getSetupRunnerEnvVars } from './setup-hook-env-vars' +import { + SETUP_RUNNER_PATH_ENV_KEYS, + getSetupRunnerEnvVars, + type HookWorkspaceIdentity +} from './setup-hook-env-vars' +import { newFolderSetupRunnerPath } from './folder-setup-runner-files' +import { isFolderRepo } from '../../shared/repo-kind' import { buildPosixRunnerScript, buildWindowsRunnerScript } from './setup-runner-script-text' import type { Repo } from '../../shared/repo-types' @@ -44,9 +50,11 @@ export async function createSetupRunnerScript( script: string, projectRuntime?: ProjectExecutionRuntimeResolution | HookRuntimeTarget, setupShell?: SetupRunnerShell, - projectStartupPolicy?: SetupAgentStartupPolicy + projectStartupPolicy?: SetupAgentStartupPolicy, + identity?: HookWorkspaceIdentity ): Promise { return createWorktreeRunnerScript({ + identity, repo, worktreePath, script, @@ -68,6 +76,7 @@ async function createWorktreeRunnerScript(args: { runtimeTarget?: HookRuntimeTarget waitForAgentStartup?: boolean setupShell?: SetupRunnerShell + identity?: HookWorkspaceIdentity }): Promise { const { repo, @@ -76,9 +85,10 @@ async function createWorktreeRunnerScript(args: { runnerBaseName, runtimeTarget, waitForAgentStartup, - setupShell + setupShell, + identity } = args - const envVars = getSetupRunnerEnvVars(repo, worktreePath) + const envVars = getSetupRunnerEnvVars(repo, worktreePath, identity) const wslWorktree = isWslPath(worktreePath) || Boolean(runtimeTarget?.wslDistro) const nativeWindowsWorktree = process.platform === 'win32' && !wslWorktree // Preserve existing Windows cmd script syntax; only a shebang opts into bash, regardless of terminal preference. @@ -93,34 +103,23 @@ async function createWorktreeRunnerScript(args: { : process.platform === 'win32' && runtimeTarget?.wslDistro ? { family: 'posix', executable: 'wsl.exe' } : undefined - // Linked worktrees have .git files; resolve the per-worktree gitdir through Git. const runnerExtension = runnerShell.family === 'cmd' ? 'cmd' : 'sh' - const gitRelPath = `orca/${runnerBaseName}.${runnerExtension}` - // Read the link with the D1c Git router (if WSL Git made the worktree, host Git can't). A worktree - // inside a distro never runs synchronous Git: that would be a synchronous wsl.exe on the main thread. - const fromLink = isWslPath(worktreePath) - ? await resolveWslWorktreeGitPath(worktreePath, gitRelPath) - : isLocalGitRuntimeRouterInstalled() - ? readWorktreeGitPath(worktreePath, gitRelPath, knownWslAutomountRoots()) - : null - let runnerScriptPath = fromLink ?? getGitPath(worktreePath, gitRelPath) + const runnerScriptPath = isFolderRepo(repo) + ? newFolderSetupRunnerPath( + worktreePath, + requireFolderIdentity(identity).worktreeId, + runnerExtension + ) + : await resolveGitRunnerScriptPath(worktreePath, runnerBaseName, runnerExtension, runtimeTarget) - // Convert WSL Git's Linux path to a path Windows filesystem calls can reach. - if (wslWorktree && !fromLink) { - const wslInfo = getHookWslContext(worktreePath, runtimeTarget) - if (wslInfo?.distro) { - runnerScriptPath = toWindowsWslPath(runnerScriptPath.trim(), wslInfo.distro) - } - } - - mkdirSync(dirname(runnerScriptPath), { recursive: true }) + await mkdir(dirname(runnerScriptPath), { recursive: true }) if (runnerShell.family === 'cmd') { - writeFileSync(runnerScriptPath, buildWindowsRunnerScript(script), 'utf-8') + await writeFile(runnerScriptPath, buildWindowsRunnerScript(script), 'utf-8') } else { - writeFileSync(runnerScriptPath, buildPosixRunnerScript(script), 'utf-8') + await writeFile(runnerScriptPath, buildPosixRunnerScript(script), 'utf-8') if (!nativeWindowsWorktree) { - chmodSync(runnerScriptPath, 0o755) + await chmod(runnerScriptPath, 0o755) } } @@ -148,6 +147,41 @@ async function createWorktreeRunnerScript(args: { } } +function requireFolderIdentity(identity: HookWorkspaceIdentity | undefined): HookWorkspaceIdentity { + if (!identity) { + throw new Error('A folder workspace setup runner needs the workspace it runs for.') + } + return identity +} + +async function resolveGitRunnerScriptPath( + worktreePath: string, + runnerBaseName: 'setup-runner', + runnerExtension: 'sh' | 'cmd', + runtimeTarget: HookRuntimeTarget | undefined +): Promise { + const wslWorktree = isWslPath(worktreePath) || Boolean(runtimeTarget?.wslDistro) + // Linked worktrees have .git files; resolve the per-worktree gitdir through Git. + const gitRelPath = `orca/${runnerBaseName}.${runnerExtension}` + // Read the link with the D1c Git router (if WSL Git made the worktree, host Git can't). A worktree + // inside a distro never runs synchronous Git: that would be a synchronous wsl.exe on the main thread. + const fromLink = isWslPath(worktreePath) + ? await resolveWslWorktreeGitPath(worktreePath, gitRelPath) + : isLocalGitRuntimeRouterInstalled() + ? readWorktreeGitPath(worktreePath, gitRelPath, knownWslAutomountRoots()) + : null + let runnerScriptPath = fromLink ?? getGitPath(worktreePath, gitRelPath) + + // Convert WSL Git's Linux path to a path Windows filesystem calls can reach. + if (wslWorktree && !fromLink) { + const wslInfo = getHookWslContext(worktreePath, runtimeTarget) + if (wslInfo?.distro) { + runnerScriptPath = toWindowsWslPath(runnerScriptPath.trim(), wslInfo.distro) + } + } + return runnerScriptPath +} + export function resolveSetupRunnerShell( settings: SetupRunnerShellSettings, platform: NodeJS.Platform = process.platform, diff --git a/src/main/workspaces/removal/folder-workspace-archive-hook.ts b/src/main/workspaces/removal/folder-workspace-archive-hook.ts new file mode 100644 index 00000000000..2485b85cbfe --- /dev/null +++ b/src/main/workspaces/removal/folder-workspace-archive-hook.ts @@ -0,0 +1,40 @@ +import { isRepoOnCatalogHost } from '../../../shared/execution-host' +import type { Repo } from '../../../shared/repo-types' +import type { ArchiveHookOverride } from '../../../shared/worktree/archive-hook-removal-gate' +import { removeFolderSetupRunnerFiles } from '../../workspace-hooks/folder-setup-runner-files' +import { getEffectiveHooks, runHook } from '../../workspace-hooks/hooks' +import type { HookRuntimeTarget } from '../../workspace-hooks/hook-runtime-target' +import { gateWorktreeRemovalOnArchiveHook } from './worktree-archive-hook-gate' + +/** + * Run a folder workspace's archive script before anything is torn down, as worktree removal does. + * Only the host holding the folder runs it; others own no files there. + */ +export async function gateFolderWorkspaceRemovalOnArchiveHook(args: { + repo: Repo + worktreeId: string + displayName: string + runArchive: boolean + allowFailure: boolean + runtimeTarget: () => HookRuntimeTarget | undefined +}): Promise { + const { repo } = args + if (!args.runArchive || !isRepoOnCatalogHost(repo) || !getEffectiveHooks(repo)?.scripts.archive) { + return undefined + } + const result = await runHook('archive', repo.path, repo, repo.path, args.runtimeTarget(), { + identity: { worktreeId: args.worktreeId, displayName: args.displayName } + }) + return gateWorktreeRemovalOnArchiveHook({ + worktreePath: repo.path, + result, + allowFailure: args.allowFailure + }) +} + +/** 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) + } +} diff --git a/src/renderer/src/components/settings/repository/RepositoryPane.tsx b/src/renderer/src/components/settings/repository/RepositoryPane.tsx index 50871a8077f..35444bb9248 100644 --- a/src/renderer/src/components/settings/repository/RepositoryPane.tsx +++ b/src/renderer/src/components/settings/repository/RepositoryPane.tsx @@ -5,6 +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 { getRepoExecutionHostId, type ExecutionHostId } from '../../../../../shared/execution-host' import { Label } from '../../ui/label' import { useShallow } from 'zustand/react/shallow' @@ -104,6 +105,7 @@ export function RepositoryPane({ }: RepositoryPaneProps): React.JSX.Element { const t = useTranslate() const isFolder = isFolderRepo(repo) + const hooksSupported = useFolderSetupSupported(repo) // Bind writes to the switcher-selected owner; same-ID/self-paired repos must not use focused-host fallback. const selectedHostId = getRepoExecutionHostId(repo) const updateSelectedRepo = useCallback( @@ -212,7 +214,8 @@ export function RepositoryPane({ const projectRuntimeEntries = allEntries.filter((entry) => entry.title === 'Project Runtime') const hooksSection = - !isFolder && (forceFullPaneForRepoMatch || matchesSettingsSearch(searchQuery, hooksEntries)) ? ( + hooksSupported && + (forceFullPaneForRepoMatch || matchesSettingsSearch(searchQuery, hooksEntries)) ? ( ) : null} - - - + {isFolder ? null : ( + + )} ) } + +/** The issue command needs a GitHub repo, so only Git projects mount its file inspection. */ +function RepositoryIssueCommandRow({ + repo, + repoHostIdentity, + forceVisible +}: { + repo: Repo + repoHostIdentity: string + forceVisible: boolean +}): React.JSX.Element { + const t = useTranslate() + const issueCommand = useRepositoryIssueCommand({ + repoId: repo.id, + repoHostIdentity, + selectedHostId: getRepoExecutionHostId(repo) + }) + return ( + + + + ) +} diff --git a/src/renderer/src/components/settings/repository/execution/repository-git-hooks-search-entries.ts b/src/renderer/src/components/settings/repository/execution/repository-git-hooks-search-entries.ts index a76f4b8da2f..adcc3c14822 100644 --- a/src/renderer/src/components/settings/repository/execution/repository-git-hooks-search-entries.ts +++ b/src/renderer/src/components/settings/repository/execution/repository-git-hooks-search-entries.ts @@ -1,4 +1,5 @@ import type { Repo } from '../../../../../../shared/repo-types' +import { isFolderRepo } from '../../../../../../shared/repo-kind' import type { SettingsSearchEntry } from '../../search/settings-search' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' @@ -134,42 +135,46 @@ export function getRepositoryGitHooksSearchEntries( ) ] }, - { - title: t( - 'auto.components.settings.repository.search.d86ea12d16', - 'Custom GitHub Issue Command' - ), - description: t( - 'auto.components.settings.repository.search.d42d1e49c0', - 'File-based linked-issue command configured via orca.yaml and optional local override.' - ), - keywords: [ - repo.displayName, - ...translateSearchKeyword( - 'auto.components.settings.repository.search.2011a6a4f2', - 'github issue command' - ), - ...translateSearchKeyword( - 'auto.components.settings.repository.search.66b584bd6c', - 'issue command' - ), - ...translateSearchKeyword( - 'auto.components.settings.repository.search.ec70364df2', - 'workflow' - ), - ...translateSearchKeyword( - 'auto.components.settings.repository.search.9dc60d7f6d', - 'github' - ), - ...translateSearchKeyword( - 'auto.components.settings.repository.search.603c68b68c', - 'orca.yaml' - ), - ...translateSearchKeyword( - 'auto.components.settings.repository.search.bc7e504b8e', - '.orca/issue-command' - ) - ] - } + ...(isFolderRepo(repo) + ? [] + : [ + { + title: t( + 'auto.components.settings.repository.search.d86ea12d16', + 'Custom GitHub Issue Command' + ), + description: t( + 'auto.components.settings.repository.search.d42d1e49c0', + 'File-based linked-issue command configured via orca.yaml and optional local override.' + ), + keywords: [ + repo.displayName, + ...translateSearchKeyword( + 'auto.components.settings.repository.search.2011a6a4f2', + 'github issue command' + ), + ...translateSearchKeyword( + 'auto.components.settings.repository.search.66b584bd6c', + 'issue command' + ), + ...translateSearchKeyword( + 'auto.components.settings.repository.search.ec70364df2', + 'workflow' + ), + ...translateSearchKeyword( + 'auto.components.settings.repository.search.9dc60d7f6d', + 'github' + ), + ...translateSearchKeyword( + 'auto.components.settings.repository.search.603c68b68c', + 'orca.yaml' + ), + ...translateSearchKeyword( + 'auto.components.settings.repository.search.bc7e504b8e', + '.orca/issue-command' + ) + ] + } + ]) ] } diff --git a/src/renderer/src/components/settings/repository/execution/use-folder-setup-supported.ts b/src/renderer/src/components/settings/repository/execution/use-folder-setup-supported.ts new file mode 100644 index 00000000000..42ab580ae75 --- /dev/null +++ b/src/renderer/src/components/settings/repository/execution/use-folder-setup-supported.ts @@ -0,0 +1,43 @@ +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 { 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 + const [supportedEnvironmentId, setSupportedEnvironmentId] = useState(null) + useEffect(() => { + if (!environmentId) { + return + } + let cancelled = false + void runtimeEnvironmentSupportsCapability( + environmentId, + WORKTREE_FOLDER_SETUP_RUNTIME_CAPABILITY + ) + .catch(() => false) + .then((supported) => { + if (!cancelled && supported) { + setSupportedEnvironmentId(environmentId) + } + }) + return () => { + cancelled = true + } + }, [environmentId]) + if (!isFolderRepo(repo)) { + return true + } + // An unserved SSH folder runs no hooks; its files aren't on a host Orca runs scripts on. + if (host?.kind === 'ssh') { + return false + } + return environmentId ? supportedEnvironmentId === environmentId : true +} diff --git a/src/renderer/src/components/settings/repository/repository-search.ts b/src/renderer/src/components/settings/repository/repository-search.ts index 4e47547207f..b8a4a39db7b 100644 --- a/src/renderer/src/components/settings/repository/repository-search.ts +++ b/src/renderer/src/components/settings/repository/repository-search.ts @@ -246,7 +246,7 @@ export function getRepositoryPaneSearchEntries( ] }, ...(isFolder - ? [] + ? getRepositoryGitHooksSearchEntries(repo, t) : [ ...getRepositoryGitAuthorSearchEntries(repo, t), ...getRepositoryGitHooksSearchEntries(repo, t) diff --git a/src/renderer/src/hooks/composer-state/composer-external-sync.ts b/src/renderer/src/hooks/composer-state/composer-external-sync.ts index 8ab3bd9aa86..38e8c36f867 100644 --- a/src/renderer/src/hooks/composer-state/composer-external-sync.ts +++ b/src/renderer/src/hooks/composer-state/composer-external-sync.ts @@ -24,7 +24,6 @@ export function useComposerExternalSync(target: ComposerTargetState): ComposerEx selectedRepoConnectionIdRef: target.asyncComposerState.selectedRepoConnectionIdRef, selectedRepoExecutionHostId: target.runtimeTargetSelection.selectedRepoExecutionHostId, selectedRepoHookContextKey: target.runtimeTargetSelection.selectedRepoHookContextKey, - selectedRepoIsGit: target.runtimeTargetSelection.selectedRepoIsGit, selectedRepoSshStatus: target.runtimeTargetSelection.selectedRepoSshStatus, setTuiAgent: target.workspaceIdentityState.setTuiAgent, settings: target.composerTargetStore.settings, 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 738291040af..566397470e0 100644 --- a/src/renderer/src/hooks/composer-state/derived-composer-state.ts +++ b/src/renderer/src/hooks/composer-state/derived-composer-state.ts @@ -120,11 +120,11 @@ export function useDerivedComposerState(input: DerivedComposerStateInput) { const currentYamlHooks = checkedHooksContextKey === selectedRepoHookContextKey ? yamlHooks : null const setupConfig = useMemo( - () => (selectedRepoIsGit ? getSetupConfig(selectedRepo, currentYamlHooks) : null), - [currentYamlHooks, selectedRepo, selectedRepoIsGit] + () => (selectedRepo ? getSetupConfig(selectedRepo, currentYamlHooks) : null), + [currentYamlHooks, selectedRepo] ) const isSetupCheckPending = - selectedRepoIsGit && + Boolean(selectedRepo) && Boolean(selectedRepoHookContextKey) && checkedHooksContextKey !== selectedRepoHookContextKey const { 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 df460e35790..7776145fc34 100644 --- a/src/renderer/src/hooks/composer-state/host-runtime-effects.ts +++ b/src/renderer/src/hooks/composer-state/host-runtime-effects.ts @@ -19,7 +19,6 @@ type HostRuntimeEffectsInput = Pick< | 'selectedRepoConnectionIdRef' | 'selectedRepoExecutionHostId' | 'selectedRepoHookContextKey' - | 'selectedRepoIsGit' | 'selectedRepoSshStatus' | 'setTuiAgent' | 'settings' @@ -66,7 +65,6 @@ export function useHostRuntimeEffects(input: HostRuntimeEffectsInput) { selectedRepoConnectionIdRef, selectedRepoExecutionHostId, selectedRepoHookContextKey, - selectedRepoIsGit, selectedRepoSshStatus, setTuiAgent, settings, @@ -114,7 +112,8 @@ export function useHostRuntimeEffects(input: HostRuntimeEffectsInput) { ]) useEffect(() => { - if (!repoId || !selectedRepoIsGit || !selectedRepoHookContextKey) { + // Folder projects have setup scripts too; hosts without folder setup report none for them. + if (!repoId || !selectedRepoHookContextKey) { return } @@ -139,7 +138,6 @@ export function useHostRuntimeEffects(input: HostRuntimeEffectsInput) { loadHookCheckForRepo, repoId, selectedRepoHookContextKey, - selectedRepoIsGit, runtimeEnvironmentId ]) 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 e4e0cd20d2b..a1cd70f639f 100644 --- a/src/renderer/src/hooks/composer-state/quick-submit-preparation.ts +++ b/src/renderer/src/hooks/composer-state/quick-submit-preparation.ts @@ -77,7 +77,6 @@ export function useQuickSubmitPreparation(input: QuickSubmitPreparationInput) { let submitResolvedSetupDecision = resolvedSetupDecision if ( - selectedRepoIsGit && setupPolicy === 'ask' && selectedRepoHookContextKey && checkedHooksContextKey !== selectedRepoHookContextKey @@ -99,34 +98,33 @@ export function useQuickSubmitPreparation(input: QuickSubmitPreparationInput) { submitResolvedSetupDecision = submitSetup.resolvedSetupDecision } - if (selectedRepoIsGit && submitSetupConfig && setupPolicy === 'ask' && !setupDecision) { + if (submitSetupConfig && setupPolicy === 'ask' && !setupDecision) { setAdvancedOpen(true) return null } - const effectiveSetupDecision: SetupDecision = selectedRepoIsGit - ? (submitResolvedSetupDecision ?? 'inherit') - : 'skip' + // Folder projects inherit too; a host without folder setup ignores it for them. + const effectiveSetupDecision: SetupDecision = submitResolvedSetupDecision ?? 'inherit' const submitLinkedWorkItemProvider = submitLinkedWorkItem ? getLinkedWorkItemProvider(submitLinkedWorkItem) : null - const hookPreparation: WorktreeCreationRequest['hookPreparation'] = selectedRepoIsGit - ? { - executionHostId: selectedRepoExecutionHostId ?? undefined, - issueCommand: - enableIssueAutomation && - submitLinkedIssueNumber !== null && - canUseIssueCommandForLinkedItemProvider(submitLinkedWorkItemProvider) && - selectedRepoExecutionHostId && - selectedRepoHookContextKey - ? { - provider: submitLinkedWorkItemProvider, - issueNumber: submitLinkedIssueNumber, - artifactUrl: submitLinkedWorkItem?.url ?? null - } - : undefined - } - : undefined + // Setup trust applies to folder projects too; the issue command needs a Git repo. + const hookPreparation: WorktreeCreationRequest['hookPreparation'] = { + executionHostId: selectedRepoExecutionHostId ?? undefined, + issueCommand: + selectedRepoIsGit && + enableIssueAutomation && + submitLinkedIssueNumber !== null && + canUseIssueCommandForLinkedItemProvider(submitLinkedWorkItemProvider) && + selectedRepoExecutionHostId && + selectedRepoHookContextKey + ? { + provider: submitLinkedWorkItemProvider, + issueNumber: submitLinkedIssueNumber, + artifactUrl: submitLinkedWorkItem?.url ?? null + } + : undefined + } const linkedLinearIssue = submitLinkedWorkItem && submitLinkedWorkItemProvider === 'linear' diff --git a/src/shared/folder-workspace-hooks.ts b/src/shared/folder-workspace-hooks.ts new file mode 100644 index 00000000000..6e24bd564f0 --- /dev/null +++ b/src/shared/folder-workspace-hooks.ts @@ -0,0 +1,14 @@ +import type { OrcaHooks } from './orca-yaml-hook-types' +import type { Repo } from './repo-types' +import { isFolderRepo } from './repo-kind' + +/** Folder workspaces share one directory, so orca.yaml default tabs would start again for every one. */ +export function scopeHooksToRepoKind( + repo: Pick, + hooks: OrcaHooks | null +): OrcaHooks | null { + if (!hooks || !isFolderRepo(repo) || !hooks.defaultTabs) { + return hooks + } + return { ...hooks, defaultTabs: undefined } +} diff --git a/src/shared/worktree-runtime-capabilities.ts b/src/shared/worktree-runtime-capabilities.ts index 989d5a3359f..e1e7bacdbab 100644 --- a/src/shared/worktree-runtime-capabilities.ts +++ b/src/shared/worktree-runtime-capabilities.ts @@ -102,6 +102,9 @@ export const WORKSPACE_SELECTOR_FOLDER_MATCH_RUNTIME_CAPABILITY = export const WORKTREE_RUN_APPROVED_SETUP_RUNTIME_CAPABILITY = 'worktree.run-approved-setup.v1' as const +// Hosts that run a folder project's setup and archive scripts when its workspaces are created and removed. +export const WORKTREE_FOLDER_SETUP_RUNTIME_CAPABILITY = 'worktree.folder-setup.v1' as const + // Hosts that honor branchIntent 'create-exact': the unsuffixed new branch, or a coded refusal. export const WORKTREE_CREATE_EXACT_NAME_RUNTIME_CAPABILITY = 'worktree.create.exact-name.v1' as const @@ -135,6 +138,7 @@ export const WORKTREE_RUNTIME_CAPABILITIES = [ WORKTREE_SET_FOLDER_PARENT_RUNTIME_CAPABILITY, WORKSPACE_SELECTOR_FOLDER_MATCH_RUNTIME_CAPABILITY, WORKTREE_RUN_APPROVED_SETUP_RUNTIME_CAPABILITY, + WORKTREE_FOLDER_SETUP_RUNTIME_CAPABILITY, WORKTREE_CREATE_EXACT_NAME_RUNTIME_CAPABILITY, ...(ORCA_SIDEBAR_INPUTS_IS_MAIN ? [] : [WORKTREE_ROWS_CHANGED_EVENT_RUNTIME_CAPABILITY]) ] as const