Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions src/main/runtime/agent-launch-settings-rollback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,19 @@ export function agentLaunchSettingsRollbackUpdates(
current: AgentLaunchSettingsSource,
updates: AgentLaunchSettingsSource
): AgentLaunchSettingsSource {
// A newer default choice supersedes both fields, including None → Blank with the same agent.
const defaultUnchanged =
Object.is(current.defaultTuiAgent, applied.defaultTuiAgent) &&
(!Object.hasOwn(updates, 'newWorkspaceSetupOnly') ||
Object.is(current.newWorkspaceSetupOnly, applied.newWorkspaceSetupOnly))
// A newer full-field write supersedes this mutation and must survive its rollback.
return {
...(Object.hasOwn(updates, 'defaultTuiAgent') &&
Object.is(current.defaultTuiAgent, applied.defaultTuiAgent)
...(Object.hasOwn(updates, 'defaultTuiAgent') && defaultUnchanged
? { defaultTuiAgent: before.defaultTuiAgent ?? null }
: {}),
...(Object.hasOwn(updates, 'newWorkspaceSetupOnly') && defaultUnchanged
? { newWorkspaceSetupOnly: before.newWorkspaceSetupOnly === true }
: {}),
...(Object.hasOwn(updates, 'disabledTuiAgents') &&
Object.is(current.disabledTuiAgents, applied.disabledTuiAgents)
? { disabledTuiAgents: before.disabledTuiAgents ?? [] }
Expand Down
1 change: 1 addition & 0 deletions src/main/runtime/orca-runtime-activate-managed-worktree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,7 @@ export class OrcaRuntimeWithActivateManagedWorktree extends OrcaRuntimeWithListM
defaultTabs?: CreateWorktreeResult['defaultTabs']
primaryTerminalHandle?: string | null
hasStartupTerminal: boolean
setupOnly?: boolean
setupCommandPlatform: 'windows' | 'posix'
observeSetupCompletion?: boolean
// Why: when the agent startup is sequenced to wait for setup
Expand Down
1 change: 1 addition & 0 deletions src/main/runtime/rpc/methods/worktree-create-args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ export function buildManagedWorktreeCreateArgs(
defaultTarget: 'host'
}),
setupDecision: params.setupDecision,
...(params.setupOnly !== undefined ? { setupOnly: params.setupOnly } : {}),
createdWithAgent: params.createdWithAgent ?? params.startupAgent,
...provenance,
// Why: a person initiated this create (the phone, CLI text and agent.launch don't surface the
Expand Down
10 changes: 10 additions & 0 deletions src/main/runtime/rpc/methods/worktree-create-setup-choice.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { describe, expect, it } from 'vitest'
import { WorktreeCreate } from '../../../../shared/rpc-contract/worktree-create-params'
import { buildManagedWorktreeCreateArgs } from './worktree-create-args'

describe('worktree setup choice', () => {
it.each([false, true])('preserves the submitted choice across RPC (%s)', (setupOnly) => {
const params = WorktreeCreate.parse({ repo: 'repo-1', name: 'choice', setupOnly })
expect(buildManagedWorktreeCreateArgs(params, {})).toMatchObject({ setupOnly })
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,27 @@ describe('durable execution-host launch settings', () => {
expect(readState().settings.agentDefaultArgs.claude).toBe('--durable-marker')
})

it('rolls back both None fields when the database write fails', async () => {
const { store, authority } = await fixture()
const controller = new RuntimeClientSettingsController(store)
const before = store.getSettings().defaultTuiAgent
authority.failNextWrite()
try {
await expect(
controller.mutateAgentLaunch({ type: 'default', agent: 'blank', setupOnly: true })
).rejects.toThrow('profile_state_write_failed')
} finally {
await store.flushPendingOrThrowAsync().catch(() => {})
}
expect(store.getSettings().defaultTuiAgent).toBe(before)
expect(store.getSettings().newWorkspaceSetupOnly).toBe(false)
await controller.mutateAgentLaunch({ type: 'default', agent: 'blank', setupOnly: true })
expect(controller.getAgentLaunch()).toMatchObject({
defaultTuiAgent: 'blank',
newWorkspaceSetupOnly: true
})
})

it('rejects a failed disk write, rolls back its settings, and allows an explicit retry', async () => {
const { store, authority, readState } = await fixture()
const controller = new RuntimeClientSettingsController(store)
Expand Down Expand Up @@ -192,6 +213,27 @@ describe('durable execution-host launch settings', () => {
])
})

it('preserves a newer blank choice when a pending None write fails', async () => {
const { store, authority } = await fixture()
const controller = new RuntimeClientSettingsController(store)
authority.failNextWrite()
const gate = authority.pause()
const first = controller.mutateAgentLaunch({ type: 'default', agent: 'blank', setupOnly: true })
const refused = expect(first).rejects.toThrow('profile_state_write_failed')
try {
await gate.started.promise
store.updateSettings({ defaultTuiAgent: 'blank', newWorkspaceSetupOnly: false })
} finally {
gate.finish.resolve()
}
await refused
expect(controller.getAgentLaunch()).toMatchObject({
defaultTuiAgent: 'blank',
newWorkspaceSetupOnly: false
})
await store.flushPendingOrThrowAsync()
})

it('preserves a newer legacy full-map write when an older mutation fails', async () => {
const { store, authority, readState } = await fixture()
const controller = new RuntimeClientSettingsController(store)
Expand Down
32 changes: 32 additions & 0 deletions src/main/runtime/runtime-client-agent-launch-settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,38 @@ describe('execution-host agent launch settings', () => {
expect(JSON.stringify(controller.getAgentLaunch())).not.toContain('host-only')
})

it('persists and projects None, then clears it for a blank default', async () => {
const { controller, host } = fixture()
const mutation = AgentLaunchSettingsMutation.parse({
type: 'default',
agent: 'blank',
setupOnly: true
})
await expect(controller.mutateAgentLaunch(mutation)).resolves.toMatchObject({
defaultTuiAgent: 'blank',
newWorkspaceSetupOnly: true
})
expect(host.newWorkspaceSetupOnly).toBe(true)
await expect(
controller.mutateAgentLaunch({ type: 'default', agent: 'blank' })
).resolves.toMatchObject({
defaultTuiAgent: 'blank',
newWorkspaceSetupOnly: false
})
expect(host.newWorkspaceSetupOnly).toBe(false)
})

it('clears None when a legacy client explicitly picks Blank Terminal', async () => {
const { controller, host } = fixture()
await controller.mutateAgentLaunch({ type: 'default', agent: 'blank', setupOnly: true })
await controller.update({ defaultTuiAgent: 'blank' })
expect(host.newWorkspaceSetupOnly).toBe(false)
expect(controller.getAgentLaunch()).toMatchObject({
defaultTuiAgent: 'blank',
newWorkspaceSetupOnly: false
})
})

it('clears the host default when disabling that agent and preserves others', async () => {
const { controller, host } = fixture()
host.defaultTuiAgent = 'claude'
Expand Down
1 change: 1 addition & 0 deletions src/main/runtime/runtime-client-settings-shape.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { SourceControlAiActionDefaults } from '../../shared/source-control-
export type RuntimeClientSettings = Pick<
GlobalSettings,
| 'defaultTuiAgent'
| 'newWorkspaceSetupOnly'
| 'disabledTuiAgents'
| 'agentCmdOverrides'
| 'agentDefaultArgs'
Expand Down
10 changes: 9 additions & 1 deletion src/main/runtime/runtime-client-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export class RuntimeClientSettingsController {
const settings = this.store.getSettings()
return {
defaultTuiAgent: settings.defaultTuiAgent ?? null,
newWorkspaceSetupOnly: settings.newWorkspaceSetupOnly === true,
disabledTuiAgents: settings.disabledTuiAgents ?? [],
agentCmdOverrides: settings.agentCmdOverrides ?? {},
agentDefaultArgs: settings.agentDefaultArgs ?? {},
Expand Down Expand Up @@ -106,7 +107,14 @@ export class RuntimeClientSettingsController {
}
const beforeSettings = this.store.getSettings()
const before = beforeSettings.agentStatusHooksEnabled !== false
this.store.updateSettings(updates, { notifyListeners: true })
// Legacy clients can select an agent or a shell, but cannot select None.
this.store.updateSettings(
{
...updates,
...(updates.defaultTuiAgent !== undefined ? { newWorkspaceSetupOnly: false } : {})
},
{ notifyListeners: true }
)
const settings = this.store.getSettings()
if (updates.worktreeVisibilityDefaults !== undefined) {
this.notifyReposChanged?.()
Expand Down
20 changes: 20 additions & 0 deletions src/main/runtime/runtime-local-worktree-terminal-startup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,26 @@ describe('startRuntimeLocalWorktreeTerminals reserved startup pane', () => {
})

describe('startRuntimeLocalWorktreeTerminals default shell seeding', () => {
it.each([false, true])(
'passes the submitted setup-only choice to the host (%s)',
async (setupOnly) => {
const { ports } = createPorts()
await startRuntimeLocalWorktreeTerminals({
request: {
repoSelector: `id:${repo.id}`,
name: 'choice',
setupOnly,
awaitTerminalProvisioning: true
},
repo,
worktree,
setup: { runnerScriptPath: '/repo/setup.sh', envVars: {} },
ports
})
expect(ports.provision).toHaveBeenCalledWith(expect.objectContaining({ setupOnly }))
}
)

it.each([false, true])(
'provisions a headless activated workspace without a viewer (setup=%s)',
async (withSetup) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ function provisionArgs(
...(args.defaultTabs ? { defaultTabs: args.defaultTabs } : {}),
primaryTerminalHandle,
hasStartupTerminal,
...(args.request.setupOnly !== undefined ? { setupOnly: args.request.setupOnly } : {}),
setupCommandPlatform: setupPlatform(args.setup, 'posix'),
observeSetupCompletion: args.request.observeSetupCompletion,
...(wrappedSetupCommand ? { wrappedSetupCommand } : {})
Expand Down
1 change: 1 addition & 0 deletions src/main/runtime/runtime-managed-worktree-create-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export type RuntimeManagedWorktreeCreateArgs = {
runHooks?: boolean
activate?: boolean
setupDecision?: 'run' | 'skip' | 'inherit'
setupOnly?: boolean
awaitTerminalProvisioning?: boolean
observeSetupCompletion?: boolean
createdWithAgent?: TuiAgent
Expand Down
2 changes: 2 additions & 0 deletions src/main/runtime/runtime-store-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ export type RuntimeStore = {
branchPrefix: string
branchPrefixCustom: string
defaultTuiAgent?: GlobalSettings['defaultTuiAgent']
newWorkspaceSetupOnly?: GlobalSettings['newWorkspaceSetupOnly']
setupScriptLaunchMode?: GlobalSettings['setupScriptLaunchMode']
disabledTuiAgents?: GlobalSettings['disabledTuiAgents']
agentCmdOverrides?: GlobalSettings['agentCmdOverrides']
agentDefaultArgs?: GlobalSettings['agentDefaultArgs']
Expand Down
95 changes: 95 additions & 0 deletions src/main/runtime/runtime-worktree-terminal-provisioning.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,98 @@ describe('default tabs beside the agent a create started', () => {
warn.mockRestore()
})
})

const setup = { runnerScriptPath: '/repo/.orca/setup.sh', envVars: {} }

function createHost(settings: Record<string, unknown>): {
host: WorktreeTerminalProvisioningHost
titles: () => (string | undefined)[]
} {
const createTerminal = vi.fn<WorktreeTerminalProvisioningHost['createTerminal']>(async () => ({
handle: `term-${createTerminal.mock.calls.length}`
}))
return {
host: {
canSpawn: () => true,
createTerminal,
splitTerminal: vi.fn(async () => ({ handle: 'split' })),
setTabTitle: vi.fn(async () => {}),
setTabColor: vi.fn(async () => {}),
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: provisioning reads only the optional keys each test supplies.
getSettings: () => settings as ReturnType<WorktreeTerminalProvisioningHost['getSettings']>,
getPtyId: () => undefined,
recordSetupCompletionToken: vi.fn()
},
titles: () => createTerminal.mock.calls.map(([, options]) => options.title)
}
}

function provisionWithSetup(
host: WorktreeTerminalProvisioningHost,
withSetup = true,
setupOnly?: boolean
) {
return provisionWorktreeTerminals(host, {
worktreeSelector: 'id:wt-1',
worktreeId: 'wt-1',
worktreePath: '/repo/wt-1',
...(withSetup ? { setup } : {}),
hasStartupTerminal: false,
...(setupOnly !== undefined ? { setupOnly } : {}),
setupCommandPlatform: 'posix'
})
}

describe('provisionWorktreeTerminals with the "None" default', () => {
const none = { defaultTuiAgent: 'blank', newWorkspaceSetupOnly: true }

it('honours a one-off None choice over the host blank default', async () => {
const { host, titles } = createHost({ defaultTuiAgent: 'blank' })
await provisionWithSetup(host, true, true)
expect(titles()).toEqual(['Setup'])
})

it('honours a one-off blank choice over the host None default', async () => {
const { host, titles } = createHost(none)
await provisionWithSetup(host, true, false)
expect(titles()).toEqual([undefined, 'Setup'])
})

it('opens only the Setup tab', async () => {
const { host, titles } = createHost(none)
await expect(provisionWithSetup(host)).resolves.toMatchObject({ setupSpawned: true })
expect(titles()).toEqual(['Setup'])
})

it('keeps the blank terminal for a plain blank default', async () => {
const { host, titles } = createHost({ defaultTuiAgent: 'blank' })
await provisionWithSetup(host)
expect(titles()).toEqual([undefined, 'Setup'])
})

it('falls back to a blank terminal when no setup runs', async () => {
const { host, titles } = createHost(none)
await provisionWithSetup(host, false)
expect(titles()).toEqual([undefined])
})

it('opens a blank terminal when the Setup tab fails to spawn', async () => {
const { host, titles } = createHost(none)
const createTerminal = vi.mocked(host.createTerminal)
createTerminal.mockRejectedValueOnce(new Error('spawn failed'))
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
await expect(provisionWithSetup(host)).resolves.toEqual({
setupSpawned: false,
setupTerminalHandle: null
})
expect(titles()).toEqual(['Setup', undefined])
warn.mockRestore()
})

it('keeps the shell a split setup needs', async () => {
const { host, titles } = createHost({ ...none, setupScriptLaunchMode: 'split-vertical' })
await provisionWithSetup(host)
expect(titles()).toEqual([undefined])
expect(host.splitTerminal).toHaveBeenCalledTimes(1)
})
})
31 changes: 26 additions & 5 deletions src/main/runtime/runtime-worktree-terminal-provisioning.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { randomUUID } from 'node:crypto'
import type { CreateWorktreeResult } from '../../shared/worktree/create-types'
import type { GlobalSettings } from '../../shared/global-settings-types'
import { buildObservedSetupCommand } from './orchestration/setup-completion-signal'
import { buildSetupRunnerCommand } from '../../shared/setup-runner-command'
import { isNewWorkspaceSetupOnlyDefault } from '../../shared/new-workspace-setup-only'
import type { RuntimeStore } from './runtime-store-contract'

type TerminalResult = { handle: string }
Expand Down Expand Up @@ -42,6 +42,7 @@ export type WorktreeTerminalProvisioningArgs = {
defaultTabs?: CreateWorktreeResult['defaultTabs']
primaryTerminalHandle?: string | null
hasStartupTerminal: boolean
setupOnly?: boolean
setupCommandPlatform: 'windows' | 'posix'
observeSetupCompletion?: boolean
// Why: setup and startup must use the same wrapper when startup waits for setup.
Expand Down Expand Up @@ -118,6 +119,7 @@ export async function provisionWorktreeTerminals(
const surfacing = args.surfaceOwner === false ? { surfaceOwner: false as const } : {}
let setupSpawned = false
let setupTerminalHandle: string | null = null
let shellSkippedForSetup = false
try {
const defaultHandles = await createWorktreeDefaultTabTerminals(
host,
Expand All @@ -128,11 +130,19 @@ export async function provisionWorktreeTerminals(
args.hasStartupTerminal ? (args.primaryTerminalHandle ?? undefined) : undefined
)
let primaryHandle = args.primaryTerminalHandle ?? defaultHandles[0] ?? null
const setupLaunchMode =
(host.getSettings() as Partial<Pick<GlobalSettings, 'setupScriptLaunchMode'>>)
.setupScriptLaunchMode ?? 'new-tab'
const settings = host.getSettings()
const setupLaunchMode = settings.setupScriptLaunchMode ?? 'new-tab'
// Why: "None" default leaves the Setup tab as the only surface; a split still needs a shell to split from.
const setupOnly =
args.setup !== undefined &&
setupLaunchMode === 'new-tab' &&
(args.setupOnly ?? isNewWorkspaceSetupOnlyDefault(settings))
if (!args.hasStartupTerminal && !primaryHandle) {
primaryHandle = (await host.createTerminal(args.worktreeSelector, surfacing)).handle
if (setupOnly) {
shellSkippedForSetup = true
} else {
primaryHandle = (await host.createTerminal(args.worktreeSelector, surfacing)).handle
}
}
if (args.setup) {
const completionToken =
Expand Down Expand Up @@ -183,6 +193,17 @@ export async function provisionWorktreeTerminals(
console.warn(
`[worktree-create] Failed to create setup/default terminals for ${args.worktreePath}: ${message}`
)
// Why: "None" skipped the shell on the promise of a Setup tab; without one the workspace would have no terminal.
if (shellSkippedForSetup && !setupSpawned) {
await host
.createTerminal(args.worktreeSelector, surfacing)
.catch((fallbackError: unknown) => {
console.warn(
`[worktree-create] Failed to open a fallback terminal for ${args.worktreePath}:`,
fallbackError
)
})
}
}
return { setupSpawned, setupTerminalHandle }
}
Loading
Loading