mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
513 lines
19 KiB
TypeScript
513 lines
19 KiB
TypeScript
import type * as SessionTabsStateModule from '../../../src/renderer/src/runtime/web-session-tabs-sync/state'
|
|
import { composeAgentLaunchProfile } from '../../../src/shared/agent-launch/choices/tui-agent-launch-defaults'
|
|
import { tokenizeStartupCommand } from '../../../src/shared/agent-launch/startup/tui-agent-startup-shell'
|
|
import * as startupInputs from '../../../src/shared/agent-launch/startup/agent-startup-plan-inputs'
|
|
import { resolveBaselineAgentStartupPlanInputs } from '../../../src/shared/agent-launch/startup/agent-startup-plan-inputs-baseline-test-fixture'
|
|
import '../../../src/main/runtime/orca-runtime-tests/runtime-test-module-registration.spec'
|
|
import { OrcaRuntimeService } from '../../../src/main/runtime/orca-runtime'
|
|
import { getDefaultWorkspaceSession } from '../../../src/shared/constants'
|
|
import '../../../src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec'
|
|
import {
|
|
TEST_WORKTREE_ID,
|
|
TEST_WORKTREE_PATH,
|
|
makeRuntimeStoreWithWorkspaceSession
|
|
} from '../../../src/main/runtime/orca-runtime-tests/orca-runtime-test-fixtures.spec'
|
|
import { committingSpawn } from '../../../src/main/runtime/orca-runtime-tests/bind-first-pane.test-fixture'
|
|
import type { RuntimePtyController } from '../../../src/main/runtime/terminal/lifecycle/runtime-pty-controller-contract'
|
|
import { RpcDispatcher } from '../../../src/main/runtime/rpc/dispatcher'
|
|
import { SESSION_TAB_METHODS } from '../../../src/main/runtime/rpc/methods/session-tabs/session-tabs'
|
|
import { TERMINAL_LIFECYCLE_METHODS } from '../../../src/main/runtime/rpc/methods/terminal/terminal-lifecycle-methods'
|
|
import { AGENT_SESSION_METHODS } from '../../../src/main/runtime/rpc/methods/terminal/agent-session'
|
|
import { YOLO_TUI_AGENT_ENV } from '../../../src/shared/agent-launch/permissions/tui-agent-permissions'
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
import { launchAgentInWebHostTab } from '../../../src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-web-host-tab'
|
|
import { buildAgentStartupPlan } from '../../../src/shared/agent-launch/startup/tui-agent-startup'
|
|
import { createWebRuntimeSessionTerminal } from '../../../src/renderer/src/runtime/hosted-terminals/creation/web-runtime-terminal-creation'
|
|
import { resetWebSessionCloseIntentForTests } from '../../../src/renderer/src/runtime/web-session-tabs-sync/closing/web-session-close-intent'
|
|
import {
|
|
ENVIRONMENT_ID,
|
|
WORKTREE_ID,
|
|
makeSnapshot,
|
|
resetTerminalCreateEnvironment,
|
|
stubTerminalCreateEnvironment
|
|
} from '../../../src/renderer/src/runtime/hosted-terminals/creation/testing/web-runtime-terminal-create.test-fixture'
|
|
import { stubRuntimeEnvironmentBridge } from '../../../src/renderer/src/runtime/rpc/testing/runtime-environment-bridge-fixture'
|
|
|
|
const mocks = vi.hoisted(() => ({
|
|
getState: vi.fn(),
|
|
setState: vi.fn(),
|
|
subscribe: vi.fn(),
|
|
setActiveWorktree: vi.fn(),
|
|
createBrowserTab: vi.fn(),
|
|
closeEmptyGroup: vi.fn(),
|
|
moveUnifiedTabToGroup: vi.fn(),
|
|
setRemoteBrowserPageHandle: vi.fn(),
|
|
focusBrowserTabInWorktree: vi.fn(),
|
|
applyWebSessionTabsSnapshot: vi.fn(),
|
|
decideWebSessionTabsSnapshot: vi.fn(() => ({ apply: true, settlesHostMirror: true })),
|
|
getWebSessionTabsTrackingGeneration: vi.fn(() => 0),
|
|
acceptReplayedWebSessionTabsSnapshot: vi.fn(),
|
|
resolveHostSessionTabIdForWebSessionTab: vi.fn(),
|
|
trackTerminalPaneSplit: vi.fn(),
|
|
deliverLaunchPromptToAgentTab: vi.fn(),
|
|
seedNativeChatLaunchDraftForAgentTab: vi.fn(),
|
|
hasMaterializedWebRuntimeBrowserPage: vi.fn()
|
|
}))
|
|
|
|
vi.mock('../../../src/renderer/src/store', () => ({
|
|
useAppStore: {
|
|
getState: mocks.getState,
|
|
setState: mocks.setState,
|
|
subscribe: mocks.subscribe
|
|
}
|
|
}))
|
|
|
|
vi.mock(
|
|
'../../../src/renderer/src/runtime/web-session-tabs-sync/state',
|
|
async (importOriginal) => ({
|
|
...(await importOriginal<typeof SessionTabsStateModule>()),
|
|
acceptReplayedWebSessionTabsSnapshot: mocks.acceptReplayedWebSessionTabsSnapshot
|
|
})
|
|
)
|
|
|
|
vi.mock('../../../src/renderer/src/runtime/web-session-tabs-sync/tracking-lifecycle', () => ({
|
|
getWebSessionTabsTrackingGeneration: mocks.getWebSessionTabsTrackingGeneration
|
|
}))
|
|
vi.mock('../../../src/renderer/src/runtime/web-session-tabs-sync/snapshot-api', () => ({
|
|
applyWebSessionTabsSnapshot: mocks.applyWebSessionTabsSnapshot
|
|
}))
|
|
vi.mock('../../../src/renderer/src/runtime/web-session-tabs-sync/tracking-decisions', () => ({
|
|
decideWebSessionTabsSnapshot: mocks.decideWebSessionTabsSnapshot
|
|
}))
|
|
vi.mock('../../../src/renderer/src/runtime/web-session-tabs-sync/store-patch', () => ({
|
|
applyWebSessionTabsStorePatch: (buildPatch: (state: unknown) => unknown) => {
|
|
mocks.setState(buildPatch)
|
|
return () => {}
|
|
}
|
|
}))
|
|
vi.mock('../../../src/renderer/src/runtime/web-session-tabs-sync/tracking-mappings', () => ({
|
|
resolveHostSessionTabIdForWebSessionTab: mocks.resolveHostSessionTabIdForWebSessionTab
|
|
}))
|
|
|
|
vi.mock('@/lib/feature-education-telemetry', () => ({
|
|
trackTerminalPaneSplit: mocks.trackTerminalPaneSplit
|
|
}))
|
|
|
|
vi.mock('@/lib/agent-session/launch/prompt/agent-launch-prompt-delivery', () => ({
|
|
deliverLaunchPromptToAgentTab: mocks.deliverLaunchPromptToAgentTab,
|
|
seedNativeChatLaunchDraftForAgentTab: mocks.seedNativeChatLaunchDraftForAgentTab
|
|
}))
|
|
|
|
vi.mock(
|
|
'../../../src/renderer/src/runtime/browser/creation/web-runtime-browser-materialization',
|
|
() => ({
|
|
hasMaterializedWebRuntimeBrowserPage: mocks.hasMaterializedWebRuntimeBrowserPage
|
|
})
|
|
)
|
|
|
|
const currentInputs = startupInputs.resolveAgentStartupPlanInputs
|
|
afterEach(() => {
|
|
resetWebSessionCloseIntentForTests()
|
|
vi.restoreAllMocks()
|
|
})
|
|
|
|
describe('createWebRuntimeSessionTerminal', () => {
|
|
beforeEach(() => {
|
|
stubTerminalCreateEnvironment(mocks)
|
|
})
|
|
|
|
afterEach(() => {
|
|
resetTerminalCreateEnvironment()
|
|
})
|
|
|
|
it.each([
|
|
{ agent: 'goose', mode: 'own', hostMode: 'full-access', authority: true, activate: true },
|
|
{ agent: 'goose', mode: 'full-access', hostMode: 'own', authority: true, activate: false },
|
|
{
|
|
agent: 'goose',
|
|
mode: 'own',
|
|
hostMode: 'full-access',
|
|
authority: false,
|
|
activate: false,
|
|
userMode: 'approve'
|
|
},
|
|
{ agent: 'codex', mode: 'ask', hostMode: 'own', authority: true },
|
|
{ agent: 'claude', mode: 'ask', hostMode: 'own', authority: true, loose: true },
|
|
{ agent: 'goose', mode: 'own', hostMode: 'full-access', authority: true, fail: true }
|
|
] as const)('preserves a complete launch at the pinned old spawn boundary: %j', async (test) => {
|
|
const settings = {
|
|
agentCmdOverrides: { [test.agent]: '/host/agent-cli' },
|
|
agentPermissionDefault: test.hostMode,
|
|
agentDefaultEnv:
|
|
test.mode === 'own' && !('userMode' in test)
|
|
? {}
|
|
: {
|
|
[test.agent]: {
|
|
PROFILE: 'user',
|
|
...('userMode' in test ? { GOOSE_MODE: test.userMode } : {})
|
|
}
|
|
}
|
|
}
|
|
const options = {
|
|
permissionMode: test.mode,
|
|
...(test.agent === 'codex' ? { model: 'gpt-5.4', effort: 'high' } : {})
|
|
}
|
|
const plan = buildAgentStartupPlan({
|
|
...currentInputs({
|
|
agent: test.agent,
|
|
settings,
|
|
platform: 'linux',
|
|
isRemote: true,
|
|
shell: 'posix',
|
|
agentArgs:
|
|
'loose' in test ? '--dangerously-skip-permissions --verbose' : '--profile "with spaces"',
|
|
sessionOptions: options
|
|
}),
|
|
prompt: '',
|
|
allowEmptyPromptLaunch: true
|
|
})
|
|
if (!plan) {
|
|
throw new Error('Missing startup plan')
|
|
}
|
|
const spawn = vi.fn(
|
|
async (_args: Parameters<NonNullable<RuntimePtyController['spawn']>>[0]) => ({
|
|
id: 'baseline-pty'
|
|
})
|
|
)
|
|
const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession(getDefaultWorkspaceSession())
|
|
const runtime = new OrcaRuntimeService({
|
|
...runtimeStore,
|
|
getSettings: () => ({ ...runtimeStore.getSettings(), ...settings })
|
|
})
|
|
runtime.setPtyController({
|
|
spawn: committingSpawn(runtime, spawn),
|
|
write: () => true,
|
|
kill: () => true,
|
|
getForegroundProcess: async () => null
|
|
})
|
|
runtime.syncWindowGraph(0, { tabs: [], leaves: [] })
|
|
const dispatcher = new RpcDispatcher({
|
|
runtime,
|
|
methods: [...SESSION_TAB_METHODS, ...TERMINAL_LIFECYCLE_METHODS, ...AGENT_SESSION_METHODS]
|
|
})
|
|
const state = mocks.getState()
|
|
mocks.getState.mockReturnValue({
|
|
...state,
|
|
setActiveTabType: vi.fn(),
|
|
activeTabTypeByWorktree: {},
|
|
settings: {
|
|
...state.settings,
|
|
agentCmdOverrides: { [test.agent]: '/desktop/agent-cli' },
|
|
agentDefaultArgs: { [test.agent]: '--model desktop-only-qa' },
|
|
agentDefaultEnv: { [test.agent]: { DESKTOP_ENV: 'desktop' } }
|
|
}
|
|
})
|
|
const creates: string[] = []
|
|
const runtimeCall = vi.fn(async (request: { method: string; params?: unknown }) => {
|
|
if (request.method === 'status.get') {
|
|
return {
|
|
id: 'status',
|
|
ok: true,
|
|
result: {
|
|
runtimeId: 'baseline-660243e61ff',
|
|
graphStatus: 'ready',
|
|
runtimeProtocolVersion: 3,
|
|
minCompatibleRuntimeClientVersion: 2,
|
|
capabilities: test.authority ? ['agent-session.host-authority.v1'] : []
|
|
}
|
|
}
|
|
}
|
|
if (request.method === 'settings.get') {
|
|
return {
|
|
id: 'settings',
|
|
ok: true,
|
|
result: {
|
|
settings: {
|
|
agentCmdOverrides: settings.agentCmdOverrides,
|
|
...composeAgentLaunchProfile(settings, 'linux')
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (
|
|
request.method !== 'terminal.create' &&
|
|
request.method !== 'terminal.createAgentSession' &&
|
|
request.method !== 'session.tabs.createTerminal'
|
|
) {
|
|
return { id: 'placement', ok: true, result: makeSnapshot() }
|
|
}
|
|
creates.push(request.method)
|
|
if (test.agent === 'goose') {
|
|
expect(request.params).toMatchObject({
|
|
command: plan.launchCommand,
|
|
env: plan.env ?? {},
|
|
launchConfig: plan.launchConfig,
|
|
cwd: TEST_WORKTREE_PATH,
|
|
targetGroupId: 'group',
|
|
activate: false,
|
|
select: 'activate' in test ? test.activate : true
|
|
})
|
|
}
|
|
vi.spyOn(startupInputs, 'resolveAgentStartupPlanInputs').mockImplementation(
|
|
resolveBaselineAgentStartupPlanInputs
|
|
)
|
|
const response = await dispatcher.dispatch(
|
|
{ id: 'create', authToken: 'test', method: request.method, params: request.params },
|
|
{ clientKind: 'runtime', clientId: 'paired-client' }
|
|
)
|
|
if ('fail' in test) {
|
|
throw new Error('ambiguous create failure')
|
|
}
|
|
return response
|
|
})
|
|
stubRuntimeEnvironmentBridge({ call: runtimeCall })
|
|
const result = await launchAgentInWebHostTab({
|
|
agent: test.agent,
|
|
worktreeId: TEST_WORKTREE_ID,
|
|
environmentId: ENVIRONMENT_ID,
|
|
agentArgs:
|
|
'loose' in test ? '--dangerously-skip-permissions --verbose' : '--profile "with spaces"',
|
|
sessionOptions: options,
|
|
buildStartup: () => ({
|
|
startupPlan: plan,
|
|
pasteDraftAfterLaunch: null,
|
|
submitPastedPrompt: false
|
|
}),
|
|
prompt: '',
|
|
promptDelivery: 'auto-submit',
|
|
activate: 'activate' in test ? test.activate : true,
|
|
cwd: TEST_WORKTREE_PATH,
|
|
groupId: 'group',
|
|
viewMode: 'terminal'
|
|
})
|
|
expect(result.outcome.status).toBe('fail' in test ? 'failed' : 'created')
|
|
expect(creates).toEqual(['session.tabs.createTerminal'])
|
|
expect(spawn).toHaveBeenCalledTimes(1)
|
|
const final = spawn.mock.calls[0][0]
|
|
expect(final.cwd).toBe(TEST_WORKTREE_PATH)
|
|
expect(final.env).toMatchObject(plan.env ?? {})
|
|
expect(final.env?.GOOSE_MODE).toBe(plan.env?.GOOSE_MODE)
|
|
const expected = tokenizeStartupCommand(plan.launchCommand, 'posix')
|
|
if (final.command === undefined) {
|
|
throw new Error('Missing final command')
|
|
}
|
|
const actual = tokenizeStartupCommand(final.command, 'posix')
|
|
if (!expected.ok || !actual.ok) {
|
|
throw new Error('Invalid final command')
|
|
}
|
|
expect(actual.tokens.toSorted()).toEqual(expected.tokens.toSorted())
|
|
if (test.agent === 'goose') {
|
|
expect(final.command).toBe(plan.launchCommand)
|
|
expect(final.launchConfig).toEqual(plan.launchConfig)
|
|
expect(final.startupCommandDelivery).toBe(plan.startupCommandDelivery)
|
|
expect(plan.env?.GOOSE_MODE).toBe(
|
|
'userMode' in test
|
|
? test.userMode
|
|
: test.mode === 'own'
|
|
? undefined
|
|
: YOLO_TUI_AGENT_ENV.goose?.GOOSE_MODE
|
|
)
|
|
}
|
|
if ('loose' in test) {
|
|
expect(plan.sessionOptions?.permissionMode).toBeUndefined()
|
|
}
|
|
})
|
|
|
|
it.each([
|
|
{
|
|
agent: 'codex' as const,
|
|
predecessor: 'web-terminal-host-tab-1',
|
|
afterTabId: 'web-terminal-host-tab-1%3A%3Aleaf-1'
|
|
},
|
|
{
|
|
agent: undefined,
|
|
predecessor: 'web-terminal-host-tab-1',
|
|
afterTabId: 'web-terminal-host-tab-1%3A%3Aleaf-1'
|
|
},
|
|
{ agent: undefined, predecessor: 'local-browser-tab', afterTabId: 'local-browser-tab' },
|
|
{
|
|
agent: undefined,
|
|
predecessor: 'web-terminal-host-tab-1%3A%3Aleaf-1',
|
|
afterTabId: 'web-terminal-host-tab-1%3A%3Aleaf-1'
|
|
}
|
|
])(
|
|
'settles after $afterTabId for $agent creation without activating it',
|
|
async ({ agent, predecessor, afterTabId }) => {
|
|
const successor = 'web-terminal-host-tab-3'
|
|
const created = 'web-terminal-host-tab-2'
|
|
const reorderUnifiedTabs = vi.fn()
|
|
mocks.getState.mockReturnValue({
|
|
...mocks.getState(),
|
|
unifiedTabsByWorktree: {
|
|
[WORKTREE_ID]: [predecessor, successor, created].map((id) => ({
|
|
id,
|
|
groupId: 'client-group'
|
|
}))
|
|
},
|
|
groupsByWorktree: {
|
|
[WORKTREE_ID]: [{ id: 'client-group', tabOrder: [predecessor, successor, created] }]
|
|
},
|
|
reorderUnifiedTabs,
|
|
moveUnifiedTabToGroup: mocks.moveUnifiedTabToGroup
|
|
})
|
|
const runtimeCall = vi.fn(async (request: { method: string }) => ({
|
|
id: request.method,
|
|
ok: true,
|
|
result:
|
|
request.method === 'session.tabs.createTerminal'
|
|
? { tab: { id: 'host-tab-2::leaf-2' }, publicationEpoch: 'epoch-1', snapshotVersion: 2 }
|
|
: makeSnapshot()
|
|
}))
|
|
stubRuntimeEnvironmentBridge({ call: runtimeCall })
|
|
|
|
await expect(
|
|
createWebRuntimeSessionTerminal({
|
|
environmentId: ENVIRONMENT_ID,
|
|
worktreeId: WORKTREE_ID,
|
|
afterTabId,
|
|
agent,
|
|
activate: false
|
|
})
|
|
).resolves.toEqual({ status: 'created' })
|
|
|
|
expect(reorderUnifiedTabs).toHaveBeenCalledExactlyOnceWith(
|
|
'client-group',
|
|
[predecessor, created, successor],
|
|
{ recordInteraction: false }
|
|
)
|
|
expect(mocks.moveUnifiedTabToGroup).not.toHaveBeenCalled()
|
|
}
|
|
)
|
|
|
|
it('preserves the opaque legacy resume payload on an old host', async () => {
|
|
const runtimeCall = vi.fn(async (request: { method: string }) => {
|
|
if (request.method === 'status.get') {
|
|
return {
|
|
id: 'status',
|
|
ok: true,
|
|
result: {
|
|
runtimeId: 'old-runtime',
|
|
graphStatus: 'ready',
|
|
runtimeProtocolVersion: 3,
|
|
minCompatibleRuntimeClientVersion: 2,
|
|
capabilities: []
|
|
}
|
|
}
|
|
}
|
|
if (request.method === 'session.tabs.createTerminal') {
|
|
return {
|
|
id: 'legacy-create',
|
|
ok: true,
|
|
result: { tab: { id: 'legacy-tab-1' }, publicationEpoch: 'epoch-1', snapshotVersion: 1 }
|
|
}
|
|
}
|
|
return { id: 'list', ok: true, result: makeSnapshot() }
|
|
})
|
|
stubRuntimeEnvironmentBridge({ call: runtimeCall })
|
|
|
|
await expect(
|
|
createWebRuntimeSessionTerminal({
|
|
environmentId: ENVIRONMENT_ID,
|
|
worktreeId: WORKTREE_ID,
|
|
agentSessionKind: 'resume',
|
|
launchAgent: 'codex',
|
|
command: "codex resume 'session-1'",
|
|
env: { CODEX_PROFILE: 'captured' },
|
|
launchConfig: {
|
|
agentCommand: 'codex',
|
|
agentArgs: '',
|
|
agentEnv: { CODEX_PROFILE: 'captured' }
|
|
},
|
|
providerSession: { key: 'session_id', id: 'session-1' }
|
|
})
|
|
).resolves.toEqual({ status: 'created' })
|
|
|
|
expect(runtimeCall).toHaveBeenNthCalledWith(2, {
|
|
selector: ENVIRONMENT_ID,
|
|
method: 'session.tabs.createTerminal',
|
|
params: {
|
|
worktree: `id:${WORKTREE_ID}`,
|
|
afterTabId: undefined,
|
|
targetGroupId: undefined,
|
|
command: "codex resume 'session-1'",
|
|
cwd: undefined,
|
|
env: { CODEX_PROFILE: 'captured' },
|
|
startupCommandDelivery: undefined,
|
|
launchConfig: {
|
|
agentCommand: 'codex',
|
|
agentArgs: '',
|
|
agentEnv: { CODEX_PROFILE: 'captured' }
|
|
},
|
|
launchAgent: 'codex',
|
|
activate: false,
|
|
select: true,
|
|
navigation: 'caller'
|
|
},
|
|
timeoutMs: 15_000
|
|
})
|
|
})
|
|
|
|
it('uses the exact legacy OMP resume when an older host only advertises base authority', async () => {
|
|
const methods: string[] = []
|
|
const runtimeCall = vi.fn(async (request: { method: string }) => {
|
|
methods.push(request.method)
|
|
if (request.method === 'status.get') {
|
|
return {
|
|
id: 'status',
|
|
ok: true,
|
|
result: {
|
|
runtimeId: 'new-runtime',
|
|
graphStatus: 'ready',
|
|
runtimeProtocolVersion: 3,
|
|
minCompatibleRuntimeClientVersion: 2,
|
|
capabilities: ['agent-session.host-authority.v1']
|
|
}
|
|
}
|
|
}
|
|
if (request.method === 'terminal.ensureAgentSession') {
|
|
return {
|
|
id: 'ensure',
|
|
ok: false,
|
|
error: {
|
|
code: 'invalid_argument',
|
|
message: 'old host rejected OMP'
|
|
}
|
|
}
|
|
}
|
|
return {
|
|
id: 'legacy-create',
|
|
ok: true,
|
|
result: { tab: { id: 'legacy-tab-1' }, publicationEpoch: 'epoch-1', snapshotVersion: 1 }
|
|
}
|
|
})
|
|
stubRuntimeEnvironmentBridge({ call: runtimeCall })
|
|
|
|
await expect(
|
|
createWebRuntimeSessionTerminal({
|
|
environmentId: ENVIRONMENT_ID,
|
|
worktreeId: WORKTREE_ID,
|
|
agentSessionKind: 'resume',
|
|
launchAgent: 'omp',
|
|
command: "omp --resume '/custom/omp/project/session.jsonl'",
|
|
env: { PI_CODING_AGENT_DIR: '/custom/omp' },
|
|
launchConfig: {
|
|
agentCommand: 'omp',
|
|
agentArgs: '',
|
|
agentEnv: { PI_CODING_AGENT_DIR: '/custom/omp' },
|
|
ompResumeFilePath: '/custom/omp/project/session.jsonl'
|
|
},
|
|
providerSession: { key: 'session_id', id: 'session-1' }
|
|
})
|
|
).resolves.toEqual({ status: 'created' })
|
|
|
|
expect(methods).toEqual(['status.get', 'session.tabs.createTerminal', 'session.tabs.list'])
|
|
expect(runtimeCall.mock.calls[1]?.[0]).toMatchObject({
|
|
params: {
|
|
command: "omp --resume '/custom/omp/project/session.jsonl'",
|
|
env: { PI_CODING_AGENT_DIR: '/custom/omp' },
|
|
launchAgent: 'omp'
|
|
}
|
|
})
|
|
})
|
|
})
|