fix(terminal): make remote agent sessions host-authoritative (#9687)

This commit is contained in:
OrcaWin
2026-07-21 20:51:28 -07:00
committed by GitHub
parent 2a32c5c9a1
commit b232df732b
161 changed files with 16007 additions and 1583 deletions
@@ -0,0 +1,325 @@
import { describe, expect, it, vi } from 'vitest'
import {
AGENT_SESSION_HOST_AUTHORITY_RUNTIME_CAPABILITY,
MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION,
RUNTIME_CAPABILITIES,
RUNTIME_PROTOCOL_VERSION
} from '../../../../shared/protocol-version'
import { AGENT_SESSION_RPC_ERROR_CODES } from '../../../../shared/agent-session-host-authority'
import { AGENT_SESSION_OPERATION_FUTURE_SKEW_MS } from '../../../../shared/agent-session-host-authority'
import type { OrcaRuntimeService } from '../../orca-runtime'
import type { RpcRequest, RpcResponse } from '../core'
import { RpcDispatcher } from '../dispatcher'
import { AGENT_SESSION_METHODS } from './agent-session'
import { TERMINAL_METHODS } from './terminal'
function request(method: string, params: unknown): RpcRequest {
return { id: 'request-1', authToken: 'token', method, params }
}
function terminalResult(disposition: 'created' | 'adopted' | 'replayed' = 'created') {
return {
terminal: {
handle: 'term_1',
worktreeId: 'worktree-1',
title: null
},
disposition
}
}
function runtimeStub() {
return {
getRuntimeId: () => 'runtime-1',
ensureAgentSession: vi.fn().mockResolvedValue(terminalResult()),
createAgentSession: vi.fn().mockResolvedValue(terminalResult())
}
}
describe('agent session RPC methods', () => {
it('dispatches an explicit structured resume without an authoritative command', async () => {
const runtime = runtimeStub()
const dispatcher = new RpcDispatcher({
runtime: runtime as unknown as OrcaRuntimeService,
methods: AGENT_SESSION_METHODS
})
const response = await dispatcher.dispatch(
request('terminal.ensureAgentSession', {
kind: 'explicit',
worktree: 'id:worktree-1',
agent: 'codex',
providerSession: { key: 'session_id', id: 'provider-session-1' },
agentArgs: '--profile review',
launchPreferences: { model: 'gpt-5', effort: 'high' },
presentation: 'focused',
placement: { tabId: 'tab-1', leafId: 'leaf-1' }
})
)
expect(response).toMatchObject({ ok: true, result: { disposition: 'created' } })
expect(runtime.ensureAgentSession).toHaveBeenCalledWith(
{
kind: 'explicit',
worktree: 'id:worktree-1',
agent: 'codex',
providerSession: { key: 'session_id', id: 'provider-session-1' },
agentArgs: '--profile review',
launchPreferences: { model: 'gpt-5', effort: 'high' },
presentation: 'focused',
placement: { tabId: 'tab-1', leafId: 'leaf-1' }
},
{}
)
})
it('keeps automatic authority checkpoint-only', async () => {
const runtime = runtimeStub()
const dispatcher = new RpcDispatcher({
runtime: runtime as unknown as OrcaRuntimeService,
methods: AGENT_SESSION_METHODS
})
const response = await dispatcher.dispatch(
request('terminal.ensureAgentSession', {
kind: 'automatic',
sleepingCheckpointId: 'checkpoint_123456789012345678901',
worktree: 'id:forged',
placement: { tabId: 'forged' }
})
)
expect(response).toMatchObject({ ok: false, error: { code: 'invalid_argument' } })
expect(runtime.ensureAgentSession).not.toHaveBeenCalled()
})
it('rejects mismatched agent/provider identity before runtime mutation', async () => {
const runtime = runtimeStub()
const dispatcher = new RpcDispatcher({
runtime: runtime as unknown as OrcaRuntimeService,
methods: AGENT_SESSION_METHODS
})
const response = await dispatcher.dispatch(
request('terminal.ensureAgentSession', {
kind: 'explicit',
worktree: 'id:worktree-1',
agent: 'antigravity',
providerSession: { key: 'session_id', id: 'provider-session-1' }
})
)
expect(response).toMatchObject({ ok: false, error: { code: 'invalid_argument' } })
expect(runtime.ensureAgentSession).not.toHaveBeenCalled()
})
it('rejects opaque fresh-launch authority and malformed operation IDs', async () => {
const runtime = runtimeStub()
const dispatcher = new RpcDispatcher({
runtime: runtime as unknown as OrcaRuntimeService,
methods: AGENT_SESSION_METHODS
})
const opaque = await dispatcher.dispatch(
request('terminal.createAgentSession', {
clientOperationId: '1752883200000-0123456789abcdef0123456789abcdef',
worktree: 'id:worktree-1',
agent: 'codex',
command: 'codex resume provider-session-1'
})
)
const malformed = await dispatcher.dispatch(
request('terminal.createAgentSession', {
clientOperationId: 'not-time-sortable',
worktree: 'id:worktree-1',
agent: 'codex'
})
)
expect(opaque).toMatchObject({ ok: false, error: { code: 'invalid_argument' } })
expect(malformed).toMatchObject({ ok: false, error: { code: 'invalid_argument' } })
expect(runtime.createAgentSession).not.toHaveBeenCalled()
})
it('preserves legacy agent-bearing terminal.create requests for mixed-version clients', async () => {
const createTerminal = vi.fn().mockResolvedValue({ handle: 'term-1' })
const dedupeTerminalCreate = vi.fn(
async (
_clientIdentity: string,
worktree: string | undefined,
_clientMutationId: string | undefined,
_reconcileExisting: boolean,
run: (worktree: string | undefined, handle: string | undefined) => Promise<unknown>
) => run(worktree, undefined)
)
const runtime = {
getRuntimeId: () => 'runtime-1',
createTerminal,
dedupeTerminalCreate
}
const dispatcher = new RpcDispatcher({
runtime: runtime as unknown as OrcaRuntimeService,
methods: TERMINAL_METHODS
})
const response = await dispatcher.dispatch(
request('terminal.create', {
worktree: 'id:worktree-1',
command: 'codex resume provider-session-1',
launchAgent: 'codex'
})
)
expect(response.ok).toBe(true)
expect(dedupeTerminalCreate).toHaveBeenCalledWith(
'local',
'id:worktree-1',
undefined,
false,
expect.any(Function)
)
expect(createTerminal).toHaveBeenCalledWith('id:worktree-1', {
command: 'codex resume provider-session-1',
startupCommandDelivery: undefined,
env: undefined,
launchAgent: 'codex',
title: undefined,
focus: false,
rendererBacked: false,
activate: false,
presentation: undefined,
tabId: undefined,
leafId: undefined
})
})
it('rejects future-dated operation IDs before runtime mutation', async () => {
const runtime = runtimeStub()
const dispatcher = new RpcDispatcher({
runtime: runtime as unknown as OrcaRuntimeService,
methods: AGENT_SESSION_METHODS
})
const now = 1_752_883_200_000
const dateNow = vi.spyOn(Date, 'now').mockReturnValue(now)
const response = await dispatcher.dispatch(
request('terminal.createAgentSession', {
clientOperationId: `${now + AGENT_SESSION_OPERATION_FUTURE_SKEW_MS + 1}-0123456789abcdef0123456789abcdef`,
worktree: 'id:worktree-1',
agent: 'codex'
})
)
dateNow.mockRestore()
expect(response).toMatchObject({
ok: false,
error: { code: 'agent_session_operation_invalid' }
})
expect(runtime.createAgentSession).not.toHaveBeenCalled()
})
it('passes authenticated caller identity outside the request payload', async () => {
const runtime = runtimeStub()
const dispatcher = new RpcDispatcher({
runtime: runtime as unknown as OrcaRuntimeService,
methods: AGENT_SESSION_METHODS
})
const replies: RpcResponse[] = []
await dispatcher.dispatchStreaming(
request('terminal.createAgentSession', {
clientOperationId: '1752883200000-0123456789abcdef0123456789abcdef',
worktree: 'id:worktree-1',
agent: 'codex',
prompt: 'Fix the race',
promptDelivery: 'draft',
agentArgs: '--profile review',
launchPreferences: { model: 'gpt-5', effort: 'high' },
viewMode: 'chat'
}),
(response) => replies.push(JSON.parse(response) as RpcResponse),
{ clientId: 'authenticated-device', clientKind: 'runtime' }
)
expect(replies).toHaveLength(1)
expect(replies[0]).toMatchObject({ ok: true, result: { disposition: 'created' } })
expect(runtime.createAgentSession).toHaveBeenCalledWith(
{
clientOperationId: '1752883200000-0123456789abcdef0123456789abcdef',
worktree: 'id:worktree-1',
agent: 'codex',
prompt: 'Fix the race',
promptDelivery: 'draft',
agentArgs: '--profile review',
launchPreferences: { model: 'gpt-5', effort: 'high' },
viewMode: 'chat'
},
{ clientId: 'authenticated-device', clientKind: 'runtime' }
)
})
it('rejects draft delivery without a non-empty prompt', async () => {
const runtime = runtimeStub()
const dispatcher = new RpcDispatcher({
runtime: runtime as unknown as OrcaRuntimeService,
methods: AGENT_SESSION_METHODS
})
const response = await dispatcher.dispatch(
request('terminal.createAgentSession', {
clientOperationId: '1752883200000-0123456789abcdef0123456789abcdef',
worktree: 'id:worktree-1',
agent: 'claude',
prompt: ' ',
promptDelivery: 'draft'
})
)
expect(response).toMatchObject({ ok: false, error: { code: 'invalid_argument' } })
expect(runtime.createAgentSession).not.toHaveBeenCalled()
})
it('rejects oversized structured agent arguments before runtime mutation', async () => {
const runtime = runtimeStub()
const dispatcher = new RpcDispatcher({
runtime: runtime as unknown as OrcaRuntimeService,
methods: AGENT_SESSION_METHODS
})
const response = await dispatcher.dispatch(
request('terminal.createAgentSession', {
clientOperationId: '1752883200000-0123456789abcdef0123456789abcdef',
worktree: 'id:worktree-1',
agent: 'codex',
agentArgs: 'a'.repeat(16 * 1024 + 1)
})
)
expect(response).toMatchObject({ ok: false, error: { code: 'invalid_argument' } })
expect(runtime.createAgentSession).not.toHaveBeenCalled()
})
it.each(AGENT_SESSION_RPC_ERROR_CODES)('preserves stable runtime error %s', async (code) => {
const runtime = runtimeStub()
runtime.ensureAgentSession.mockRejectedValueOnce(new Error(code))
const dispatcher = new RpcDispatcher({
runtime: runtime as unknown as OrcaRuntimeService,
methods: AGENT_SESSION_METHODS
})
const response = await dispatcher.dispatch(
request('terminal.ensureAgentSession', {
kind: 'automatic',
sleepingCheckpointId: 'checkpoint_123456789012345678901'
})
)
expect(response).toMatchObject({ ok: false, error: { code } })
})
it('advertises the capability without moving the mixed-version protocol fence', () => {
expect(RUNTIME_PROTOCOL_VERSION).toBe(3)
expect(MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION).toBe(2)
expect(RUNTIME_CAPABILITIES).toContain(AGENT_SESSION_HOST_AUTHORITY_RUNTIME_CAPABILITY)
})
})
@@ -0,0 +1,228 @@
import { z } from 'zod'
import {
getAgentResumeArgv,
hasUnsafeProviderSessionIdChars,
RESUMABLE_TUI_AGENTS
} from '../../../../shared/agent-session-resume'
import type {
RuntimeAgentSessionRpcCaller,
RuntimeCreateAgentSessionRequest,
RuntimeCreateAgentSessionResult,
RuntimeEnsureAgentSessionRequest,
RuntimeEnsureAgentSessionResult
} from '../../../../shared/agent-session-host-authority'
import {
AGENT_SESSION_OPERATION_FUTURE_SKEW_MS,
parseAgentSessionOperationTimestamp
} from '../../../../shared/agent-session-host-authority'
import { isTuiAgent } from '../../../../shared/tui-agent-config'
import { isValidTerminalTabId } from '../../../../shared/terminal-tab-id'
import type { OrcaRuntimeService } from '../../orca-runtime'
import { defineMethod, type RpcAnyMethod } from '../core'
const MAX_WORKTREE_SELECTOR_LENGTH = 32_768
const MAX_TRANSCRIPT_PATH_BYTES = 16 * 1024
const MAX_PROMPT_BYTES = 256 * 1024
const MAX_AGENT_ARGS_BYTES = 16 * 1024
const MAX_LAUNCH_PREFERENCE_LENGTH = 512
const StrictNonEmptyString = (max: number, message: string) =>
z
.string()
.min(1, message)
.max(max, message)
.refine((value) => value === value.trim(), `${message}; surrounding whitespace is invalid`)
const WorktreeSelector = StrictNonEmptyString(
MAX_WORKTREE_SELECTOR_LENGTH,
'Invalid worktree selector'
)
const Presentation = z.enum(['background', 'focused'])
const Placement = z
.object({
tabId: z
.string()
.min(1)
.max(512)
.refine(isValidTerminalTabId, 'Invalid terminal tab ID')
.optional(),
leafId: z.string().min(1).max(128).optional()
})
.strict()
.refine((value) => value.tabId !== undefined || value.leafId !== undefined, {
message: 'Placement must include a tab or leaf ID'
})
const LaunchPreferences = z
.object({
model: StrictNonEmptyString(
MAX_LAUNCH_PREFERENCE_LENGTH,
'Invalid model preference'
).optional(),
effort: StrictNonEmptyString(
MAX_LAUNCH_PREFERENCE_LENGTH,
'Invalid effort preference'
).optional(),
mode: StrictNonEmptyString(MAX_LAUNCH_PREFERENCE_LENGTH, 'Invalid mode preference').optional()
})
.strict()
const PromptDelivery = z.enum(['auto-submit', 'draft'])
const AgentArgs = z
.string()
.refine(
(value) => Buffer.byteLength(value, 'utf8') <= MAX_AGENT_ARGS_BYTES,
'Agent arguments are too large'
)
.nullable()
const ProviderSession = z
.object({
key: z.enum(['session_id', 'conversation_id']),
id: StrictNonEmptyString(512, 'Invalid provider session ID').refine(
(value) => !value.startsWith('-') && !hasUnsafeProviderSessionIdChars(value),
'Invalid provider session ID'
),
transcriptPath: z
.string()
.min(1)
.refine((value) => value === value.trim(), 'Invalid transcript path')
.refine(
(value) =>
!hasUnsafeProviderSessionIdChars(value) &&
Buffer.byteLength(value, 'utf8') <= MAX_TRANSCRIPT_PATH_BYTES,
'Invalid transcript path'
)
.optional()
})
.strict()
const AutomaticEnsure = z
.object({
kind: z.literal('automatic'),
sleepingCheckpointId: z
.string()
.min(32)
.max(128)
.regex(/^[A-Za-z0-9_-]+$/),
presentation: Presentation.optional()
})
.strict()
const ExplicitEnsure = z
.object({
kind: z.literal('explicit'),
worktree: WorktreeSelector,
agent: z.enum(RESUMABLE_TUI_AGENTS),
providerSession: ProviderSession,
agentArgs: AgentArgs.optional(),
launchPreferences: LaunchPreferences.optional(),
presentation: Presentation.optional(),
placement: Placement.optional()
})
.strict()
.superRefine((value, context) => {
if (getAgentResumeArgv(value.agent, value.providerSession) === null) {
context.addIssue({
code: z.ZodIssueCode.custom,
path: ['providerSession'],
message: 'Provider session is not resumable for this agent'
})
}
})
export const EnsureAgentSessionParams: z.ZodType<RuntimeEnsureAgentSessionRequest> =
z.discriminatedUnion('kind', [AutomaticEnsure, ExplicitEnsure])
export const CreateAgentSessionParams: z.ZodType<RuntimeCreateAgentSessionRequest> = z
.object({
clientOperationId: z
.string()
.refine(
(value) => parseAgentSessionOperationTimestamp(value) !== null,
'Invalid agent operation ID'
),
worktree: WorktreeSelector,
agent: z.string().refine(isTuiAgent, 'Unknown agent preset'),
prompt: z
.string()
.refine(
(value) => Buffer.byteLength(value, 'utf8') <= MAX_PROMPT_BYTES,
'Prompt is too large'
)
.optional(),
promptDelivery: PromptDelivery.optional(),
agentArgs: AgentArgs.optional(),
launchPreferences: LaunchPreferences.optional(),
startupCwd: z.string().min(1).max(MAX_WORKTREE_SELECTOR_LENGTH).optional(),
presentation: Presentation.optional(),
placement: Placement.optional(),
viewMode: z.enum(['terminal', 'chat']).optional()
})
.strict()
.superRefine((value, context) => {
if (value.promptDelivery === 'draft' && !value.prompt?.trim()) {
context.addIssue({
code: z.ZodIssueCode.custom,
path: ['prompt'],
message: 'Draft delivery requires a non-empty prompt'
})
}
})
type AgentSessionRuntime = OrcaRuntimeService & {
ensureAgentSession(
request: RuntimeEnsureAgentSessionRequest,
caller?: RuntimeAgentSessionRpcCaller
): Promise<RuntimeEnsureAgentSessionResult>
createAgentSession(
request: RuntimeCreateAgentSessionRequest,
caller?: RuntimeAgentSessionRpcCaller
): Promise<RuntimeCreateAgentSessionResult>
}
function callerContext(
clientId: string | undefined,
clientKind: 'mobile' | 'runtime' | undefined,
signal: AbortSignal | undefined
): RuntimeAgentSessionRpcCaller {
return {
...(clientId !== undefined ? { clientId } : {}),
...(clientKind !== undefined ? { clientKind } : {}),
...(signal ? { signal } : {})
}
}
function assertOperationTimestampWithinFutureSkew(clientOperationId: string): void {
const timestamp = parseAgentSessionOperationTimestamp(clientOperationId)
if (timestamp === null || timestamp > Date.now() + AGENT_SESSION_OPERATION_FUTURE_SKEW_MS) {
// Why: a future-dated ID could look new again after its idempotency tombstone is collected.
throw new Error('agent_session_operation_invalid')
}
}
export const AGENT_SESSION_METHODS: RpcAnyMethod[] = [
defineMethod({
name: 'terminal.ensureAgentSession',
params: EnsureAgentSessionParams,
handler: (params, { runtime, pairedDeviceId, clientId, clientKind, signal }) =>
(runtime as AgentSessionRuntime).ensureAgentSession(
params,
callerContext(pairedDeviceId ?? clientId, clientKind, signal)
)
}),
defineMethod({
name: 'terminal.createAgentSession',
params: CreateAgentSessionParams,
handler: (params, { runtime, pairedDeviceId, clientId, clientKind, signal }) => {
assertOperationTimestampWithinFutureSkew(params.clientOperationId)
return (runtime as AgentSessionRuntime).createAgentSession(
params,
callerContext(pairedDeviceId ?? clientId, clientKind, signal)
)
}
})
]
+2
View File
@@ -35,6 +35,7 @@ import { CLIPBOARD_METHODS } from './clipboard'
import { HOST_CAPABILITY_METHODS } from './host-capabilities'
import { EMULATOR_METHODS } from './emulator'
import { PAIRING_METHODS } from './pairing'
import { AGENT_SESSION_METHODS } from './agent-session'
// Why: a flat manifest keeps registration order explicit and provides one
// grep-point for "what methods does the RPC server expose?" — useful when
@@ -45,6 +46,7 @@ export const ALL_RPC_METHODS: readonly RpcAnyMethod[] = [
...AUTOMATION_METHODS,
...REPO_METHODS,
...WORKTREE_METHODS,
...AGENT_SESSION_METHODS,
...TERMINAL_METHODS,
...BROWSER_CORE_METHODS,
...BROWSER_SCREENCAST_METHODS,
@@ -10,7 +10,7 @@ export const SESSION_TAB_CLOSE_METHODS: RpcAnyMethod[] = [
withSpan(
'runtime.session-tabs.close',
async (span) => {
if (!params.reason && context.clientKind !== 'mobile') {
if (!params.reason && context.clientKind === undefined) {
const result = await context.runtime.refuseUnattributedMobileSessionTabClose(
params.worktree,
params.tabId
@@ -35,7 +35,8 @@ export const SESSION_TAB_CLOSE_METHODS: RpcAnyMethod[] = [
attribution: 'session-tab-close',
origin: context.clientKind ?? 'in-process',
closeReason:
params.reason ?? (context.clientKind === 'mobile' ? 'legacy-mobile-user' : 'missing'),
params.reason ??
(context.clientKind ? `legacy-${context.clientKind}-user` : 'missing'),
connectionGeneration: context.connectionId ?? 'in-process',
requestId: context.requestId ?? 'in-process'
}
@@ -28,8 +28,8 @@ export const ActivateTab = WorktreeTabSelector.extend({
})
export const CloseTab = ActivateTab.extend({
// Why: optional so legacy clients still validate; policy conservatively
// attributes only authenticated mobile callers as user intent.
// Why: optional preserves authenticated legacy user closes; lifecycle intent
// uses the additive evidence-bearing method instead.
reason: z.literal('user').optional()
})
@@ -136,6 +136,28 @@ describe('session tab RPC methods', () => {
expect(runtime.refuseUnattributedMobileSessionTabClose).not.toHaveBeenCalled()
})
it('preserves reasonless explicit closes from authenticated legacy runtime clients', async () => {
const runtime = {
getRuntimeId: () => 'test-runtime',
refuseUnattributedMobileSessionTabClose: vi.fn(),
closeMobileSessionTab: vi.fn().mockResolvedValue({ closed: true })
} as unknown as OrcaRuntimeService
const dispatcher = new RpcDispatcher({ runtime, methods: SESSION_TAB_METHODS })
const replies: string[] = []
await dispatcher.dispatchStreaming(
makeRequest('session.tabs.close', { worktree: 'id:wt-1', tabId: 'tab-1' }),
(response) => replies.push(response),
{ clientKind: 'runtime', pairedDeviceId: 'legacy-runtime' }
)
expect(replies).toHaveLength(1)
expect(runtime.closeMobileSessionTab).toHaveBeenCalledWith('id:wt-1', 'tab-1', {
reason: 'user'
})
expect(runtime.refuseUnattributedMobileSessionTabClose).not.toHaveBeenCalled()
})
it.each(['pty-exit', 'cleanup'] as const)(
'rejects %s on the legacy close endpoint before host adjudication',
async (reason) => {
@@ -262,7 +284,7 @@ describe('session tab RPC methods', () => {
})
})
it('dispatches terminal creation with the requested tab group', async () => {
it('dispatches ordinary terminal creation with the requested tab group', async () => {
const runtime = {
getRuntimeId: () => 'test-runtime',
createMobileSessionTerminal: vi.fn().mockResolvedValue({
@@ -321,7 +343,9 @@ describe('session tab RPC methods', () => {
activate: true,
select: undefined,
clientNavigationId: undefined,
navigation: 'all'
navigation: 'all',
clientMutationId: undefined,
signal: undefined
})
})
@@ -357,7 +381,7 @@ describe('session tab RPC methods', () => {
)
})
it('dispatches terminal creation with a requested agent preset', async () => {
it('preserves legacy agent creation for mixed-version clients', async () => {
const runtime = {
getRuntimeId: () => 'test-runtime',
createMobileSessionTerminal: vi.fn().mockResolvedValue({
@@ -390,13 +414,16 @@ describe('session tab RPC methods', () => {
afterTabId: undefined,
targetGroupId: undefined,
command: undefined,
cwd: undefined,
startupCommandDelivery: undefined,
agent: 'codex',
agentPrompt: 'Review this diff',
activate: undefined,
select: undefined,
clientNavigationId: undefined,
navigation: 'all'
navigation: 'all',
clientMutationId: undefined,
signal: undefined
})
})