Files
archived-orca/src/main/runtime/runtime-folder-worktree-create.ts
T
Neil 0b2158a394 fix(wsl): name the stopped distro, in the user's language, when main holds a terminal start (#36228)
Worktree-create startup, setup and initial terminals built their warning
from the raw terminal_held_wsl_distro_* code, and the window showed it
as is, as it did for a held pane recovery. Main now writes the readable
sentence into those warnings, and the window swaps either form for
localized copy naming the distro. The runtime spawn's hold and its
wslBackgroundStart option now share one verdict.
2026-10-29 22:47:30 -07:00

248 lines
10 KiB
TypeScript

import { readableWslDistroHoldText } from '../../shared/wsl-distro-stopped-hold'
import { paneIdentity } from './runtime-terminal-pane-identity'
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../shared/layout-owner-switch'
import { shouldSeedWorktreePrimaryTerminal } from '../../shared/worktree-first-surface'
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-types'
import type { CreateWorktreeResult } from '../../shared/worktree/create-types'
import type { Repo } from '../../shared/repo-types'
import type { TuiAgent } from '../../shared/tui-agent'
import type { WorktreeStartupLaunch } from '../../shared/worktree/launch-types'
import type { AgentLaunchRuntime } from '../../shared/agent-launch-runtime'
import {
getRuntimeFolderWorkspaceInstanceId,
mergeRuntimeFolderWorkspace
} from './runtime-folder-workspace'
import type { RuntimeManagedWorktreeCreateArgs } from './runtime-managed-worktree-create-types'
import type { RuntimeStore } from './runtime-store-contract'
import type { TerminalCreateOptions } from './runtime-terminal-contracts'
import type {
WorktreeStartupDraftPaste,
WorktreeStartupFollowup
} from './runtime-worktree-agent-startup'
import { hostWorktreeTargetForRepo } from '../persistence/host-qualified-worktree-meta'
type RuntimeFolderWorktreeCreateDeps = {
store: RuntimeStore
ptySpawnAvailable: boolean
provisionInBackground?: () => boolean
createTerminal: (
selector: string,
options: TerminalCreateOptions
) => Promise<RuntimeTerminalCreate>
pasteDraft: (handle: string, draft: WorktreeStartupDraftPaste) => void
sendFollowup: (handle: string, followup: WorktreeStartupFollowup) => void
invalidateResolvedWorktrees: () => void
notifyWorktreesChanged: (repoId: string) => void
emitCreated: (event: {
kind: 'created'
worktreeId: string
path: string
branch: string
}) => void
activate: (
repoId: string,
worktreeId: string,
setup?: undefined,
startup?: WorktreeStartupLaunch,
providesInitialSurface?: boolean
) => void
}
export async function createRuntimeFolderWorktree(args: {
request: RuntimeManagedWorktreeCreateArgs
repo: Repo
startup?: WorktreeStartupLaunch
startupFollowup?: WorktreeStartupFollowup
/** What a host-built startup was quoted for, or the repair error it fails with. */
startupLaunchRuntime?: AgentLaunchRuntime | Error
createdWithAgent?: TuiAgent
promisedAgentChat?: boolean
onWorkspaceCreated?: (worktreeId: string) => void
draftPaste?: WorktreeStartupDraftPaste
deps: RuntimeFolderWorktreeCreateDeps
}): Promise<CreateWorktreeResult> {
const { request, repo, deps } = args
const now = Date.now()
const settings = deps.store.getSettings()
const instanceId = randomUUID()
const worktreeId = getRuntimeFolderWorkspaceInstanceId(repo, instanceId)
const displayNameRequest = resolveWorktreeCreateDisplayNameRequest(
request.displayName,
request.displayNameKind,
request.name,
request.cliProvenance?.kind === 'created-by-cli',
request.nameWasGenerated === true
)
const resolvedFolderDisplayName = displayNameRequest.value
const meta = deps.store.setWorktreeMeta(hostWorktreeTargetForRepo(worktreeId, repo), {
instanceId,
...getProjectHostSetupWorktreeMeta(deps.store.getProjectHostSetups?.() ?? [], repo),
displayName: resolvedFolderDisplayName ?? request.name,
...(displayNameRequest.kind === 'user' && resolvedFolderDisplayName
? { displayNameIsPinned: true }
: {}),
lastActivityAt: now,
createdAt: now,
orcaCreatedAt: now,
orcaCreationSource: 'runtime',
orcaCreationWorkspaceLayout: {
path: settings.workspaceDir,
nestWorkspaces: settings.nestWorkspaces
},
...(request.automationProvenance ? { automationProvenance: request.automationProvenance } : {}),
...(request.cliProvenance ? { cliProvenance: request.cliProvenance } : {}),
creatorProvenance: request.creatorProvenance ?? { kind: 'host' },
...(request.linkedIssue !== undefined ? { linkedIssue: request.linkedIssue } : {}),
...(request.linkedPR !== undefined ? { linkedPR: request.linkedPR } : {}),
...(request.linkedLinearIssue !== undefined
? { linkedLinearIssue: request.linkedLinearIssue }
: {}),
...(request.linkedLinearIssueWorkspaceId !== undefined
? { linkedLinearIssueWorkspaceId: request.linkedLinearIssueWorkspaceId }
: {}),
...(request.linkedLinearIssueOrganizationUrlKey !== undefined
? { linkedLinearIssueOrganizationUrlKey: request.linkedLinearIssueOrganizationUrlKey }
: {}),
...(request.linkedGitLabIssue !== undefined
? { linkedGitLabIssue: request.linkedGitLabIssue }
: {}),
...(request.linkedGitLabMR !== undefined ? { linkedGitLabMR: request.linkedGitLabMR } : {}),
...(request.linkedBitbucketPR !== undefined
? { linkedBitbucketPR: request.linkedBitbucketPR }
: {}),
...(request.linkedAzureDevOpsPR !== undefined
? { linkedAzureDevOpsPR: request.linkedAzureDevOpsPR }
: {}),
...(request.linkedGiteaPR !== undefined ? { linkedGiteaPR: request.linkedGiteaPR } : {}),
...(request.linkedWorkItem !== undefined ? { linkedWorkItem: request.linkedWorkItem } : {}),
...(request.linkedItems !== undefined ? { linkedItems: request.linkedItems } : {}),
...(request.linkedTaskSourceContext !== undefined
? { linkedTaskSourceContext: request.linkedTaskSourceContext }
: {}),
...(args.createdWithAgent ? { createdWithAgent: args.createdWithAgent } : {}),
...(request.comment !== undefined ? { comment: request.comment } : {}),
...(request.manualOrder !== undefined ? { manualOrder: request.manualOrder } : {}),
...(request.workspaceStatus !== undefined ? { workspaceStatus: request.workspaceStatus } : {})
})
args.onWorkspaceCreated?.(worktreeId)
const worktree = mergeRuntimeFolderWorkspace(repo, worktreeId, meta)
deps.invalidateResolvedWorktrees()
deps.notifyWorktreesChanged(repo.id)
deps.emitCreated({
kind: 'created',
worktreeId: worktree.id,
path: worktree.path,
branch: worktree.branch
})
const shouldActivate = request.activate === true || request.runHooks === true
let warning: string | undefined
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)) {
try {
const launchRuntime = args.startupLaunchRuntime
if (launchRuntime instanceof Error && !ORCA_LAYOUT_OWNER_IS_MAIN) {
throw launchRuntime
}
const terminal = await deps.createTerminal(`id:${worktree.id}`, {
command: args.startup.command,
...(request.startupCwd ? { cwd: request.startupCwd } : {}),
...paneIdentity(request.startupPaneKey),
env: args.startup.env,
...(args.startup.launchConfig ? { launchConfig: args.startup.launchConfig } : {}),
...(args.createdWithAgent ? { launchAgent: args.createdWithAgent } : {}),
...(launchRuntime instanceof Error
? { startFailure: launchRuntime }
: launchRuntime
? { launchRuntime }
: {}),
...(args.startup.viewMode ? { viewMode: args.startup.viewMode } : {}),
startupCommandDelivery: args.startup.startupCommandDelivery,
telemetry: args.startup.telemetry,
// Keep failed main-owned starts visible in their panes.
...(ORCA_LAYOUT_OWNER_IS_MAIN ? { keepPaneOnStartFailure: true as const } : {}),
...(shouldActivate ? {} : { surfaceOwner: false })
})
if (args.draftPaste) {
deps.pasteDraft(terminal.handle, args.draftPaste)
}
if (args.startupFollowup) {
deps.sendFollowup(terminal.handle, args.startupFollowup)
}
didSpawnStartup = true
startupTerminal = {
spawned: true,
handle: terminal.handle,
...(terminal.tabId ? { tabId: terminal.tabId } : {}),
...(terminal.paneKey ? { paneKey: terminal.paneKey } : {}),
...(terminal.ptyId ? { ptyId: terminal.ptyId } : {}),
surface: 'background'
}
} catch (error) {
const message = readableWslDistroHoldText(
error instanceof Error ? error.message : String(error)
)
warning = `Failed to create the startup terminal for ${worktree.path}: ${message}`
console.warn(`[worktree-create] ${warning}`)
}
}
if (shouldActivate) {
deps.activate(
repo.id,
worktree.id,
undefined,
// Main retains failed startup presentation; the window must not take it over.
ORCA_LAYOUT_OWNER_IS_MAIN
? undefined
: args.startup && !didSpawnStartup
? args.startup
: undefined,
...(args.promisedAgentChat && !args.startup ? ([true] as const) : [])
)
}
if (
(!shouldActivate || deps.provisionInBackground?.() === true) &&
deps.ptySpawnAvailable &&
shouldSeedWorktreePrimaryTerminal({
// Failed agents retain their panes; do not seed a shell beside them.
hasPrimarySurface: didSpawnStartup || (ORCA_LAYOUT_OWNER_IS_MAIN && Boolean(args.startup)),
// Background attribution-only creates have historically omitted the shell.
callerProvidesSurface: args.promisedAgentChat === true || args.createdWithAgent !== undefined
})
) {
try {
await deps.createTerminal(`id:${worktree.id}`, { surfaceOwner: false })
} catch (error) {
const message = readableWslDistroHoldText(
error instanceof Error ? error.message : String(error)
)
const initialWarning = `Failed to create the initial terminal for ${worktree.path}: ${message}`
warning = warning
? `${warning} Also failed to create the initial terminal for ${worktree.path}: ${message}`
: initialWarning
console.warn(`[worktree-create] ${warning}`)
}
}
return {
worktree: {
...worktree,
parentWorktreeId: null,
childWorktreeIds: [],
lineage: null,
git: {
path: worktree.path,
head: worktree.head,
branch: worktree.branch,
isBare: worktree.isBare,
isMainWorktree: worktree.isMainWorktree
}
},
...(startupTerminal ? { startupTerminal } : {}),
...(warning ? { warning } : {})
}
}