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
114 changes: 114 additions & 0 deletions src/main/runtime/created-mobile-session-tab-caller-selection.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/**
* A tab a create just published becomes one paired client's selection: the shared snapshot the host
* and unselected clients follow stays put, and no PTY work runs — unlike a tap, which may respawn.
*/
import { expect, it, vi } from 'vitest'
import { parsePaneKey } from '../../shared/stable-pane-id'
import type { RuntimeMobileSessionTabsResult } from '../../shared/runtime-types'

// Fragments stay side-effect ordered: mocks, then lifecycle, then fixtures.
const { OrcaRuntimeService } = await import('./orca-runtime-test-mocks.spec')
await import('./orca-runtime-test-lifecycle.spec')
const { store, TEST_WORKTREE_ID, HEADLESS_LEAF_ID } =
await import('./orca-runtime-test-fixtures.spec')
const { makePendingAgentTabActivationRuntime } =
await import('./orca-runtime-test-scenario-builders.spec')

const WT = TEST_WORKTREE_ID

function pairedRuntime() {
let next = 0
const spawn = vi.fn(async () => ({ id: `pty-${++next}` }))
const runtime = new OrcaRuntimeService(store)
runtime.setPtyController({
spawn,
write: () => true,
kill: () => true,
getForegroundProcess: async () => null
})
const caller: RuntimeMobileSessionTabsResult[] = []
runtime.onMobileSessionTabsChanged((snapshot) => caller.push(snapshot), 'device-caller')
// A subscribed second device: selection that fans out to live clients would move it too.
runtime.onMobileSessionTabsChanged(() => {}, 'device-bystander')
return { runtime, spawn, caller }
}

async function createPane(runtime: InstanceType<typeof OrcaRuntimeService>) {
const created = await runtime.createTerminal(`id:${WT}`)
const pane = parsePaneKey(created.paneKey ?? '')
if (!pane) {
throw new Error(`createTerminal returned no pane key: ${created.paneKey}`)
}
return { tabId: pane.tabId, leafId: pane.leafId, id: `${pane.tabId}::${pane.leafId}` }
}

it('selects a launched terminal for the caller only, without spawning again', async () => {
const { runtime, spawn, caller } = pairedRuntime()
const first = await createPane(runtime)
const launched = await createPane(runtime)
expect((await runtime.listMobileSessionTabs(`id:${WT}`)).activeTabId).toBe(first.id)

expect(runtime.selectCreatedMobileSessionTabForClient(WT, launched, 'device-caller')).toBe(true)

expect(caller.at(-1)?.activeTabId).toBe(launched.id)
expect((await runtime.listMobileSessionTabs(`id:${WT}`, 'device-caller')).activeTabId).toBe(
launched.id
)
expect((await runtime.listMobileSessionTabs(`id:${WT}`)).activeTabId).toBe(first.id)
expect((await runtime.listMobileSessionTabs(`id:${WT}`, 'device-bystander')).activeTabId).toBe(
first.id
)
expect(spawn).toHaveBeenCalledTimes(2)
})

it('selects a launched chat by its session for the caller only', async () => {
const { runtime, caller } = pairedRuntime()
const first = await createPane(runtime)
await runtime.publishStructuredAgentSessionTab({
workspaceId: WT,
sessionId: 'sess-1',
agent: 'claude',
activate: false
})

expect(
runtime.selectCreatedMobileSessionTabForClient(WT, { sessionId: 'sess-1' }, 'device-caller')
).toBe(true)

expect(caller.at(-1)?.activeTabId).toBe('agent-session:sess-1')
expect((await runtime.listMobileSessionTabs(`id:${WT}`)).activeTabId).toBe(first.id)
expect((await runtime.listMobileSessionTabs(`id:${WT}`, 'device-bystander')).activeTabId).toBe(
first.id
)
})

it('reports a tab that is not published instead of selecting something else', async () => {
const { runtime, caller } = pairedRuntime()
await createPane(runtime)
const before = caller.length

expect(
runtime.selectCreatedMobileSessionTabForClient(WT, { sessionId: 'missing' }, 'device-caller')
).toBe(false)
expect(caller).toHaveLength(before)
})

it('never materializes a pane that is not ready, as a tap would', async () => {
const { runtime, spawn } = makePendingAgentTabActivationRuntime()
const listed = await runtime.listMobileSessionTabs(`id:${WT}`)
expect(listed.tabs[0]).toMatchObject({ launchAgent: 'claude', status: 'pending-handle' })

expect(
runtime.selectCreatedMobileSessionTabForClient(
WT,
{ tabId: 'host-tab', leafId: HEADLESS_LEAF_ID },
'device-caller'
)
).toBe(true)

const selected = await runtime.listMobileSessionTabs(`id:${WT}`, 'device-caller')
expect(selected.activeTabId).toBe(`host-tab::${HEADLESS_LEAF_ID}`)
// Why wait: a tap's respawn lands several awaits later, so an immediate check cannot see one.
await new Promise((resolve) => setTimeout(resolve, 200))
expect(spawn).not.toHaveBeenCalled()
})
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,31 @@ export class OrcaRuntimeWithApplyMobileSessionTabNavigation extends OrcaRuntimeW
return snapshot
}

/**
* Records a tab a create just published as one paired client's selection, as a create does for
* its own tab. Not the tap path: a tap is a wake gesture that may respawn a non-ready pane.
* Returns false when the tab is not in the snapshot.
*/
selectCreatedMobileSessionTabForClient(
worktreeId: string,
surface: { tabId: string; leafId: string } | { sessionId: string },
clientNavigationId: string
): boolean {
const snapshot = this.getMobileSessionTabsForWorktree(worktreeId)
const tab = snapshot.tabs.find((candidate) =>
'sessionId' in surface
? candidate.type === 'agent-session' && candidate.sessionId === surface.sessionId
: candidate.type === 'terminal' &&
candidate.parentTabId === surface.tabId &&
candidate.leafId === surface.leafId
)
if (!tab) {
return false
}
this.applyMobileSessionTabNavigation(snapshot, tab.id, 'caller', clientNavigationId)
return true
}

/**
* Whether persistence proves this pane's PTY was deliberately taken down and parked
* (workspace sleep or completed-agent hibernation) rather than lost and awaiting reconnect.
Expand Down
181 changes: 181 additions & 0 deletions src/main/runtime/rpc/methods/agent-launch-caller-selection.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
/**
* A launch from a paired client moves that client's view to the new tab and nobody else's: the view
* intent belongs to the connection that asked. In-process callers and workspace-creating launches
* keep today's behaviour.
*/

import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { AgentSessionRecordStore } from '../../agent-session-record-store'
import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry'
import type { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-host'
import type { RpcContext } from '../core'
import {
CAPABLE_CLIENT,
STRUCTURED_PREFERENCE,
methodNamed,
rpcContext,
runtimeStub,
type AgentLaunchRuntimeStub
} from './agent-launch.test-fixture'

const createStructuredSession = vi.hoisted(() => vi.fn())
vi.mock('./structured-agent-session-create', () => ({
createStructuredAgentSessionForWorktree: createStructuredSession
}))

const { AGENT_LAUNCH_METHODS } = await import('./agent-launch')
const AGENT_LAUNCH = methodNamed(AGENT_LAUNCH_METHODS, 'agent.launch')
const AGENT_LAUNCH_REPLAY = methodNamed(AGENT_LAUNCH_METHODS, 'agent.launchReplay')

const TAB_ID = '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
const LEAF_ID = '3f2504e0-4f89-41d3-9a0c-0305e82c3301'
const PANE_KEY = `${TAB_ID}:${LEAF_ID}`
const EXISTING_LAUNCH = { agent: 'claude', target: { kind: 'existing', worktree: 'id:wt-7' } }
const CREATE_LAUNCH = {
agent: 'claude',
target: { kind: 'create-worktree', create: { repo: 'id:repo-1', name: 'task' } }
}
const CALLER = 'device-1'

function selectionRuntime(options: Parameters<typeof runtimeStub>[0]) {
return Object.assign(runtimeStub(options), {
selectCreatedMobileSessionTabForClient: vi.fn(() => true)
})
}

async function launch(
params: unknown,
runtime: AgentLaunchRuntimeStub,
context: Partial<RpcContext> = CAPABLE_CLIENT
) {
return AGENT_LAUNCH.handler(AGENT_LAUNCH.params.parse(params), rpcContext(runtime, context))
}

function chatActivation(): unknown {
return createStructuredSession.mock.calls[0]?.[0]?.activate
}

beforeEach(() => {
createStructuredSession
.mockReset()
.mockResolvedValue({ ok: true, value: { sessionId: 'sess-1' } })
})

describe('a paired client launching into an existing workspace', () => {
it("selects the new terminal as that client's tab only", async () => {
const runtime = selectionRuntime({ settings: {}, terminalPaneKey: PANE_KEY })

await launch(EXISTING_LAUNCH, runtime)

expect(runtime.selectCreatedMobileSessionTabForClient).toHaveBeenCalledExactlyOnceWith(
'wt-7',
expect.objectContaining({ tabId: TAB_ID, leafId: LEAF_ID }),
CALLER
)
})

it('publishes the chat without activating it for everyone, then selects it by session for the caller', async () => {
const runtime = selectionRuntime({ settings: STRUCTURED_PREFERENCE })

const result = await launch(EXISTING_LAUNCH, runtime)

expect(result.outcome.kind).toBe('structured')
expect(chatActivation()).toBe(false)
expect(runtime.selectCreatedMobileSessionTabForClient).toHaveBeenCalledExactlyOnceWith(
'wt-7',
{ sessionId: 'sess-1' },
CALLER
)
})

it('still reports the launch when selecting its tab fails', async () => {
const runtime = selectionRuntime({ settings: {}, terminalPaneKey: PANE_KEY })
runtime.selectCreatedMobileSessionTabForClient.mockImplementationOnce(() => {
throw new Error('selection store unavailable')
})
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})

const result = await launch(EXISTING_LAUNCH, runtime)

expect(result.outcome).toMatchObject({ kind: 'terminal', handle: 'term_1' })
warn.mockRestore()
})

it('selects nothing when the runtime reported no pane for the terminal', async () => {
const runtime = selectionRuntime({ settings: {} })

await launch(EXISTING_LAUNCH, runtime)

expect(runtime.selectCreatedMobileSessionTabForClient).not.toHaveBeenCalled()
})
})

describe('launches that keep the host-wide behaviour', () => {
it('an in-process caller activates the chat and selects nothing per client', async () => {
const runtime = selectionRuntime({ settings: STRUCTURED_PREFERENCE })

await launch(EXISTING_LAUNCH, runtime, {})

expect(chatActivation()).toBe(true)
expect(runtime.selectCreatedMobileSessionTabForClient).not.toHaveBeenCalled()
})

it("the host's own desktop window, a runtime client with no paired device, still activates the chat", async () => {
const runtime = selectionRuntime({ settings: STRUCTURED_PREFERENCE })

await launch(EXISTING_LAUNCH, runtime, {
...CAPABLE_CLIENT,
clientKind: 'runtime',
pairedDeviceId: undefined
})

expect(chatActivation()).toBe(true)
expect(runtime.selectCreatedMobileSessionTabForClient).not.toHaveBeenCalled()
})

it('a workspace-creating launch from a paired client keeps the create navigation', async () => {
const runtime = selectionRuntime({ settings: STRUCTURED_PREFERENCE })

await launch(CREATE_LAUNCH, runtime)

expect(chatActivation()).toBe(true)
expect(runtime.selectCreatedMobileSessionTabForClient).not.toHaveBeenCalled()
})
})

describe('a replayed launch', () => {
// The ledger admits against `Date.now()`, so the id must be dated now.
const OPERATION_ID = `${Date.now()}-000000000000000000000000000000dd`
let directory: string

beforeEach(async () => {
directory = await mkdtemp(join(tmpdir(), 'orca-agent-launch-caller-'))
const store = await AgentSessionRecordStore.open({ directory, hostId: 'local' })
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: `deps.store` is the only member `agent.launch` reads, and a member it omits throws on call.
setStructuredAgentSessionHost({ deps: { store } } as unknown as StructuredAgentSessionHost)
})

afterEach(async () => {
setStructuredAgentSessionHost(null)
await rm(directory, { recursive: true, force: true })
})

it('answers from the record without moving the caller again', async () => {
const params = AGENT_LAUNCH_REPLAY.params.parse({
...EXISTING_LAUNCH,
operationId: OPERATION_ID
})
const first = selectionRuntime({ settings: {}, terminalPaneKey: PANE_KEY })
await AGENT_LAUNCH_REPLAY.handler(params, rpcContext(first, CAPABLE_CLIENT))
expect(first.selectCreatedMobileSessionTabForClient).toHaveBeenCalledOnce()

const replay = selectionRuntime({ settings: {}, terminalPaneKey: PANE_KEY })
await AGENT_LAUNCH_REPLAY.handler(params, rpcContext(replay, CAPABLE_CLIENT))

expect(replay.createTerminal).not.toHaveBeenCalled()
expect(replay.selectCreatedMobileSessionTabForClient).not.toHaveBeenCalled()
})
})
57 changes: 57 additions & 0 deletions src/main/runtime/rpc/methods/agent-launch-caller-selection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/**
* Which view a launch moves: the requesting connection's, never the host's or another client's.
*
* A paired client (a phone, or a desktop client of a remote server) that launches into an existing
* workspace gets the new tab as its own selection, recorded the way `session.tabs.createTerminal`
* selects the tab it creates for its caller. In-process callers keep today's behaviour, and a
* launch that creates its workspace keeps `worktree.create`'s navigation, whose host activation is
* what runs the new workspace's setup.
*/

import type { AgentLaunchResult, AgentLaunchTarget } from '../../../../shared/agent-launch-intent'
import { parsePaneKey } from '../../../../shared/stable-pane-id'
import type { OrcaRuntimeService } from '../../orca-runtime'
import type { RpcContext } from '../core'

/** The paired client whose view this launch should move, or null when it moves the host's. */
export function agentLaunchCallerNavigationId(
target: AgentLaunchTarget,
context: Pick<RpcContext, 'clientKind' | 'pairedDeviceId'>
): string | null {
if (target.kind !== 'existing' || context.clientKind === undefined) {
return null
}
return context.pairedDeviceId?.trim() || null
}

/** Bookkeeping, never a gate: the agent already runs, so a failure here only leaves the view as it was. */
export function selectAgentLaunchTabForCaller(
runtime: Pick<OrcaRuntimeService, 'selectCreatedMobileSessionTabForClient'>,
result: AgentLaunchResult,
clientNavigationId: string
): void {
const { outcome } = result
// Found by pane or session, never by a predicted tab id.
const surface =
outcome.kind === 'terminal'
? outcome.paneKey
? parsePaneKey(outcome.paneKey)
: null
: { sessionId: outcome.sessionId }
if (!surface) {
return
}
try {
if (
!runtime.selectCreatedMobileSessionTabForClient(
result.worktreeId,
surface,
clientNavigationId
)
) {
console.warn('[agent-launch] the launch ran; its tab was not published to select')
}
} catch (error) {
console.warn('[agent-launch] the launch ran; selecting its tab for the caller did not', error)
}
}
Loading
Loading