mirror of
https://github.com/stablyai/orca.git
synced 2026-11-18 20:06:10 +00:00
Preserve group setup startup input across paired hosts
This commit is contained in:
@@ -57,6 +57,7 @@ vi.mock('../workspaces/creation/worktree-root-preparation', () =>
|
||||
moduleMocks.worktreeRootPreparationModuleMock(reposMocks)
|
||||
)
|
||||
|
||||
import { ipcMain } from 'electron'
|
||||
import { registerRepoHandlers } from './repos'
|
||||
import { clearGitCapabilityStateForTests } from '../git/command-runner/host-routing/git-capability-state'
|
||||
import { resetSshProviderAuthorities } from '../ssh/connection/authority/ssh-provider-authority'
|
||||
@@ -91,6 +92,33 @@ describe('projectGroups IPC validation', () => {
|
||||
registerRepoHandlers(mockWindow as never, mockStore as never, {} as never)
|
||||
})
|
||||
|
||||
it('re-registers group hook inspection and subsequent handlers when a window reopens', () => {
|
||||
const registered = new Map<string, (...args: unknown[]) => unknown>()
|
||||
handleMock.mockImplementation((channel: string, handler: (...args: unknown[]) => unknown) => {
|
||||
if (registered.has(channel)) {
|
||||
throw new Error(`Handler already registered: ${channel}`)
|
||||
}
|
||||
registered.set(channel, handler)
|
||||
})
|
||||
vi.mocked(ipcMain.removeHandler).mockImplementation((channel) => {
|
||||
registered.delete(channel)
|
||||
})
|
||||
const runtime = { checkProjectGroupHooks: vi.fn(() => ({ status: 'ok' })) }
|
||||
try {
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the registration harness supplies only the window, store and runtime ports invoked by these handlers.
|
||||
registerRepoHandlers(mockWindow as never, mockStore as never, runtime as never)
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the registration harness supplies only the window, store and runtime ports invoked by these handlers.
|
||||
registerRepoHandlers(mockWindow as never, mockStore as never, runtime as never)
|
||||
expect(registered.get('projectGroups:checkHooks')?.(null, { groupId: 'group-1' })).toEqual({
|
||||
status: 'ok'
|
||||
})
|
||||
expect(registered.get('projectGroups:list')?.()).toEqual([])
|
||||
expect(registered.has('folderWorkspaces:create')).toBe(true)
|
||||
} finally {
|
||||
vi.mocked(ipcMain.removeHandler).mockReset()
|
||||
}
|
||||
})
|
||||
|
||||
describe('while a WSL move fences the local repo-1', () => {
|
||||
let userDataPath: string
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -35,6 +35,7 @@ export function registerRepoHandlers(
|
||||
ipcMain.removeHandler('projectHostSetups:setupExistingFolder')
|
||||
ipcMain.removeHandler('projectHostSetups:update')
|
||||
ipcMain.removeHandler('projectHostSetups:delete')
|
||||
ipcMain.removeHandler('projectGroups:checkHooks')
|
||||
ipcMain.removeHandler('projectGroups:list')
|
||||
ipcMain.removeHandler('projectGroups:create')
|
||||
ipcMain.removeHandler('projectGroups:update')
|
||||
|
||||
@@ -7,7 +7,10 @@ import { WorkspaceAttachmentsSchema } from '../../../shared/workspace-attachment
|
||||
import { isWorkspaceLinkedItemSourceContextMatch } from '../../../shared/workspace-attachments/workspace-linked-item-source-context'
|
||||
import { DiffCommentSchema } from '../../../shared/diff-comment-schema'
|
||||
import { normalizeExecutionHostId } from '../../../shared/execution-host'
|
||||
import { FolderWorkspaceHookCreateShape } from '../../../shared/rpc-contract/folder-workspace-params'
|
||||
import {
|
||||
FolderWorkspaceHookCreateShape,
|
||||
assertFolderWorkspaceStartupDelivery
|
||||
} from '../../../shared/rpc-contract/folder-workspace-params'
|
||||
|
||||
export const ProjectGroupCreateArgs = z.object({
|
||||
name: z.string().min(1),
|
||||
@@ -161,6 +164,7 @@ export const FolderWorkspaceCreateArgs = z
|
||||
pendingFirstAgentMessageRename: z.boolean().optional()
|
||||
})
|
||||
.superRefine(assertFolderWorkspaceLinkedSourceContextMatch)
|
||||
.superRefine(assertFolderWorkspaceStartupDelivery)
|
||||
|
||||
export const FolderWorkspaceUpdateArgs = z.object({
|
||||
folderWorkspaceId: z.string().min(1),
|
||||
|
||||
@@ -18,3 +18,125 @@ describe('orchestration setup completion signal', () => {
|
||||
expect(onComplete).toHaveBeenCalledWith(17)
|
||||
})
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'observes the exact sequenced Setup invocation once and keeps its failure result',
|
||||
async () => {
|
||||
const { mkdtempSync, readFileSync, rmSync, writeFileSync } = await import('node:fs')
|
||||
const { tmpdir } = await import('node:os')
|
||||
const { join } = await import('node:path')
|
||||
const { runProcessSync } = await import('@orca/process-host')
|
||||
const { createSequencedSetupAgentCommands } =
|
||||
await import('../../../../../shared/agent-launch/startup/setup-agent-sequencing')
|
||||
const { buildObservedSetupCommand } = await import('./setup-completion-signal')
|
||||
const root = mkdtempSync(join(tmpdir(), 'orca-observed-sequence-'))
|
||||
const runner = join(root, 'setup.sh')
|
||||
try {
|
||||
writeFileSync(runner, 'printf x >> "$RUN_RECEIPT"\nexit 17\n')
|
||||
const sequence = createSequencedSetupAgentCommands({
|
||||
runnerScriptPath: runner,
|
||||
startupCommand: 'codex',
|
||||
platform: 'posix',
|
||||
nonce: 'once'
|
||||
})
|
||||
const observed = buildObservedSetupCommand(
|
||||
runner,
|
||||
'posix',
|
||||
'token-exact',
|
||||
undefined,
|
||||
sequence.setupCommand
|
||||
)
|
||||
const result = runProcessSync({
|
||||
program: 'bash',
|
||||
args: ['-c', observed.command],
|
||||
env: {
|
||||
...process.env,
|
||||
...sequence.setupEnv,
|
||||
...observed.env,
|
||||
RUN_RECEIPT: join(root, 'ran')
|
||||
}
|
||||
})
|
||||
expect(result.code).toBe(17)
|
||||
expect(readFileSync(join(root, 'ran'), 'utf8')).toBe('x')
|
||||
expect(readFileSync(`${runner}.once.done`, 'utf8')).toBe('once:17\n')
|
||||
const completed = vi.fn()
|
||||
createSetupCompletionScanner('token-exact', completed).scan(result.stdout ?? '')
|
||||
expect(completed).toHaveBeenCalledExactlyOnceWith(17)
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it('keeps deep Windows sequenced invocations out of the typed observer payload', async () => {
|
||||
const { createSequencedSetupAgentCommands } =
|
||||
await import('../../../../../shared/agent-launch/startup/setup-agent-sequencing')
|
||||
const { buildObservedSetupCommand } = await import('./setup-completion-signal')
|
||||
const runner = `C:\\${'deep path\\'.repeat(80)}setup.cmd`
|
||||
const sequence = createSequencedSetupAgentCommands({
|
||||
runnerScriptPath: runner,
|
||||
startupCommand: 'codex',
|
||||
platform: 'windows'
|
||||
})
|
||||
const observed = buildObservedSetupCommand(
|
||||
runner,
|
||||
'windows',
|
||||
'token-windows',
|
||||
{ family: 'cmd' },
|
||||
sequence.setupCommand
|
||||
)
|
||||
expect(observed.env?.ORCA_OBSERVED_SETUP_COMMAND).toBe(sequence.setupCommand)
|
||||
expect(observed.command.length).toBeLessThan(1800)
|
||||
const gitBash = createSequencedSetupAgentCommands({
|
||||
runnerScriptPath: runner,
|
||||
startupCommand: 'codex',
|
||||
platform: 'windows',
|
||||
shell: { family: 'posix' }
|
||||
})
|
||||
const posixObserved = buildObservedSetupCommand(
|
||||
runner,
|
||||
'windows',
|
||||
'token-gitbash',
|
||||
{ family: 'posix' },
|
||||
gitBash.setupCommand
|
||||
)
|
||||
expect(posixObserved.command).toMatch(/^bash -lc /)
|
||||
expect(posixObserved.command.length).toBeLessThan(1000)
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'runs the generated POSIX example with the owning managed CLI name and quoted arguments',
|
||||
async () => {
|
||||
const { mkdtempSync, readFileSync, rmSync, writeFileSync } = await import('node:fs')
|
||||
const { tmpdir } = await import('node:os')
|
||||
const { join } = await import('node:path')
|
||||
const { runProcessSync } = await import('@orca/process-host')
|
||||
const { projectGroupSetupExample } =
|
||||
await import('../../../../../shared/project-group-setup-example')
|
||||
const root = mkdtempSync(join(tmpdir(), 'orca-group-cli-example-'))
|
||||
const cli = join(root, 'managed cli')
|
||||
const receipt = join(root, 'arguments')
|
||||
try {
|
||||
writeFileSync(cli, '#!/bin/bash\nprintf "%s\\n" "$@" > "$CLI_RECEIPT"\n', { mode: 0o755 })
|
||||
const result = runProcessSync({
|
||||
program: 'bash',
|
||||
args: [
|
||||
'-c',
|
||||
projectGroupSetupExample([{ id: 'repo-id', displayName: 'Services' }], 'linux')
|
||||
],
|
||||
env: {
|
||||
...process.env,
|
||||
ORCA_CLI_COMMAND: cli,
|
||||
ORCA_WORKSPACE_NAME: 'task & spaced',
|
||||
CLI_RECEIPT: receipt
|
||||
}
|
||||
})
|
||||
expect(result.code).toBe(0)
|
||||
expect(readFileSync(receipt, 'utf8')).toBe(
|
||||
'worktree\ncreate\n--repo\nid:repo-id\n--name\ntask & spaced\n--json\n'
|
||||
)
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
@@ -8,19 +8,22 @@ import {
|
||||
const SETUP_COMPLETION_PREFIX = '__ORCA_SETUP_COMPLETE__:'
|
||||
const SETUP_COMPLETION_CARRY_LENGTH = SETUP_COMPLETION_PREFIX.length + 96
|
||||
const WINDOWS_SETUP_RUNNER_ENV = 'ORCA_SETUP_RUNNER_PATH'
|
||||
const OBSERVED_SETUP_COMMAND_ENV = 'ORCA_OBSERVED_SETUP_COMMAND'
|
||||
|
||||
export function buildObservedSetupCommand(
|
||||
runnerScriptPath: string,
|
||||
platform: SetupRunnerCommandPlatform,
|
||||
completionToken: string,
|
||||
// Preserve runner shell selection so WSL drive paths stay /mnt/c rather than Git Bash /c.
|
||||
shell?: SetupRunnerShell
|
||||
shell?: SetupRunnerShell,
|
||||
sequencedCommand?: string
|
||||
): { command: string; env?: Record<string, string> } {
|
||||
const resolution = resolveSetupRunnerCommand(runnerScriptPath, platform, shell)
|
||||
if (resolution.shell === 'windows') {
|
||||
if (resolution.shell === 'windows' && !(sequencedCommand && shell?.family === 'posix')) {
|
||||
const script = [
|
||||
`$runner = $env:${WINDOWS_SETUP_RUNNER_ENV}`,
|
||||
'& $runner',
|
||||
...(sequencedCommand
|
||||
? [`& ([scriptblock]::Create($env:${OBSERVED_SETUP_COMMAND_ENV}))`]
|
||||
: [`$runner = $env:${WINDOWS_SETUP_RUNNER_ENV}`, '& $runner']),
|
||||
'$succeeded = $?',
|
||||
'$status = $LASTEXITCODE',
|
||||
'if ($null -eq $status) { $status = if ($succeeded) { 0 } else { 1 } }',
|
||||
@@ -32,13 +35,15 @@ export function buildObservedSetupCommand(
|
||||
script,
|
||||
'utf16le'
|
||||
).toString('base64')}`,
|
||||
env: { [WINDOWS_SETUP_RUNNER_ENV]: resolution.runnerScriptPathForShell }
|
||||
env: sequencedCommand
|
||||
? { [OBSERVED_SETUP_COMMAND_ENV]: sequencedCommand }
|
||||
: { [WINDOWS_SETUP_RUNNER_ENV]: resolution.runnerScriptPathForShell }
|
||||
}
|
||||
}
|
||||
|
||||
// Why no `( … )`: this is typed into the user's line editor, where autopair widgets corrupt it (#18059).
|
||||
const script = [
|
||||
resolution.command,
|
||||
sequencedCommand ?? resolution.command,
|
||||
'status=$?',
|
||||
`printf '\\n${completionPrefix(completionToken)}%s\\n' "$status"`,
|
||||
'exit "$status"'
|
||||
|
||||
@@ -106,6 +106,7 @@ export async function deliverTerminalAgentLaunchPrompt(args: {
|
||||
clock?: ReadinessClock
|
||||
/** Aborting ends the readiness wait and refuses the paste; text already handed over stays so. */
|
||||
signal?: AbortSignal
|
||||
beforeWrite?: (ptyId: string) => void
|
||||
}): Promise<boolean> {
|
||||
if (args.text.trim().length === 0) {
|
||||
return false
|
||||
@@ -137,7 +138,10 @@ export async function deliverTerminalAgentLaunchPrompt(args: {
|
||||
inputKind: 'launch',
|
||||
// A fresh launch's composer was just seen ready; a reused pane's state is only inferred.
|
||||
composerReady: args.freshLaunch,
|
||||
beforeWrite: guard.beforeWrite,
|
||||
beforeWrite: async (ptyId) => {
|
||||
await guard.beforeWrite(ptyId)
|
||||
args.beforeWrite?.(ptyId)
|
||||
},
|
||||
// Both fields enable queued acceptance; without requestId a slow first turn throws despite written input.
|
||||
acceptQueued: true,
|
||||
requestId: randomUUID(),
|
||||
|
||||
@@ -7,6 +7,7 @@ export async function groupSetupAgentOutcome(args: {
|
||||
terminalHandle?: string | null
|
||||
wait: (handle: string, signal: AbortSignal) => Promise<{ exitCode: number | null }>
|
||||
signal?: AbortSignal
|
||||
timeoutMs?: number
|
||||
}): Promise<FolderWorkspaceAgentLaunchOutcome> {
|
||||
if (!args.required) {
|
||||
return { status: 'not-required' }
|
||||
@@ -32,7 +33,10 @@ export async function groupSetupAgentOutcome(args: {
|
||||
resolve(outcome)
|
||||
}
|
||||
const cancel = (): void => finish({ status: 'failed', reason: 'cancelled' })
|
||||
const deadline = setTimeout(() => finish({ status: 'failed', reason: 'timeout' }), 60_000)
|
||||
const deadline = setTimeout(
|
||||
() => finish({ status: 'failed', reason: 'timeout' }),
|
||||
args.timeoutMs ?? 60_000
|
||||
)
|
||||
if (args.signal?.aborted) {
|
||||
cancel()
|
||||
return
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
groupFolderCreationIsUserAct,
|
||||
type RuntimeGroupFolderCreateInput
|
||||
} from './runtime-group-folder-setup'
|
||||
import type { RuntimeTerminalCreate } from '../../../../shared/runtime-terminal-create-contract'
|
||||
import type { ProjectGroup } from '../../../../shared/project-group-types'
|
||||
import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types'
|
||||
import type { Worktree } from '../../../../shared/worktree/types'
|
||||
@@ -12,6 +13,11 @@ import type { RuntimeLocalWorktreeTerminalPorts } from '../startup/runtime-local
|
||||
import { wslUserAct } from '../startup/workspace-create-activation'
|
||||
import { buildWorktreeStartupForAgent } from '../startup/runtime-worktree-agent-startup'
|
||||
import { resolveStartupAgentLaunchRuntime } from '../../terminal/launch/agent-launch-scope-runtime'
|
||||
import { createLaunchedAgentWriteGuard } from '../../terminal/wait/launched-agent-write-guard'
|
||||
import {
|
||||
deliverStartupFollowupPrompt,
|
||||
pasteWorktreeStartupDraftWhenReady
|
||||
} from '../startup/runtime-worktree-startup-readiness'
|
||||
import { projectGroupHookOwner } from '../../../../shared/workspace-hook-owner'
|
||||
|
||||
export abstract class OrcaRuntimeWithGroupFolderSetup extends OrcaRuntimeWithGetWorktreeTerminalProvisioningHost {
|
||||
@@ -58,6 +64,17 @@ export abstract class OrcaRuntimeWithGroupFolderSetup extends OrcaRuntimeWithGet
|
||||
})
|
||||
})
|
||||
}
|
||||
private assertGroupStartupInputTarget(target: RuntimeTerminalCreate, ptyId: string): void {
|
||||
const live = this.getLivePtyForHandle(target.handle)?.pty
|
||||
if (
|
||||
!target.ptyId ||
|
||||
target.ptyId !== ptyId ||
|
||||
live?.ptyId !== target.ptyId ||
|
||||
(target.incarnationId && live.incarnationId !== target.incarnationId)
|
||||
) {
|
||||
throw new Error('terminal_handle_stale')
|
||||
}
|
||||
}
|
||||
protected localWorktreeTerminalPorts(
|
||||
args: { navigation?: RuntimeNavigationTarget; wslUserAct?: true },
|
||||
activate: RuntimeLocalWorktreeTerminalPorts['activate'],
|
||||
@@ -70,9 +87,38 @@ export abstract class OrcaRuntimeWithGroupFolderSetup extends OrcaRuntimeWithGet
|
||||
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 }),
|
||||
pasteDraft: (handle, draft, target) => {
|
||||
if (!target) {
|
||||
this.pasteStartupDraftWhenReady(handle, draft)
|
||||
return
|
||||
}
|
||||
const guard = createLaunchedAgentWriteGuard(this, draft.agent, {
|
||||
unprovableHost: 'write-unless-shell'
|
||||
})
|
||||
pasteWorktreeStartupDraftWhenReady(this.getWorktreeStartupReadinessHost(), handle, draft, {
|
||||
beforeWrite: async (ptyId) => {
|
||||
await guard.beforeWrite(ptyId)
|
||||
this.assertGroupStartupInputTarget(target, ptyId)
|
||||
},
|
||||
dispose: guard.dispose
|
||||
})
|
||||
},
|
||||
sendFollowup: (handle, followup, terminal, guardTarget) => {
|
||||
if (!guardTarget) {
|
||||
void this.deliverStartupFollowup(handle, followup, { terminalCreation: terminal })
|
||||
return
|
||||
}
|
||||
void deliverStartupFollowupPrompt(
|
||||
this,
|
||||
this.getWorktreeStartupReadinessHost(),
|
||||
handle,
|
||||
followup,
|
||||
{
|
||||
terminalCreation: terminal,
|
||||
beforeWrite: (ptyId) => this.assertGroupStartupInputTarget(terminal, ptyId)
|
||||
}
|
||||
)
|
||||
},
|
||||
provision: (options) =>
|
||||
this.provisionManagedWorktreeTerminals({ ...options, ...wslUserAct(args) }, worktree),
|
||||
activate
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { RuntimeTerminalCreate } from '../../../../shared/runtime-terminal-create-contract'
|
||||
import { SETUP_AGENT_WAIT_TIMEOUT_SECONDS } from '../../../../shared/agent-launch/startup/setup-agent-sequencing'
|
||||
import { blockedWslDistroForPath } from '../../../wsl/filesystem/wsl-unc-access-gate'
|
||||
import type {
|
||||
FolderWorkspaceCreateInput,
|
||||
@@ -110,6 +112,22 @@ export async function prepareGroupFolderCreation(args: {
|
||||
if (result.agentLaunchOutcome?.status === 'failed') {
|
||||
return result
|
||||
}
|
||||
const pendingDraft =
|
||||
input.startupCommand &&
|
||||
input.startupAgent &&
|
||||
input.startupPrompt &&
|
||||
input.startupPromptDelivery === 'draft'
|
||||
? { agent: input.startupAgent, content: input.startupPrompt }
|
||||
: undefined
|
||||
const pendingFollowup =
|
||||
input.startupCommand &&
|
||||
input.startupAgent &&
|
||||
input.startupPrompt &&
|
||||
input.startupPromptDelivery === 'auto-submit'
|
||||
? { agent: input.startupAgent, prompt: input.startupPrompt }
|
||||
: undefined
|
||||
const deferInput = required && Boolean(pendingDraft || pendingFollowup)
|
||||
const captured: { terminal?: RuntimeTerminalCreate } = {}
|
||||
const request = {
|
||||
...input,
|
||||
...(input.startupCommand
|
||||
@@ -124,7 +142,11 @@ export async function prepareGroupFolderCreation(args: {
|
||||
: {}),
|
||||
startupLaunchSource: input.launchSource,
|
||||
awaitTerminalProvisioning: true,
|
||||
observeSetupCompletion: input.agentLaunchMode === 'structured',
|
||||
observeSetupCompletion: input.agentLaunchMode === 'structured' || deferInput,
|
||||
onStartupTerminalCreated: (terminal: RuntimeTerminalCreate) => {
|
||||
captured.terminal = terminal
|
||||
input.onStartupTerminalCreated?.(terminal)
|
||||
},
|
||||
setupOnly: input.agentLaunchMode === 'structured'
|
||||
}
|
||||
const built = await resolveWorktreeCreateAgentStartup(request, args.buildStartup)
|
||||
@@ -134,12 +156,37 @@ export async function prepareGroupFolderCreation(args: {
|
||||
worktree: folderWorkspaceToWorktree(workspace),
|
||||
setup: prepared?.setup,
|
||||
startup: request.startup ?? built?.startup,
|
||||
startupFollowup: built?.followup,
|
||||
startupFollowup: deferInput ? undefined : (pendingFollowup ?? built?.followup),
|
||||
draftPaste: deferInput ? undefined : pendingDraft,
|
||||
observeSequencedSetupCompletion: deferInput,
|
||||
...(pendingDraft || pendingFollowup ? { guardStartupInput: true as const } : {}),
|
||||
startupLaunchRuntime: built?.launchRuntime,
|
||||
createdWithAgent: input.createdWithAgent,
|
||||
promisedAgentChat: input.agentLaunchMode === 'structured',
|
||||
ports: args.ports
|
||||
})
|
||||
if (deferInput && started.didSpawnStartup && captured.terminal) {
|
||||
const terminal = captured.terminal
|
||||
// The host owns pending input after create returns; RPC disconnect is not cancellation.
|
||||
void groupSetupAgentOutcome({
|
||||
required: true,
|
||||
prepared: Boolean(prepared?.setup),
|
||||
terminalHandle: started.setupTerminalHandle,
|
||||
wait: args.wait,
|
||||
timeoutMs: SETUP_AGENT_WAIT_TIMEOUT_SECONDS * 1000
|
||||
})
|
||||
.then((outcome) => {
|
||||
if (outcome.status !== 'successful') {
|
||||
return
|
||||
}
|
||||
if (pendingDraft) {
|
||||
args.ports.pasteDraft(terminal.handle, pendingDraft, terminal)
|
||||
} else if (pendingFollowup) {
|
||||
args.ports.sendFollowup(terminal.handle, pendingFollowup, terminal, true)
|
||||
}
|
||||
})
|
||||
.catch((error) => console.warn('[hooks] group startup input was not delivered:', error))
|
||||
}
|
||||
// Host-owned provisioning is never retried by renderer activation.
|
||||
result.setup = undefined
|
||||
result.warning = started.warning ?? result.warning
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
import { mkdtempSync, realpathSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { getDefaultRepoHookSettings, getDefaultSettings } from '../../../../shared/constants'
|
||||
import { createProjectGroup } from '../../../../shared/project-groups'
|
||||
import { prepareGroupFolderCreation } from './runtime-group-folder-setup'
|
||||
import { OrcaRuntimeWithGroupFolderSetup } from './runtime-group-folder-setup-host'
|
||||
import { provisionWorktreeTerminals } from '../startup/runtime-worktree-terminal-provisioning'
|
||||
import { OrcaRuntimeWithStartTuiIdleVisibleReadProbe } from '../../terminal/wait/terminal-wait-visible-probe'
|
||||
import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types'
|
||||
import type { RuntimeTerminalCreate } from '../../../../shared/runtime-terminal-create-contract'
|
||||
import type { RuntimeLocalWorktreeTerminalPorts } from '../startup/runtime-local-worktree-terminal-startup'
|
||||
|
||||
vi.mock('electron', () => ({ app: { getPath: () => tmpdir() } }))
|
||||
vi.mock('../startup/workspace-terminal-provisioning', () => ({
|
||||
OrcaRuntimeWithGetWorktreeTerminalProvisioningHost: class {}
|
||||
}))
|
||||
vi.mock('../../terminal/input/terminal-agent-prompt-render', () => ({
|
||||
OrcaRuntimeWithCreateAgentPromptRenderGate: class {}
|
||||
}))
|
||||
const roots: string[] = []
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
for (const root of roots.splice(0)) {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
function fixture(
|
||||
fast = false,
|
||||
unprovableHost = false,
|
||||
delivery: 'draft' | 'auto-submit' = 'draft'
|
||||
) {
|
||||
const root = realpathSync(mkdtempSync(join(tmpdir(), 'orca-group-pending-input-')))
|
||||
roots.push(root)
|
||||
const group = {
|
||||
...createProjectGroup({
|
||||
name: 'Services',
|
||||
parentPath: root,
|
||||
createdFrom: 'folder-scan',
|
||||
tabOrder: 0
|
||||
}),
|
||||
hookSettings: {
|
||||
...getDefaultRepoHookSettings(),
|
||||
scripts: { setup: 'echo setup', archive: '' },
|
||||
setupAgentStartupPolicy: 'wait-for-setup' as const,
|
||||
commandSourcePolicy: 'local-only' as const
|
||||
}
|
||||
}
|
||||
const workspace: FolderWorkspace = {
|
||||
id: 'task',
|
||||
projectGroupId: group.id,
|
||||
name: 'Task',
|
||||
folderPath: root,
|
||||
linkedTask: null,
|
||||
comment: '',
|
||||
isArchived: false,
|
||||
isUnread: false,
|
||||
isPinned: false,
|
||||
sortOrder: 0,
|
||||
lastActivityAt: 0,
|
||||
createdAt: 0,
|
||||
updatedAt: 0
|
||||
}
|
||||
const listeners = new Map<string, Set<(data: string) => void>>()
|
||||
const replay = new Map<string, string>()
|
||||
const tokens = new Map<string, string>()
|
||||
const agent = { ptyId: 'agent-pty', incarnationId: 'agent-incarnation' }
|
||||
let currentAgent = agent
|
||||
let launchedForeground = unprovableHost ? 'unknown' : 'agent'
|
||||
const write = vi.fn()
|
||||
const subscribe = (ptyId: string, listener: (data: string) => void) => {
|
||||
const subscriptions = listeners.get(ptyId) ?? new Set()
|
||||
listeners.set(ptyId, subscriptions)
|
||||
subscriptions.add(listener)
|
||||
return () => {
|
||||
subscriptions.delete(listener)
|
||||
}
|
||||
}
|
||||
const emit = (ptyId: string, data: string) => {
|
||||
replay.set(ptyId, data)
|
||||
for (const listener of listeners.get(ptyId) ?? []) {
|
||||
listener(data)
|
||||
}
|
||||
}
|
||||
const createTerminal = vi.fn(
|
||||
async (_selector: string, options: { title?: string }): Promise<RuntimeTerminalCreate> =>
|
||||
options.title === 'Setup'
|
||||
? { handle: 'setup', ptyId: 'setup-pty', title: 'Setup', worktreeId: 'folder:task' }
|
||||
: {
|
||||
handle: 'agent',
|
||||
ptyId: 'agent-pty',
|
||||
incarnationId: agent.incarnationId,
|
||||
tabId: 'agent-tab',
|
||||
title: 'Codex',
|
||||
worktreeId: 'folder:task'
|
||||
}
|
||||
)
|
||||
const getLivePtyForHandle = (handle: string) => ({
|
||||
pty: handle === 'agent' ? currentAgent : { ptyId: 'setup-pty' }
|
||||
})
|
||||
const readiness = {
|
||||
getPtyId: () => currentAgent.ptyId,
|
||||
getForegroundProcess: async () => 'codex',
|
||||
subscribeToData: subscribe,
|
||||
readRecentOutput: (ptyId: string) => replay.get(ptyId),
|
||||
write
|
||||
}
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the mocked superclass is empty; these are every port reached by group pending-input delivery.
|
||||
const runtime = Object.assign(Reflect.construct(OrcaRuntimeWithGroupFolderSetup, []), {
|
||||
ptyController: { spawn: vi.fn() },
|
||||
getLivePtyForHandle,
|
||||
createTerminal,
|
||||
getWorktreeStartupReadinessHost: () => readiness,
|
||||
readLaunchedAgentForeground: async () => launchedForeground,
|
||||
launchedAgentHostProvesAgent: () => !unprovableHost,
|
||||
launchedAgentHostProvesShellAlone: () => false,
|
||||
launchedAgentTerminalIdentity: () => currentAgent,
|
||||
subscribeToTerminalData: subscribe,
|
||||
shouldProvisionWorktreeInBackground: () => true,
|
||||
provisionManagedWorktreeTerminals: (args: Parameters<typeof provisionWorktreeTerminals>[1]) =>
|
||||
provisionWorktreeTerminals(
|
||||
{
|
||||
canSpawn: () => true,
|
||||
createTerminal,
|
||||
setTabTitle: async () => {},
|
||||
setTabColor: async () => {},
|
||||
getPtyId: () => 'setup-pty',
|
||||
recordSetupCompletionToken: (ptyId, token) => {
|
||||
tokens.set(ptyId, token)
|
||||
if (fast) {
|
||||
emit(ptyId, `\n__ORCA_SETUP_COMPLETE__:${token}:0\n`)
|
||||
}
|
||||
}
|
||||
},
|
||||
args
|
||||
)
|
||||
}) as { localWorktreeTerminalPorts: (...args: unknown[]) => RuntimeLocalWorktreeTerminalPorts }
|
||||
const waitHost = {
|
||||
getLivePtyForHandle,
|
||||
setupCompletionTokenByPtyId: tokens,
|
||||
recentPtyOutputById: new Map([['setup-pty', { read: () => replay.get('setup-pty') }]]),
|
||||
subscribeToTerminalData: subscribe,
|
||||
waitForTerminal: (_handle: string, options: { signal: AbortSignal }) =>
|
||||
new Promise((_resolve, reject) => {
|
||||
options.signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true })
|
||||
})
|
||||
}
|
||||
const wait = (handle: string, signal: AbortSignal) =>
|
||||
OrcaRuntimeWithStartTuiIdleVisibleReadProbe.prototype.waitForSetupTerminalCompletion.call(
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixture supplies every host port used by the production completion observer.
|
||||
waitHost as never,
|
||||
handle,
|
||||
signal
|
||||
)
|
||||
return {
|
||||
args: {
|
||||
group,
|
||||
workspace,
|
||||
input: {
|
||||
projectGroupId: group.id,
|
||||
startupCommand: 'codex --model custom',
|
||||
startupEnv: { CUSTOM: 'preserved' },
|
||||
startupAgent: 'codex' as const,
|
||||
startupPrompt: 'Inspect the linked task',
|
||||
startupPromptDelivery: delivery
|
||||
},
|
||||
settings: getDefaultSettings(root),
|
||||
ports: runtime.localWorktreeTerminalPorts({}, () => {}, { id: 'folder:task' }),
|
||||
wait,
|
||||
buildStartup: vi.fn()
|
||||
},
|
||||
write,
|
||||
createTerminal,
|
||||
listeners,
|
||||
finish: (status: number) =>
|
||||
emit('setup-pty', `\n__ORCA_SETUP_COMPLETE__:${tokens.get('setup-pty')}:${status}\n`),
|
||||
ready: () => emit('agent-pty', '\x1b[?2004h\x1b]7501;state=idle:app=codex\x1b\\'),
|
||||
shell: () => {
|
||||
launchedForeground = 'shell'
|
||||
},
|
||||
replace: () => {
|
||||
currentAgent = { ptyId: 'replacement', incarnationId: 'replacement' }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
it('returns creation before slow required Setup and starts real draft readiness only after observed success', async () => {
|
||||
vi.useFakeTimers()
|
||||
const f = fixture()
|
||||
const result = await prepareGroupFolderCreation(f.args)
|
||||
expect(result.startupTerminal?.tabId).toBe('agent-tab')
|
||||
await vi.advanceTimersByTimeAsync(30_000)
|
||||
expect(f.write).not.toHaveBeenCalled()
|
||||
f.finish(0)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
f.ready()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(f.write).toHaveBeenCalledExactlyOnceWith(
|
||||
'agent-pty',
|
||||
'\x1b[200~Inspect the linked task\x1b[201~',
|
||||
'launch'
|
||||
)
|
||||
expect(f.args.buildStartup).not.toHaveBeenCalled()
|
||||
expect(f.createTerminal.mock.calls[0]?.[1]).toMatchObject({
|
||||
env: expect.objectContaining({ CUSTOM: 'preserved' })
|
||||
})
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
|
||||
it('replays fast Setup completion without losing the unsent draft', async () => {
|
||||
vi.useFakeTimers()
|
||||
const f = fixture(true)
|
||||
await prepareGroupFolderCreation(f.args)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
f.ready()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(f.write).toHaveBeenCalledExactlyOnceWith(
|
||||
'agent-pty',
|
||||
'\x1b[200~Inspect the linked task\x1b[201~',
|
||||
'launch'
|
||||
)
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['draft', '\x1b[200~Inspect the linked task\x1b[201~'],
|
||||
['auto-submit', 'Inspect the linked task\r']
|
||||
] as const)('delivers %s once on a ready Windows-hosted WSL pane', async (delivery, expected) => {
|
||||
vi.useFakeTimers()
|
||||
const f = fixture(false, true, delivery)
|
||||
await prepareGroupFolderCreation(f.args)
|
||||
expect(f.write).not.toHaveBeenCalled()
|
||||
f.finish(0)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
f.ready()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(f.write).toHaveBeenCalledExactlyOnceWith('agent-pty', expected, 'launch')
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
|
||||
it('refuses a replaced Windows-hosted WSL target before typed followup', async () => {
|
||||
vi.useFakeTimers()
|
||||
const f = fixture(false, true, 'auto-submit')
|
||||
await prepareGroupFolderCreation(f.args)
|
||||
f.replace()
|
||||
f.finish(0)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(f.write).not.toHaveBeenCalled()
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
|
||||
it.each(['failed setup', 'replaced agent'] as const)(
|
||||
'never writes pending text after %s',
|
||||
async (failure) => {
|
||||
vi.useFakeTimers()
|
||||
const f = fixture()
|
||||
await prepareGroupFolderCreation(f.args)
|
||||
f.finish(failure === 'failed setup' ? 1 : 0)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
if (failure === 'replaced agent') {
|
||||
f.replace()
|
||||
}
|
||||
f.ready()
|
||||
await vi.advanceTimersByTimeAsync(10_000)
|
||||
expect(f.write).not.toHaveBeenCalled()
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
}
|
||||
)
|
||||
|
||||
it('refuses a proven shell after stale WSL draft readiness', async () => {
|
||||
vi.useFakeTimers()
|
||||
const f = fixture(false, true)
|
||||
await prepareGroupFolderCreation(f.args)
|
||||
f.shell()
|
||||
f.finish(0)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
f.ready()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(f.write).not.toHaveBeenCalled()
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
@@ -11,8 +11,6 @@ import type { WorktreeStartupLaunch } from '../../../../shared/worktree/launch-t
|
||||
import type { AgentLaunchRuntime } from '../../../../shared/agent-launch/startup/agent-launch-runtime'
|
||||
import { createSequencedSetupAgentCommands } from '../../../../shared/agent-launch/startup/setup-agent-sequencing'
|
||||
import { getSetupRunnerCommandPlatformForPath } from '../../../../shared/agent-launch/startup/setup-runner-command'
|
||||
import type { RuntimeTerminalCreate } from '../../../../shared/runtime-terminal-create-contract'
|
||||
import type { TerminalCreateOptions } from '../../terminal/launch/terminal-create-options'
|
||||
import type { RuntimeManagedWorktreeCreateArgs } from '../creation/runtime-managed-worktree-create-types'
|
||||
import type {
|
||||
WorktreeStartupDraftPaste,
|
||||
@@ -23,44 +21,11 @@ import type {
|
||||
WorktreeTerminalProvisioningArgs
|
||||
} from './runtime-worktree-terminal-provisioning'
|
||||
|
||||
export type RuntimeLocalWorktreeTerminalPorts = {
|
||||
canSpawn: boolean
|
||||
provisionInBackground?: () => boolean
|
||||
createTerminal: (
|
||||
selector: string,
|
||||
options: TerminalCreateOptions
|
||||
) => Promise<RuntimeTerminalCreate>
|
||||
pasteDraft: (handle: string, draft: WorktreeStartupDraftPaste) => void
|
||||
sendFollowup: (
|
||||
handle: string,
|
||||
followup: WorktreeStartupFollowup,
|
||||
terminal: RuntimeTerminalCreate
|
||||
) => void
|
||||
provision: (
|
||||
options: WorktreeTerminalProvisioningArgs
|
||||
) => Promise<{ setupSpawned: boolean; setupTerminalHandle: string | null }>
|
||||
activate: (
|
||||
repoId: string,
|
||||
worktreeId: string,
|
||||
startup?: WorktreeStartupLaunch,
|
||||
// Only work main tried to start and failed; the host window retries it where the user sees it.
|
||||
failedSetup?: CreateWorktreeResult['setup'],
|
||||
failedDefaultTabs?: CreateWorktreeResult['defaultTabs'],
|
||||
providesInitialSurface?: boolean
|
||||
) => void
|
||||
}
|
||||
|
||||
export type RuntimeLocalWorktreeTerminalStartupResult = {
|
||||
warning?: string
|
||||
returnedSetup?: CreateWorktreeResult['setup']
|
||||
didSpawnSetup: boolean
|
||||
didSpawnStartup: boolean
|
||||
setupTerminalHandle: string | null
|
||||
startupTerminalHandle: string | null
|
||||
startupTerminalTabId: string | null
|
||||
startupTerminalPaneKey: string | null
|
||||
startupTerminalPtyId: string | null
|
||||
}
|
||||
import type {
|
||||
RuntimeLocalWorktreeTerminalPorts,
|
||||
RuntimeLocalWorktreeTerminalStartupResult
|
||||
} from './runtime-worktree-terminal-startup-types'
|
||||
export type { RuntimeLocalWorktreeTerminalPorts } from './runtime-worktree-terminal-startup-types'
|
||||
|
||||
export async function startRuntimeLocalWorktreeTerminals(args: {
|
||||
request: Omit<RuntimeManagedWorktreeCreateArgs, 'repoSelector' | 'name'>
|
||||
@@ -73,6 +38,8 @@ export async function startRuntimeLocalWorktreeTerminals(args: {
|
||||
/** What a host-built startup was quoted for, or the repair error it fails with. */
|
||||
startupLaunchRuntime?: AgentLaunchRuntime | Error
|
||||
createdWithAgent?: TuiAgent
|
||||
observeSequencedSetupCompletion?: boolean
|
||||
guardStartupInput?: true
|
||||
promisedAgentChat?: boolean
|
||||
draftPaste?: WorktreeStartupDraftPaste
|
||||
warning?: string
|
||||
@@ -138,10 +105,14 @@ export async function startRuntimeLocalWorktreeTerminals(args: {
|
||||
})
|
||||
request.onStartupTerminalCreated?.(terminal)
|
||||
if (args.draftPaste) {
|
||||
ports.pasteDraft(terminal.handle, args.draftPaste)
|
||||
ports.pasteDraft(
|
||||
terminal.handle,
|
||||
args.draftPaste,
|
||||
args.guardStartupInput ? terminal : undefined
|
||||
)
|
||||
}
|
||||
if (args.startupFollowup) {
|
||||
ports.sendFollowup(terminal.handle, args.startupFollowup, terminal)
|
||||
ports.sendFollowup(terminal.handle, args.startupFollowup, terminal, args.guardStartupInput)
|
||||
}
|
||||
didSpawnStartup = true
|
||||
startupTerminalHandle = terminal.handle
|
||||
@@ -272,6 +243,7 @@ function provisionArgs(
|
||||
startupNeedsTerminal: args.startup !== undefined,
|
||||
setupCommandPlatform: setupPlatform(args.setup, 'posix'),
|
||||
observeSetupCompletion: args.request.observeSetupCompletion,
|
||||
observeSequencedSetupCompletion: args.observeSequencedSetupCompletion,
|
||||
...(wrappedSetupCommand ? { wrappedSetupCommand } : {})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,23 +38,29 @@ export type WorktreeStartupReadinessHost = {
|
||||
export function pasteWorktreeStartupDraftWhenReady(
|
||||
host: WorktreeStartupReadinessHost,
|
||||
handle: string,
|
||||
draft: WorktreeStartupDraftPaste
|
||||
draft: WorktreeStartupDraftPaste,
|
||||
guarded?: { beforeWrite: (ptyId: string) => Promise<void>; dispose: () => void }
|
||||
): void {
|
||||
void waitForWorktreeStartupDraft(host, handle, draft.agent)
|
||||
.then((ptyId) => {
|
||||
.then(async (ptyId) => {
|
||||
if (!ptyId) {
|
||||
console.warn('[worktree-create] agent did not become ready for draft paste')
|
||||
return
|
||||
}
|
||||
if (guarded) {
|
||||
await guarded.beforeWrite(ptyId)
|
||||
}
|
||||
host.write(ptyId, `${BRACKETED_PASTE_BEGIN}${draft.content}${BRACKETED_PASTE_END}`, 'launch')
|
||||
})
|
||||
.catch((error) => console.warn('[worktree-create] failed to paste startup draft:', error))
|
||||
.finally(() => guarded?.dispose())
|
||||
}
|
||||
|
||||
export type StartupFollowupPromptOptions = {
|
||||
signal?: AbortSignal
|
||||
agentLaunch?: boolean
|
||||
terminalCreation?: TerminalReadinessCreation
|
||||
beforeWrite?: (ptyId: string) => void
|
||||
}
|
||||
|
||||
/** A post-start agent's first prompt: its process in front can still drop typed text (#10336). */
|
||||
@@ -78,6 +84,7 @@ export async function deliverStartupFollowupPrompt(
|
||||
}
|
||||
// WSL and SSH-to-Windows cannot prove a lone shell either: keep their typed follow-up; agent.launch refused there.
|
||||
if (!options.agentLaunch && runtime.launchedAgentHostProvesShellAlone?.(ptyId) !== true) {
|
||||
options.beforeWrite?.(ptyId)
|
||||
host.write(ptyId, `${prompt}\r`, 'launch')
|
||||
return true
|
||||
}
|
||||
@@ -90,6 +97,7 @@ export async function deliverStartupFollowupPrompt(
|
||||
terminalCreation: options.terminalCreation,
|
||||
text: prompt,
|
||||
unprovableHost: 'write-if-shell-provable',
|
||||
beforeWrite: options.beforeWrite,
|
||||
...(signal ? { signal } : {})
|
||||
})
|
||||
} catch (error) {
|
||||
|
||||
@@ -60,6 +60,7 @@ export type WorktreeTerminalProvisioningArgs = {
|
||||
startupNeedsTerminal?: boolean
|
||||
setupCommandPlatform: 'windows' | 'posix'
|
||||
observeSetupCompletion?: boolean
|
||||
observeSequencedSetupCompletion?: boolean
|
||||
// Why: setup and startup must use the same wrapper when startup waits for setup.
|
||||
wrappedSetupCommand?: string
|
||||
surfaceOwner?: false
|
||||
@@ -224,18 +225,22 @@ export async function provisionWorktreeTerminals(
|
||||
}
|
||||
if (args.setup) {
|
||||
const completionToken =
|
||||
args.observeSetupCompletion && !args.wrappedSetupCommand ? randomUUID() : null
|
||||
args.observeSetupCompletion &&
|
||||
(!args.wrappedSetupCommand || args.observeSequencedSetupCompletion)
|
||||
? randomUUID()
|
||||
: null
|
||||
const observed = completionToken
|
||||
? buildObservedSetupCommand(
|
||||
args.setup.runnerScriptPath,
|
||||
args.setupCommandPlatform,
|
||||
completionToken,
|
||||
args.setup.shell
|
||||
args.setup.shell,
|
||||
args.wrappedSetupCommand
|
||||
)
|
||||
: null
|
||||
const command =
|
||||
args.wrappedSetupCommand ??
|
||||
observed?.command ??
|
||||
args.wrappedSetupCommand ??
|
||||
buildSetupRunnerCommand(
|
||||
args.setup.runnerScriptPath,
|
||||
args.setupCommandPlatform,
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { CreateWorktreeResult } from '../../../../shared/worktree/create-types'
|
||||
import type { WorktreeStartupLaunch } from '../../../../shared/worktree/launch-types'
|
||||
import type { RuntimeTerminalCreate } from '../../../../shared/runtime-terminal-create-contract'
|
||||
import type { TerminalCreateOptions } from '../../terminal/launch/terminal-create-options'
|
||||
import type {
|
||||
WorktreeStartupDraftPaste,
|
||||
WorktreeStartupFollowup
|
||||
} from './runtime-worktree-agent-startup'
|
||||
import type { WorktreeTerminalProvisioningArgs } from './runtime-worktree-terminal-provisioning'
|
||||
|
||||
export type RuntimeLocalWorktreeTerminalPorts = {
|
||||
canSpawn: boolean
|
||||
provisionInBackground?: () => boolean
|
||||
createTerminal: (
|
||||
selector: string,
|
||||
options: TerminalCreateOptions
|
||||
) => Promise<RuntimeTerminalCreate>
|
||||
pasteDraft: (
|
||||
handle: string,
|
||||
draft: WorktreeStartupDraftPaste,
|
||||
target?: RuntimeTerminalCreate
|
||||
) => void
|
||||
sendFollowup: (
|
||||
handle: string,
|
||||
followup: WorktreeStartupFollowup,
|
||||
terminal: RuntimeTerminalCreate,
|
||||
guardTarget?: true
|
||||
) => void
|
||||
provision: (
|
||||
options: WorktreeTerminalProvisioningArgs
|
||||
) => Promise<{ setupSpawned: boolean; setupTerminalHandle: string | null }>
|
||||
activate: (
|
||||
repoId: string,
|
||||
worktreeId: string,
|
||||
startup?: WorktreeStartupLaunch,
|
||||
// Only work main tried to start and failed; the host window retries it where the user sees it.
|
||||
failedSetup?: CreateWorktreeResult['setup'],
|
||||
failedDefaultTabs?: CreateWorktreeResult['defaultTabs'],
|
||||
providesInitialSurface?: boolean
|
||||
) => void
|
||||
}
|
||||
|
||||
export type RuntimeLocalWorktreeTerminalStartupResult = {
|
||||
warning?: string
|
||||
returnedSetup?: CreateWorktreeResult['setup']
|
||||
didSpawnSetup: boolean
|
||||
didSpawnStartup: boolean
|
||||
setupTerminalHandle: string | null
|
||||
startupTerminalHandle: string | null
|
||||
startupTerminalTabId: string | null
|
||||
startupTerminalPaneKey: string | null
|
||||
startupTerminalPtyId: string | null
|
||||
}
|
||||
+65
-1
@@ -89,7 +89,7 @@ it('loads owner-host settings and inserts/copies the real-repo example without o
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Use this example' }))
|
||||
await waitFor(() => expect(updateProjectGroup).toHaveBeenCalled())
|
||||
const script =
|
||||
'# Repo IDs are local to this machine; review them before sharing this script.\n# API server\norca worktree create --repo \'id:api\' --name "$ORCA_WORKSPACE_NAME" --json\n# Website\norca worktree create --repo \'id:web\' --name "$ORCA_WORKSPACE_NAME" --json'
|
||||
'# Repo IDs are local to this machine; review them before sharing this script.\n# API server\n"${ORCA_CLI_COMMAND:-orca}" worktree create --repo \'id:api\' --name "$ORCA_WORKSPACE_NAME" --json\n# Website\n"${ORCA_CLI_COMMAND:-orca}" worktree create --repo \'id:web\' --name "$ORCA_WORKSPACE_NAME" --json'
|
||||
expect(updateProjectGroup).toHaveBeenLastCalledWith(
|
||||
'services',
|
||||
{ hookSettings: { ...saved, scripts: { setup: script, archive: 'echo keep archive' } } },
|
||||
@@ -169,3 +169,67 @@ it('shows setup-only shared configuration through the group Advanced disclosure'
|
||||
view.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('preserves saved scripts while authoritative group inspection is pending', async () => {
|
||||
const group = createProjectGroup({
|
||||
name: 'Loading',
|
||||
parentPath: '/loading',
|
||||
createdFrom: 'folder-scan',
|
||||
tabOrder: 0
|
||||
})
|
||||
let inspect!: (value: Awaited<ReturnType<typeof checkRuntimeGroupHooks>>) => void
|
||||
vi.mocked(checkRuntimeGroupHooks).mockReturnValue(
|
||||
new Promise((resolve) => {
|
||||
inspect = resolve
|
||||
})
|
||||
)
|
||||
const updateProjectGroup = vi.fn(async (..._args: unknown[]) => true)
|
||||
useAppStore.setState({
|
||||
settingsSearchQuery: '',
|
||||
projectGroups: [group],
|
||||
repos: [],
|
||||
updateProjectGroup
|
||||
})
|
||||
const view = render(
|
||||
<TooltipProvider>
|
||||
<ProjectGroupHooksSection group={group} />
|
||||
</TooltipProvider>
|
||||
)
|
||||
const example = within(view.container).getByRole('button', { name: 'Use this example' })
|
||||
fireEvent.click(example)
|
||||
view.unmount()
|
||||
expect(updateProjectGroup).not.toHaveBeenCalled()
|
||||
const saved = {
|
||||
mode: 'auto' as const,
|
||||
scripts: { setup: 'echo saved', archive: 'echo preserve' },
|
||||
setupRunPolicy: 'ask' as const,
|
||||
setupAgentStartupPolicy: 'wait-for-setup' as const,
|
||||
commandSourcePolicy: 'local-only' as const
|
||||
}
|
||||
const second = render(
|
||||
<TooltipProvider>
|
||||
<ProjectGroupHooksSection group={group} />
|
||||
</TooltipProvider>
|
||||
)
|
||||
inspect({
|
||||
status: 'ok',
|
||||
hasHooks: false,
|
||||
hooks: null,
|
||||
hookSettings: saved,
|
||||
mayNeedUpdate: false,
|
||||
setupRunPolicy: 'ask',
|
||||
setupConfig: null
|
||||
})
|
||||
await waitFor(() => expect(within(second.container).getByDisplayValue('echo saved')).toBeTruthy())
|
||||
fireEvent.click(within(second.container).getByRole('button', { name: 'Use this example' }))
|
||||
await waitFor(() => expect(updateProjectGroup).toHaveBeenCalled())
|
||||
expect(updateProjectGroup.mock.calls[0]?.[1]).toEqual({
|
||||
hookSettings: {
|
||||
...saved,
|
||||
scripts: {
|
||||
setup: '# Repo IDs are local to this machine; review them before sharing this script.',
|
||||
archive: 'echo preserve'
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
+20
-15
@@ -58,20 +58,25 @@ export function ProjectGroupHooksSection({
|
||||
? projectGroupSetupExample(getFolderSourceRepos(repos, groups, group), platform)
|
||||
: undefined
|
||||
return (
|
||||
<RepositoryHooksSection
|
||||
repo={owner}
|
||||
showArchive={false}
|
||||
yamlHooks={inspection?.hooks ?? null}
|
||||
hasHooksFile={inspection?.hasHooks ?? false}
|
||||
hooksInspectionReady={inspection !== null && !inspection.unavailable}
|
||||
mayNeedUpdate={inspection?.mayNeedUpdate ?? false}
|
||||
copiedTemplate={false}
|
||||
onCopyTemplate={() => void window.api.ui.writeClipboardText(GROUP_SETUP_HOOKS_TEMPLATE)}
|
||||
setupExample={example}
|
||||
onUpdateHookSettings={(hookSettings) => {
|
||||
setInspection((current) => (current ? { ...current, hookSettings } : current))
|
||||
void useAppStore.getState().updateProjectGroup(group.id, { hookSettings }, { hostId })
|
||||
}}
|
||||
/>
|
||||
<fieldset disabled={!inspection || Boolean(inspection.unavailable)} className="min-w-0">
|
||||
<RepositoryHooksSection
|
||||
repo={owner}
|
||||
showArchive={false}
|
||||
yamlHooks={inspection?.hooks ?? null}
|
||||
hasHooksFile={inspection?.hasHooks ?? false}
|
||||
hooksInspectionReady={inspection !== null && !inspection.unavailable}
|
||||
mayNeedUpdate={inspection?.mayNeedUpdate ?? false}
|
||||
copiedTemplate={false}
|
||||
onCopyTemplate={() => void window.api.ui.writeClipboardText(GROUP_SETUP_HOOKS_TEMPLATE)}
|
||||
setupExample={example}
|
||||
onUpdateHookSettings={(hookSettings) => {
|
||||
if (!inspection || inspection.unavailable) {
|
||||
return
|
||||
}
|
||||
setInspection((current) => (current ? { ...current, hookSettings } : current))
|
||||
void useAppStore.getState().updateProjectGroup(group.id, { hookSettings }, { hostId })
|
||||
}}
|
||||
/>
|
||||
</fieldset>
|
||||
)
|
||||
}
|
||||
|
||||
+168
-1
@@ -1,15 +1,30 @@
|
||||
// @vitest-environment happy-dom
|
||||
// oxlint-disable-next-line typescript/triple-slash-reference -- The cross-process composition imports main runtime types whose build constants are ambient globals, not a module.
|
||||
/// <reference path="../../../../../../types/build-constants.d.ts" />
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { makeProjectGroup, makeFolderWorkspace } from './folder-workspace-composer-submit-fixtures'
|
||||
|
||||
const mocks = vi.hoisted(() => ({ activateAndRevealFolderWorkspace: vi.fn() }))
|
||||
const mocks = vi.hoisted(() => ({ activateAndRevealFolderWorkspace: vi.fn(), seedDraft: vi.fn() }))
|
||||
|
||||
vi.mock('@/lib/workspace/activation/worktree-activation', async (importOriginal) => {
|
||||
const actual = await importOriginal<Record<string, unknown>>()
|
||||
return { ...actual, activateAndRevealFolderWorkspace: mocks.activateAndRevealFolderWorkspace }
|
||||
})
|
||||
|
||||
vi.mock(
|
||||
'@/lib/agent-session/launch/prompt/agent-launch-prompt-delivery',
|
||||
async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
seedNativeChatLaunchDraftForAgentTab: mocks.seedDraft
|
||||
})
|
||||
)
|
||||
vi.mock('electron', () => ({ app: { getPath: () => '/tmp' } }))
|
||||
|
||||
import { getDefaultSettings } from '../../../../../../shared/constants'
|
||||
import { FolderWorkspaceCreate } from '../../../../../../shared/rpc-contract/folder-workspace-params'
|
||||
import { FolderWorkspaceCreateArgs } from '../../../../../../main/ipc/repos/repo-ipc-arg-schemas'
|
||||
import { prepareGroupFolderCreation } from '../../../../../../main/runtime/workspaces/creation/runtime-group-folder-setup'
|
||||
import { useAppStore } from '@/store/index'
|
||||
import { submitFolderWorkspaceCreate } from './folder-workspace-composer-submit'
|
||||
import { getFolderWorkspaceAgentLaunchFact } from './folder-workspace-agent-startup'
|
||||
@@ -177,3 +192,155 @@ describe('submitFolderWorkspaceCreate on an Orca server', () => {
|
||||
expect(createFolderWorkspace).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ agent: 'codex', delivery: 'draft' },
|
||||
{ agent: 'claude', delivery: null },
|
||||
{ agent: 'autohand', delivery: 'auto-submit' }
|
||||
] as const)(
|
||||
'preserves the actual paired $agent delivery through schemas and the host starter ($delivery)',
|
||||
async ({ agent, delivery }) => {
|
||||
mocks.activateAndRevealFolderWorkspace.mockReturnValue({ primaryTabId: 'setup-tab' })
|
||||
mocks.seedDraft.mockClear()
|
||||
const projectGroup = { ...makeProjectGroup(), executionHostId: 'runtime:paired' as const }
|
||||
useAppStore.setState({
|
||||
runtimeStatusByEnvironmentId: new Map([
|
||||
[
|
||||
'paired',
|
||||
{
|
||||
checkedAt: 1,
|
||||
status: {
|
||||
runtimeId: 'rt',
|
||||
rendererGraphEpoch: 0,
|
||||
graphStatus: 'ready',
|
||||
authoritativeWindowId: null,
|
||||
liveTabCount: 0,
|
||||
liveLeafCount: 0,
|
||||
hostPlatform: 'linux'
|
||||
}
|
||||
}
|
||||
]
|
||||
])
|
||||
})
|
||||
const pasteDraft = vi.fn()
|
||||
const sendFollowup = vi.fn()
|
||||
const buildStartup = vi.fn()
|
||||
const createFolderWorkspace = vi.fn(
|
||||
async (input: Parameters<typeof FolderWorkspaceCreate.parse>[0]) => {
|
||||
const parsed = FolderWorkspaceCreateArgs.parse(FolderWorkspaceCreate.parse(input))
|
||||
expect(parsed.startupCommand).toContain(`custom-${agent} --color never`)
|
||||
expect(parsed.startupPromptDelivery).toBe(delivery ?? undefined)
|
||||
if (delivery === 'draft') {
|
||||
expect(parsed.startupPrompt).toContain('https://linear.app/team/issue/STA-1')
|
||||
} else if (delivery === 'auto-submit') {
|
||||
expect(parsed.startupPrompt).toBe('Inspect regular task')
|
||||
} else {
|
||||
expect(parsed.startupPrompt).toBeUndefined()
|
||||
}
|
||||
return prepareGroupFolderCreation({
|
||||
input: parsed,
|
||||
group: { ...projectGroup, executionHostId: undefined },
|
||||
workspace: makeFolderWorkspace(),
|
||||
settings: getDefaultSettings('/tmp'),
|
||||
buildStartup,
|
||||
wait: async () => ({ exitCode: 0 }),
|
||||
ports: {
|
||||
canSpawn: true,
|
||||
createTerminal: async () => ({
|
||||
handle: 'agent',
|
||||
tabId: 'returned-agent-tab',
|
||||
ptyId: 'agent-pty',
|
||||
worktreeId: 'folder:folder-workspace-1',
|
||||
title: 'Codex'
|
||||
}),
|
||||
pasteDraft,
|
||||
sendFollowup,
|
||||
provision: async () => ({ setupSpawned: false, setupTerminalHandle: null }),
|
||||
activate: vi.fn()
|
||||
}
|
||||
})
|
||||
}
|
||||
)
|
||||
await submitFolderWorkspaceCreate({
|
||||
projectGroup,
|
||||
setupSupported: true,
|
||||
setupApproval: { setupDecision: 'skip' },
|
||||
runtimeEnvironmentId: 'paired',
|
||||
name: 'Linked task',
|
||||
lastAutoName: '',
|
||||
linkedWorkItem:
|
||||
delivery === 'auto-submit'
|
||||
? null
|
||||
: {
|
||||
provider: 'linear',
|
||||
type: 'issue',
|
||||
number: 1,
|
||||
title: 'Inspect task',
|
||||
url: 'https://linear.app/team/issue/STA-1'
|
||||
},
|
||||
note: delivery === 'auto-submit' ? 'Inspect regular task' : '',
|
||||
autoRenameBranchFromWork: false,
|
||||
quickAgent: agent,
|
||||
agentCmdOverrides: { [agent]: `custom-${agent} --color never` },
|
||||
createFolderWorkspace,
|
||||
onOpenChange: vi.fn()
|
||||
})
|
||||
expect(buildStartup).not.toHaveBeenCalled()
|
||||
if (delivery === 'draft') {
|
||||
expect(pasteDraft).toHaveBeenCalledOnce()
|
||||
expect(pasteDraft.mock.calls[0]?.[1]).toMatchObject({
|
||||
agent: 'codex',
|
||||
content: expect.stringContaining('https://linear.app/team/issue/STA-1')
|
||||
})
|
||||
expect(sendFollowup).not.toHaveBeenCalled()
|
||||
} else if (delivery === 'auto-submit') {
|
||||
expect(pasteDraft).not.toHaveBeenCalled()
|
||||
expect(sendFollowup).toHaveBeenCalledExactlyOnceWith(
|
||||
'agent',
|
||||
{ agent: 'autohand', prompt: 'Inspect regular task' },
|
||||
expect.objectContaining({ tabId: 'returned-agent-tab' }),
|
||||
true
|
||||
)
|
||||
} else {
|
||||
expect(pasteDraft).not.toHaveBeenCalled()
|
||||
expect(sendFollowup).not.toHaveBeenCalled()
|
||||
}
|
||||
if (delivery !== 'auto-submit') {
|
||||
expect(mocks.seedDraft).toHaveBeenCalledExactlyOnceWith({
|
||||
tabId: 'returned-agent-tab',
|
||||
agent,
|
||||
text: expect.stringContaining('https://linear.app/team/issue/STA-1')
|
||||
})
|
||||
} else {
|
||||
expect(mocks.seedDraft).not.toHaveBeenCalled()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it('rejects incomplete explicit delivery on IPC and RPC but preserves old captured-command forms', () => {
|
||||
for (const schema of [FolderWorkspaceCreate, FolderWorkspaceCreateArgs]) {
|
||||
expect(
|
||||
schema.safeParse({
|
||||
projectGroupId: 'group',
|
||||
startupCommand: 'codex',
|
||||
startupAgent: 'codex',
|
||||
startupPromptDelivery: 'draft'
|
||||
}).success
|
||||
).toBe(false)
|
||||
expect(
|
||||
schema.safeParse({
|
||||
projectGroupId: 'group',
|
||||
startupAgent: 'codex',
|
||||
startupPrompt: 'task',
|
||||
startupPromptDelivery: 'draft'
|
||||
}).success
|
||||
).toBe(false)
|
||||
expect(
|
||||
schema.safeParse({
|
||||
projectGroupId: 'group',
|
||||
startupCommand: 'codex',
|
||||
startupPrompt: 'legacy'
|
||||
}).success
|
||||
).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
+18
-18
@@ -1,10 +1,12 @@
|
||||
import { showFolderWorkspaceSetupOutcome } from './folder-workspace-setup-feedback'
|
||||
import { buildFolderWorkspaceStartupPayload } from './folder-workspace-startup-payload'
|
||||
import {
|
||||
buildFolderWorkspaceStartupPayload,
|
||||
buildFolderWorkspaceHostStartupPayload
|
||||
} from './folder-workspace-startup-payload'
|
||||
import { reviewSetupTrustMismatch } from '@/store/slices/worktrees/create/created-worktree-setup-trust'
|
||||
import { projectGroupHookTrustKey } from '../../../../../../shared/workspace-hook-owner'
|
||||
import { folderWorkspaceToWorktree } from '../../../../../../shared/folder-workspaces/folder-workspace-worktree'
|
||||
import { ensureAgentLaunchPreferences } from '@/runtime/agent-launch-settings/use-host-agent-launch-preferences'
|
||||
import { toAgentLaunchPreferences } from '../../../../../../shared/agent-launch/choices/agent-launch-preferences'
|
||||
import { resolveAgentStartupPlanInputs } from '../../../../../../shared/agent-launch/startup/agent-startup-plan-inputs'
|
||||
import { ensureAgentStartupInTerminal } from '@/lib/workspace/creation/new-workspace'
|
||||
import { seedNativeChatLaunchDraftForAgentTab } from '@/lib/agent-session/launch/prompt/agent-launch-prompt-delivery'
|
||||
@@ -187,18 +189,13 @@ export async function submitFolderWorkspaceCreate({
|
||||
...(setupSupported && structuredLaunch ? { agentLaunchMode: 'structured' as const } : {}),
|
||||
...(hostStartsTerminal && startupPlan
|
||||
? {
|
||||
startupCommand: startupPlan.launchCommand,
|
||||
startupEnv: startupPlan.env,
|
||||
startupLaunchConfig: startupPlan.launchConfig,
|
||||
startupCommandDelivery: startupPlan.startupCommandDelivery,
|
||||
startupAgent: quickAgent ?? undefined,
|
||||
startupPrompt: launchDraftPrompt ?? note,
|
||||
startupAgentArgs: agentArgs,
|
||||
startupSessionOptions: sessionOptions,
|
||||
startupLaunchPreferences: quickAgent
|
||||
? toAgentLaunchPreferences(sessionOptions, quickAgent)
|
||||
: undefined,
|
||||
launchSource
|
||||
...buildFolderWorkspaceHostStartupPayload({
|
||||
startupPlan,
|
||||
quickAgent,
|
||||
agentArgs,
|
||||
sessionOptions,
|
||||
launchSource
|
||||
})
|
||||
}
|
||||
: {}),
|
||||
projectGroupId: projectGroup.id,
|
||||
@@ -266,19 +263,22 @@ export async function submitFolderWorkspaceCreate({
|
||||
revealWorkspace()
|
||||
}
|
||||
const activation = activationHolder.value
|
||||
const draftTabId = hostStartsTerminal
|
||||
? result.startupTerminal?.tabId
|
||||
: activation !== false
|
||||
? activation.primaryTabId
|
||||
: undefined
|
||||
if (
|
||||
!launchFailed &&
|
||||
!hostStartsTerminal &&
|
||||
!structuredLaunch &&
|
||||
quickAgent &&
|
||||
startupPlan &&
|
||||
launchDraftPrompt &&
|
||||
activation !== false &&
|
||||
activation.primaryTabId
|
||||
draftTabId
|
||||
) {
|
||||
// TUI prefill needs a separate chat-composer copy to remain visible after switching views.
|
||||
seedNativeChatLaunchDraftForAgentTab({
|
||||
tabId: activation.primaryTabId,
|
||||
tabId: draftTabId,
|
||||
agent: quickAgent,
|
||||
text: launchDraftPrompt
|
||||
})
|
||||
|
||||
+35
@@ -1,3 +1,5 @@
|
||||
import { toAgentLaunchPreferences } from '../../../../../../shared/agent-launch/choices/agent-launch-preferences'
|
||||
import type { FolderWorkspaceCreateInput } from '../../../../../../shared/folder-workspaces/folder-workspace-create'
|
||||
import type { SubmitFolderWorkspaceCreateParams } from './folder-workspace-composer-submit-input'
|
||||
import type { buildAgentStartupPlan } from '../../../../../../shared/agent-launch/startup/tui-agent-startup'
|
||||
import { tuiAgentToAgentKind } from '../../../../../../shared/agent-kind'
|
||||
@@ -53,3 +55,36 @@ export function buildFolderWorkspaceStartupPayload({
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
|
||||
export function buildFolderWorkspaceHostStartupPayload({
|
||||
startupPlan,
|
||||
quickAgent,
|
||||
agentArgs,
|
||||
sessionOptions,
|
||||
launchSource
|
||||
}: Pick<SubmitFolderWorkspaceCreateParams, 'quickAgent' | 'agentArgs' | 'sessionOptions'> & {
|
||||
startupPlan: NonNullable<ReturnType<typeof buildAgentStartupPlan>>
|
||||
launchSource: NonNullable<SubmitFolderWorkspaceCreateParams['launchSource']>
|
||||
}): Partial<FolderWorkspaceCreateInput> {
|
||||
return {
|
||||
startupCommand: startupPlan.launchCommand,
|
||||
startupEnv: startupPlan.env,
|
||||
startupLaunchConfig: startupPlan.launchConfig,
|
||||
startupCommandDelivery: startupPlan.startupCommandDelivery,
|
||||
startupAgent: quickAgent ?? undefined,
|
||||
...(startupPlan.draftPrompt
|
||||
? { startupPrompt: startupPlan.draftPrompt, startupPromptDelivery: 'draft' as const }
|
||||
: startupPlan.followupPrompt
|
||||
? {
|
||||
startupPrompt: startupPlan.followupPrompt,
|
||||
startupPromptDelivery: 'auto-submit' as const
|
||||
}
|
||||
: {}),
|
||||
startupAgentArgs: agentArgs,
|
||||
startupSessionOptions: sessionOptions,
|
||||
startupLaunchPreferences: quickAgent
|
||||
? toAgentLaunchPreferences(sessionOptions, quickAgent)
|
||||
: undefined,
|
||||
launchSource
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,6 +110,13 @@ export function useFolderSubmitOrchestration(input: FolderSubmitOrchestrationInp
|
||||
if (isSubmissionCancelled()) {
|
||||
return
|
||||
}
|
||||
const policySettlement = await settleComposerSubmit(
|
||||
groupSetup.waitForStartupPolicySave(),
|
||||
isSubmissionCancelled
|
||||
)
|
||||
if (policySettlement.status === 'cancelled' || !policySettlement.value) {
|
||||
return
|
||||
}
|
||||
const owner = projectGroupHookOwner(selectedProjectGroup)
|
||||
const setupSupported = await resolveFolderSetupSupported(
|
||||
owner,
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { beforeEach, expect, it, vi } from 'vitest'
|
||||
import { createProjectGroup } from '../../../../shared/project-groups'
|
||||
import { getDefaultRepoHookSettings } from '../../../../shared/constants'
|
||||
import '../../components/settings/__fixtures__/settings-persistence-test-fixture'
|
||||
import { useAppStore } from '@/store'
|
||||
import { checkRuntimeGroupHooks } from '@/runtime/repo-hooks/runtime-hooks-client'
|
||||
import { useProjectGroupSetup } from './use-project-group-setup'
|
||||
import { useFolderSubmitOrchestration } from './folder-submit-orchestration'
|
||||
import { submitFolderWorkspaceCreate } from '@/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
vi.mock('@/lib/workspace/creation/setup/folder-setup-support', () => ({
|
||||
useFolderSetupSupport: () => 'supported',
|
||||
resolveFolderSetupSupported: async () => true
|
||||
}))
|
||||
vi.mock('@/runtime/repo-hooks/runtime-hooks-client', () => ({ checkRuntimeGroupHooks: vi.fn() }))
|
||||
vi.mock('@/lib/workspace/creation/setup/workspace-setup-trust', () => ({
|
||||
confirmWorkspaceSetupDecision: async () => ({ setupDecision: 'skip' })
|
||||
}))
|
||||
vi.mock('@/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit', () => ({
|
||||
submitFolderWorkspaceCreate: vi.fn(async () => true)
|
||||
}))
|
||||
vi.mock('sonner', () => ({ toast: { error: vi.fn() } }))
|
||||
const group = {
|
||||
...createProjectGroup({
|
||||
name: 'Services',
|
||||
parentPath: '/services',
|
||||
createdFrom: 'folder-scan',
|
||||
tabOrder: 0
|
||||
}),
|
||||
id: 'services'
|
||||
}
|
||||
const saved = {
|
||||
...getDefaultRepoHookSettings(),
|
||||
scripts: { setup: 'echo retained', archive: '' },
|
||||
setupAgentStartupPolicy: 'start-immediately' as const
|
||||
}
|
||||
const inspected = {
|
||||
status: 'ok' as const,
|
||||
hasHooks: false,
|
||||
hooks: null,
|
||||
hookSettings: saved,
|
||||
mayNeedUpdate: false,
|
||||
setupRunPolicy: 'run-by-default' as const,
|
||||
setupConfig: null
|
||||
}
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(checkRuntimeGroupHooks).mockResolvedValue(inspected)
|
||||
})
|
||||
|
||||
function useSubmission(selected: typeof group) {
|
||||
const groupSetup = useProjectGroupSetup(selected)
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the folder submission path runs; unrelated composer fields are not read.
|
||||
const submit = useFolderSubmitOrchestration({
|
||||
groupSetup,
|
||||
selectedProjectGroup: selected,
|
||||
folderCreateDisabled: false,
|
||||
folderSourceRepos: [],
|
||||
disabledTuiAgents: [],
|
||||
isSubmissionCancelled: () => false,
|
||||
decisions: { canResolveFolderSmartGitHubSubmit: () => false },
|
||||
setCreateError: vi.fn(),
|
||||
setCreating: vi.fn(),
|
||||
revealSetupChoice: vi.fn(),
|
||||
lastAutoNameRef: { current: '' },
|
||||
name: 'task',
|
||||
note: '',
|
||||
linkedWorkItem: null,
|
||||
settings: null,
|
||||
folderTargetRuntimeEnvironmentId: null,
|
||||
folderTargetIsRemote: false,
|
||||
createFolderWorkspace: vi.fn(),
|
||||
onCreated: vi.fn(),
|
||||
taskSourceContext: null,
|
||||
resolvePendingSmartGitHubSubmit: vi.fn(),
|
||||
telemetrySource: 'sidebar',
|
||||
clearNewWorkspaceDraft: vi.fn(),
|
||||
persistDraft: false
|
||||
} as unknown as Parameters<typeof useFolderSubmitOrchestration>[0])
|
||||
return { groupSetup, ...submit }
|
||||
}
|
||||
|
||||
it.each([true, false])(
|
||||
'settles a held policy save before group inspection/create (save=%s)',
|
||||
async (success) => {
|
||||
let finish!: (saved: boolean) => void
|
||||
const updateProjectGroup = vi.fn(
|
||||
() =>
|
||||
new Promise<boolean>((resolve) => {
|
||||
finish = resolve
|
||||
})
|
||||
)
|
||||
useAppStore.setState({ projectGroups: [group], updateProjectGroup })
|
||||
const hook = renderHook(() => {
|
||||
return useSubmission(group)
|
||||
})
|
||||
await waitFor(() => expect(hook.result.current.groupSetup.shouldWaitForSetupCheck).toBe(false))
|
||||
await waitFor(() => expect(checkRuntimeGroupHooks).toHaveBeenCalledOnce())
|
||||
await act(async () => {
|
||||
hook.result.current.groupSetup.setStartupPolicy('wait-for-setup')
|
||||
})
|
||||
await waitFor(() => expect(updateProjectGroup).toHaveBeenCalledOnce())
|
||||
let submitting!: Promise<void>
|
||||
act(() => {
|
||||
submitting = hook.result.current.submitFolderTarget(null)
|
||||
})
|
||||
await Promise.resolve()
|
||||
expect(submitFolderWorkspaceCreate).not.toHaveBeenCalled()
|
||||
expect(checkRuntimeGroupHooks).toHaveBeenCalledOnce()
|
||||
await act(async () => {
|
||||
finish(success)
|
||||
await submitting
|
||||
})
|
||||
if (success) {
|
||||
expect(submitFolderWorkspaceCreate).toHaveBeenCalledOnce()
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
} else {
|
||||
expect(submitFolderWorkspaceCreate).not.toHaveBeenCalled()
|
||||
expect(toast.error).toHaveBeenCalledOnce()
|
||||
expect(hook.result.current.groupSetup.startupPolicy).toBe('start-immediately')
|
||||
}
|
||||
hook.unmount()
|
||||
}
|
||||
)
|
||||
|
||||
it('does not roll an old owner failure over a newer owner policy selection', async () => {
|
||||
const second = { ...group, id: 'second', parentPath: '/second' }
|
||||
let finishFirst!: (value: boolean) => void
|
||||
let finishSecond!: (value: boolean) => void
|
||||
const updateProjectGroup = vi.fn(
|
||||
(groupId: string) =>
|
||||
new Promise<boolean>((resolve) => {
|
||||
if (groupId === group.id) {
|
||||
finishFirst = resolve
|
||||
} else {
|
||||
finishSecond = resolve
|
||||
}
|
||||
})
|
||||
)
|
||||
useAppStore.setState({ projectGroups: [group, second], updateProjectGroup })
|
||||
const hook = renderHook(({ selected }) => useProjectGroupSetup(selected), {
|
||||
initialProps: { selected: group }
|
||||
})
|
||||
await waitFor(() => expect(hook.result.current.shouldWaitForSetupCheck).toBe(false))
|
||||
await act(async () => {
|
||||
hook.result.current.setStartupPolicy('wait-for-setup')
|
||||
})
|
||||
let oldSettlement!: Promise<boolean>
|
||||
act(() => {
|
||||
oldSettlement = hook.result.current.waitForStartupPolicySave()
|
||||
})
|
||||
hook.rerender({ selected: second })
|
||||
await waitFor(() => expect(hook.result.current.shouldWaitForSetupCheck).toBe(false))
|
||||
await act(async () => {
|
||||
hook.result.current.setStartupPolicy('wait-for-setup')
|
||||
})
|
||||
await act(async () => {
|
||||
finishFirst(false)
|
||||
expect(await oldSettlement).toBe(false)
|
||||
})
|
||||
expect(hook.result.current.startupPolicy).toBe('wait-for-setup')
|
||||
await act(async () => {
|
||||
finishSecond(true)
|
||||
expect(await hook.result.current.waitForStartupPolicySave()).toBe(true)
|
||||
})
|
||||
expect(hook.result.current.startupPolicy).toBe('wait-for-setup')
|
||||
hook.unmount()
|
||||
})
|
||||
|
||||
it.each([true, false])(
|
||||
'retains a held owner save across A→B(save)→A (save=%s)',
|
||||
async (success) => {
|
||||
const second = { ...group, id: 'second', parentPath: '/second' }
|
||||
let finishFirst!: (value: boolean) => void
|
||||
const updateProjectGroup = vi.fn((groupId: string) =>
|
||||
groupId === group.id
|
||||
? new Promise<boolean>((resolve) => {
|
||||
finishFirst = resolve
|
||||
})
|
||||
: Promise.resolve(true)
|
||||
)
|
||||
useAppStore.setState({ projectGroups: [group, second], updateProjectGroup })
|
||||
const hook = renderHook(({ selected }) => useSubmission(selected), {
|
||||
initialProps: { selected: group }
|
||||
})
|
||||
await waitFor(() => expect(hook.result.current.groupSetup.shouldWaitForSetupCheck).toBe(false))
|
||||
await act(async () => {
|
||||
hook.result.current.groupSetup.setStartupPolicy('wait-for-setup')
|
||||
})
|
||||
hook.rerender({ selected: second })
|
||||
await waitFor(() => expect(hook.result.current.groupSetup.shouldWaitForSetupCheck).toBe(false))
|
||||
await act(async () => {
|
||||
hook.result.current.groupSetup.setStartupPolicy('wait-for-setup')
|
||||
expect(await hook.result.current.groupSetup.waitForStartupPolicySave()).toBe(true)
|
||||
})
|
||||
hook.rerender({ selected: group })
|
||||
await waitFor(() => expect(hook.result.current.groupSetup.shouldWaitForSetupCheck).toBe(false))
|
||||
const inspectionsBeforeSubmit = vi.mocked(checkRuntimeGroupHooks).mock.calls.length
|
||||
let submitting!: Promise<void>
|
||||
act(() => {
|
||||
submitting = hook.result.current.submitFolderTarget(null)
|
||||
})
|
||||
await Promise.resolve()
|
||||
expect(submitFolderWorkspaceCreate).not.toHaveBeenCalled()
|
||||
expect(checkRuntimeGroupHooks).toHaveBeenCalledTimes(inspectionsBeforeSubmit)
|
||||
await act(async () => {
|
||||
finishFirst(success)
|
||||
await submitting
|
||||
})
|
||||
if (success) {
|
||||
expect(submitFolderWorkspaceCreate).toHaveBeenCalledOnce()
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
} else {
|
||||
expect(submitFolderWorkspaceCreate).not.toHaveBeenCalled()
|
||||
expect(toast.error).toHaveBeenCalledOnce()
|
||||
}
|
||||
hook.unmount()
|
||||
}
|
||||
)
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState, type Dispatch, type SetStateAction } from 'react'
|
||||
import { useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react'
|
||||
import type { ProjectGroup } from '../../../../shared/project-group-types'
|
||||
import type { GroupHookCheckResult } from '../../../../shared/project-group-hooks'
|
||||
import type { SetupAgentStartupPolicy } from '../../../../shared/orca-yaml-hook-types'
|
||||
@@ -10,12 +10,23 @@ import { useFolderSetupSupport } from '@/lib/workspace/creation/setup/folder-set
|
||||
import { deriveWorkspaceSetupState } from '@/lib/workspace/creation/setup/workspace-setup-preparation'
|
||||
import { checkRuntimeGroupHooks } from '@/runtime/repo-hooks/runtime-hooks-client'
|
||||
import { useAppStore } from '@/store'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { buildSetupAgentStartupHookSettings } from './setup-policy-decisions'
|
||||
|
||||
export function useProjectGroupSetup(group: ProjectGroup | null | undefined) {
|
||||
const t = useTranslate()
|
||||
const owner = group ? projectGroupHookOwner(group) : null
|
||||
const support = useFolderSetupSupport(owner, PROJECT_GROUP_FOLDER_SETUP_RUNTIME_CAPABILITY)
|
||||
const context = owner?.id ?? null
|
||||
const selectedContext = useRef(context)
|
||||
useEffect(() => {
|
||||
selectedContext.current = context
|
||||
return () => {
|
||||
selectedContext.current = null
|
||||
}
|
||||
}, [context])
|
||||
const policySaves = useRef(new Map<string, Promise<boolean>>())
|
||||
const [inspection, setInspection] = useState<{
|
||||
context: string
|
||||
result: GroupHookCheckResult
|
||||
@@ -78,9 +89,25 @@ export function useProjectGroupSetup(group: ProjectGroup | null | undefined) {
|
||||
},
|
||||
decision,
|
||||
setDecision,
|
||||
waitForStartupPolicySave: async (): Promise<boolean> => {
|
||||
if (!context || selectedContext.current !== context) {
|
||||
return false
|
||||
}
|
||||
let pending = policySaves.current.get(context)
|
||||
while (pending) {
|
||||
if (!(await pending) || selectedContext.current !== context) {
|
||||
return false
|
||||
}
|
||||
if (policySaves.current.get(context) === pending) {
|
||||
break
|
||||
}
|
||||
pending = policySaves.current.get(context)
|
||||
}
|
||||
return selectedContext.current === context
|
||||
},
|
||||
startupPolicy: inspectedGroup?.hookSettings?.setupAgentStartupPolicy ?? 'start-immediately',
|
||||
setStartupPolicy: (policy: SetupAgentStartupPolicy) => {
|
||||
if (group && hostId) {
|
||||
if (group && hostId && context && ready) {
|
||||
const hookSettings = buildSetupAgentStartupHookSettings(
|
||||
inspectedGroup?.hookSettings,
|
||||
policy
|
||||
@@ -90,7 +117,44 @@ export function useProjectGroupSetup(group: ProjectGroup | null | undefined) {
|
||||
? { ...current, result: { ...current.result, hookSettings } }
|
||||
: current
|
||||
)
|
||||
void useAppStore.getState().updateProjectGroup(group.id, { hookSettings }, { hostId })
|
||||
const previous = policySaves.current.get(context)
|
||||
const promise: Promise<boolean> = Promise.resolve(previous)
|
||||
.then(async () => {
|
||||
const saved = await useAppStore
|
||||
.getState()
|
||||
.updateProjectGroup(group.id, { hookSettings }, { hostId })
|
||||
.catch(() => false)
|
||||
if (!saved) {
|
||||
const latest = await checkRuntimeGroupHooks(hostId, group.id, {
|
||||
background: true
|
||||
}).catch(() => null)
|
||||
if (
|
||||
policySaves.current.get(context) === promise &&
|
||||
selectedContext.current === context
|
||||
) {
|
||||
setInspection((current) =>
|
||||
current?.context === context && current.result.hookSettings === hookSettings
|
||||
? latest && !latest.unavailable
|
||||
? { context, result: latest }
|
||||
: null
|
||||
: current
|
||||
)
|
||||
}
|
||||
toast.error(
|
||||
t(
|
||||
'auto.hooks.useComposerState.setupAgentStartupPolicySaveFailed',
|
||||
'Failed to save setup startup behavior.'
|
||||
)
|
||||
)
|
||||
}
|
||||
return saved
|
||||
})
|
||||
.finally(() => {
|
||||
if (policySaves.current.get(context) === promise) {
|
||||
policySaves.current.delete(context)
|
||||
}
|
||||
})
|
||||
policySaves.current.set(context, promise)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
import { createNonSecureContextUuid } from '../../non-secure-context-uuid'
|
||||
import { quotePowerShellLiteral } from '../../powershell-native-argument'
|
||||
|
||||
const DEFAULT_WAIT_TIMEOUT_SECONDS = 2 * 60 * 60
|
||||
export const SETUP_AGENT_WAIT_TIMEOUT_SECONDS = 2 * 60 * 60
|
||||
export const SETUP_COMPLETE_MESSAGE = 'Setup finished; starting agent.'
|
||||
export const SETUP_AGENT_SEQUENCE_STARTUP_COMMAND_ENV = 'ORCA_SEQUENCED_STARTUP_COMMAND'
|
||||
export const SETUP_AGENT_SEQUENCE_STARTUP_SCRIPT_ENV = 'ORCA_SEQUENCED_STARTUP_SCRIPT'
|
||||
@@ -54,7 +54,7 @@ export function createSequencedSetupAgentCommands(args: {
|
||||
: resolution.runnerScriptPathForShell
|
||||
// Use distinct markers for overlapping launches of one setup runner.
|
||||
const markerPath = `${markerBasePath}.${nonce}.done`
|
||||
const waitTimeoutSeconds = args.waitTimeoutSeconds ?? DEFAULT_WAIT_TIMEOUT_SECONDS
|
||||
const waitTimeoutSeconds = args.waitTimeoutSeconds ?? SETUP_AGENT_WAIT_TIMEOUT_SECONDS
|
||||
|
||||
if (resolution.shell === 'windows' && !posixGateForWindowsRunner) {
|
||||
return {
|
||||
|
||||
@@ -21,6 +21,7 @@ export type FolderWorkspaceCreateInput = {
|
||||
startupCommandDelivery?: WorktreeStartupLaunch['startupCommandDelivery']
|
||||
startupAgent?: TuiAgent
|
||||
startupPrompt?: string
|
||||
startupPromptDelivery?: 'draft' | 'auto-submit'
|
||||
startupAgentArgs?: string | null
|
||||
startupSessionOptions?: Record<string, string>
|
||||
startupLaunchPreferences?: AgentLaunchPreferences
|
||||
|
||||
@@ -8,12 +8,13 @@ export function projectGroupSetupExample(
|
||||
const windows = platform === 'win32'
|
||||
const comment = windows ? 'REM' : '#'
|
||||
const shell = windows ? 'cmd' : 'posix'
|
||||
const command = windows ? 'orca' : '"${ORCA_CLI_COMMAND:-orca}"'
|
||||
const workspaceName = windows ? '"%ORCA_WORKSPACE_NAME%"' : '"$ORCA_WORKSPACE_NAME"'
|
||||
return [
|
||||
`${comment} Repo IDs are local to this machine; review them before sharing this script.`,
|
||||
...repos.flatMap((repo) => [
|
||||
`${comment} ${repo.displayName.replace(windows ? /[^\p{L}\p{N} ._/-]/gu : /[\r\n]/g, ' ')}`,
|
||||
`orca worktree create --repo ${quoteStartupArg(`id:${repo.id}`, shell)} --name ${workspaceName} --json`
|
||||
`${command} worktree create --repo ${quoteStartupArg(`id:${repo.id}`, shell)} --name ${workspaceName} --json`
|
||||
])
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
@@ -22,12 +22,33 @@ export const FolderWorkspaceHookCreateShape = {
|
||||
startupCommandDelivery: z.enum(['fast', 'shell-ready']).optional(),
|
||||
startupAgent: z.string().refine(isTuiAgent).optional(),
|
||||
startupPrompt: OptionalString,
|
||||
startupPromptDelivery: z.enum(['draft', 'auto-submit']).optional(),
|
||||
startupAgentArgs: AgentArgs.optional(),
|
||||
startupSessionOptions: z.record(z.string(), z.string()).optional(),
|
||||
startupLaunchPreferences: LaunchPreferences.optional(),
|
||||
launchSource: LaunchSourceParam.optional()
|
||||
}
|
||||
|
||||
export function assertFolderWorkspaceStartupDelivery(
|
||||
value: {
|
||||
startupPromptDelivery?: string
|
||||
startupCommand?: string
|
||||
startupAgent?: string
|
||||
startupPrompt?: string
|
||||
},
|
||||
ctx: z.RefinementCtx
|
||||
): void {
|
||||
if (
|
||||
value.startupPromptDelivery &&
|
||||
(!value.startupCommand?.trim() || !value.startupAgent || !value.startupPrompt?.trim())
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'Startup prompt delivery requires a command, agent and text'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export const FolderWorkspaceLinkedTask = WorkspaceLinkedItemSchema.nullable()
|
||||
|
||||
export function assertLinkedTaskSourceContextMatch(
|
||||
@@ -64,6 +85,7 @@ export const FolderWorkspaceCreate = z
|
||||
pendingFirstAgentMessageRename: z.boolean().optional()
|
||||
})
|
||||
.superRefine(assertLinkedTaskSourceContextMatch)
|
||||
.superRefine(assertFolderWorkspaceStartupDelivery)
|
||||
|
||||
// Hosts advertising the unique-id mutation capability refuse a shared folder id when this is set.
|
||||
const RequireUniqueId = z.boolean().optional()
|
||||
|
||||
Reference in New Issue
Block a user