Fix paste ownership, input bounds, and IPC validation

Supersedes #5745, #5746, and #5747.
This commit is contained in:
Jinwoo Hong
2026-06-19 17:14:55 -07:00
committed by GitHub
parent a5920b2183
commit 972078f2c4
592 changed files with 33303 additions and 3737 deletions
+165 -2
View File
@@ -17,6 +17,7 @@ import type {
WorkspaceSessionState
} from '../../shared/types'
import { AGENT_STATUS_STALE_AFTER_MS } from '../../shared/agent-status-types'
import { MAX_OSC_TITLE_CHARS } from '../../shared/agent-detection'
import {
addWorktree,
assertWorktreeCleanForRemoval,
@@ -45,6 +46,12 @@ import {
type RuntimeTerminalAgentStatusEvent
} from './orca-runtime'
import type { RuntimeMobileSessionTabsResult } from '../../shared/runtime-types'
import {
TERMINAL_INPUT_CHUNK_MAX_BYTES,
TERMINAL_INPUT_MAX_BYTES,
TERMINAL_INPUT_TOO_LARGE_ERROR
} from '../../shared/terminal-input'
import { CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS } from '../../shared/clipboard-text'
import {
registerSshFilesystemProvider,
unregisterSshFilesystemProvider
@@ -6213,6 +6220,49 @@ describe('OrcaRuntimeService', () => {
})
})
it('resolves Antigravity ready prompts with newline-heavy pasted tails without splitting', async () => {
const runtime = new OrcaRuntimeService(store)
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }),
write: () => true,
kill: () => true,
getForegroundProcess: async () => null
})
const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`)
let pastedTail = ''
for (let index = 0; index < 90; index += 1) {
pastedTail += `${'pasted text '.repeat(25)}${index}\n`
}
const splitSpy = vi.spyOn(String.prototype, 'split')
runtime.onPtyData(
'pty-bg',
[
'Antigravity CLI 1.0.3\n',
'user@example.com (Antigravity Business)\n',
pastedTail,
'Gemini 4 Experimental (High)\n',
'~/orca/workspaces/orca/agy-dispatch-issue\n',
'>'
].join(''),
Date.now()
)
await expect(
runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 1_000 })
).resolves.toMatchObject({
handle,
condition: 'tui-idle',
satisfied: true,
status: 'running'
})
const splitReadyTail = splitSpy.mock.contexts.some((context) => {
const value = typeof context === 'string' ? context : String(context)
return value.includes('antigravity cli') && value.includes('pasted text pasted text')
})
expect(splitReadyTail).toBe(false)
})
it('resolves tui-idle from an Antigravity prompt before the model line', async () => {
const runtime = new OrcaRuntimeService(store)
runtime.setPtyController({
@@ -6634,6 +6684,87 @@ describe('OrcaRuntimeService', () => {
expect(writes).toEqual(['continue', '\r'])
})
it('chunks large terminal.send text before provider writes', async () => {
const writes: string[] = []
const runtime = new OrcaRuntimeService(store)
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }),
write: (_ptyId, data) => {
writes.push(data)
return true
},
kill: () => true,
getForegroundProcess: async () => null
})
const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`)
const text = ['x'.repeat(TERMINAL_INPUT_CHUNK_MAX_BYTES), 'tail'].join('')
const result = await runtime.sendTerminal(handle, { text })
expect(result).toMatchObject({
handle,
accepted: true,
bytesWritten: Buffer.byteLength(text, 'utf8')
})
expect(writes).toEqual(['x'.repeat(TERMINAL_INPUT_CHUNK_MAX_BYTES), 'tail'])
})
it('yields while validating accepted large terminal.send text before provider writes', async () => {
const writes: string[] = []
const runtime = new OrcaRuntimeService(store)
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }),
write: (_ptyId, data) => {
writes.push(data)
return true
},
kill: () => true,
getForegroundProcess: async () => null
})
const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`)
const text = 'é'.repeat(CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS + 1)
vi.useFakeTimers()
try {
const sendPromise = runtime.sendTerminal(handle, { text })
expect(writes).toEqual([])
await vi.runAllTimersAsync()
const result = await sendPromise
expect(result).toMatchObject({
handle,
accepted: true,
bytesWritten: Buffer.byteLength(text, 'utf8')
})
expect(writes.length).toBeGreaterThan(1)
expect(writes.join('')).toBe(text)
} finally {
vi.useRealTimers()
}
})
it('rejects oversized terminal.send text before provider writes', async () => {
const writes: string[] = []
const runtime = new OrcaRuntimeService(store)
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }),
write: (_ptyId, data) => {
writes.push(data)
return true
},
kill: () => true,
getForegroundProcess: async () => null
})
const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`)
await expect(
runtime.sendTerminal(handle, { text: 'x'.repeat(TERMINAL_INPUT_MAX_BYTES + 1) })
).rejects.toThrow(TERMINAL_INPUT_TOO_LARGE_ERROR)
expect(writes).toEqual([])
})
it('reveals a background terminal session when focusing its handle', async () => {
const revealTerminalSession = vi.fn().mockResolvedValue({ tabId: 'tab-adopted' })
const runtime = new OrcaRuntimeService(store)
@@ -7367,7 +7498,7 @@ describe('OrcaRuntimeService', () => {
ptysById: Map<string, { lastOscTitle: string | null }>
}
).ptysById.get('pty-1')
expect(pty?.lastOscTitle).toBe('x'.repeat(4092))
expect(pty?.lastOscTitle).toBe('x'.repeat(MAX_OSC_TITLE_CHARS))
})
it('does not retain split ST-terminated string controls as preview text', async () => {
@@ -7465,6 +7596,37 @@ describe('OrcaRuntimeService', () => {
expect(retained).not.toContain('49m')
})
it('normalizes large CRLF-heavy terminal chunks without regex replacement or line splits', async () => {
const replaceSpy = vi.spyOn(String.prototype, 'replace')
const splitSpy = vi.spyOn(String.prototype, 'split')
const runtime = new OrcaRuntimeService(store)
syncSinglePty(runtime)
const [terminal] = (await runtime.listTerminals()).terminals
runtime.onPtyData('pty-1', `${'line\r\n'.repeat(10_000)}tail`, 100)
const read = await runtime.readTerminal(terminal.handle, { limit: 5 })
const usedCrlfReplace = replaceSpy.mock.calls.some(
([pattern], index) =>
pattern instanceof RegExp &&
pattern.source === '\\r\\n' &&
typeof replaceSpy.mock.contexts[index] === 'string' &&
replaceSpy.mock.contexts[index].length > 10_000
)
const usedLineSplit = splitSpy.mock.calls.some(([separator], index) => {
const splitSeparator = separator as unknown
return (
(splitSeparator === '\n' ||
(splitSeparator instanceof RegExp && splitSeparator.source === '\\r?\\n')) &&
typeof splitSpy.mock.contexts[index] === 'string' &&
splitSpy.mock.contexts[index].length > 10_000
)
})
expect(read.tail.at(-1)).toBe('tail')
expect(usedCrlfReplace).toBe(false)
expect(usedLineSplit).toBe(false)
})
it('bounds retained partial terminal output before preview reads', async () => {
const runtime = new OrcaRuntimeService(store)
@@ -18487,7 +18649,8 @@ describe('OrcaRuntimeService', () => {
expect(invalidateAuthorizedRootsCacheMock).toHaveBeenCalled()
expect(notifier.worktreesChanged).toHaveBeenCalledWith(TEST_REPO_ID)
} finally {
await rm(parentDir, { recursive: true, force: true })
// Why: Windows can keep a just-inspected git admin dir busy briefly.
await rm(parentDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 })
}
})
+130 -38
View File
@@ -21,6 +21,11 @@ import {
createAgentStatusOscProcessor,
type ProcessedAgentStatusChunk
} from '../../shared/agent-status-osc'
import {
isTerminalInputTooLargeWithYield,
TERMINAL_INPUT_TOO_LARGE_ERROR,
iterateTerminalInputChunks
} from '../../shared/terminal-input'
import { gitExecFileAsync, wslAwareSpawn } from '../git/runner'
import {
cleanupClaimedCloneTarget,
@@ -7888,6 +7893,7 @@ export class OrcaRuntimeService {
if (payload === null) {
throw new Error('invalid_terminal_send')
}
await assertTerminalInputWithinLimitWithYield(action.text)
await this.writeTerminalAction(pty.pty.ptyId, action, payload)
return {
handle,
@@ -7904,6 +7910,7 @@ export class OrcaRuntimeService {
if (payload === null) {
throw new Error('invalid_terminal_send')
}
await assertTerminalInputWithinLimitWithYield(action.text)
await this.writeTerminalAction(leaf.ptyId, action, payload)
@@ -7919,24 +7926,27 @@ export class OrcaRuntimeService {
action: { text?: string; enter?: boolean; interrupt?: boolean },
payload: string
): Promise<void> {
// Why: TUI apps (Claude Code, etc.) treat a single large write as a paste
// event. Keep Enter/interrupt as a second write for both visible and
// background PTYs so CLI automation behaves the same either way.
// Why: direct terminal.send can carry paste-sized text from RPC/mobile
// clients; chunk text before PTY/ConPTY while preserving suffix separation.
const hasText = typeof action.text === 'string' && action.text.length > 0
const hasSuffix = action.enter || action.interrupt
if (hasText && hasSuffix) {
const textWrote = this.ptyController?.write(ptyId, action.text!) ?? false
if (!textWrote) {
throw new Error('terminal_not_writable')
}
if (hasText) {
await this.writeTerminalInputChunks(ptyId, action.text!)
}
if (hasSuffix) {
const suffix = (action.enter ? '\r' : '') + (action.interrupt ? '\x03' : '')
await new Promise((resolve) => setTimeout(resolve, 500))
if (hasText) {
await new Promise((resolve) => setTimeout(resolve, 500))
}
const suffixWrote = this.ptyController?.write(ptyId, suffix) ?? false
if (!suffixWrote) {
throw new Error('terminal_not_writable')
}
return
}
if (hasText) {
return
}
const wrote = this.ptyController?.write(ptyId, payload) ?? false
if (!wrote) {
@@ -7944,6 +7954,21 @@ export class OrcaRuntimeService {
}
}
private async writeTerminalInputChunks(ptyId: string, text: string): Promise<void> {
const chunks = iterateTerminalInputChunks(text)
let chunk = chunks.next()
while (!chunk.done) {
const wrote = this.ptyController?.write(ptyId, chunk.value) ?? false
if (!wrote) {
throw new Error('terminal_not_writable')
}
chunk = chunks.next()
if (!chunk.done) {
await new Promise((resolve) => setTimeout(resolve, 0))
}
}
}
async waitForTerminal(
handle: string,
options?: {
@@ -20649,16 +20674,24 @@ export function appendNormalizedToTailBuffer(
// Why: status UIs redraw a single line with CR/backspace/ANSI erase
// controls. Terminal previews are text, not a full screen model, so retain
// the latest visible redraw segment instead of appending every spinner frame.
const pieces = `${boundedPreviousPartialLine}${normalizedChunk}`
.split('\n')
.map(applyTerminalLineControls)
const nextPartialLine = (pieces.pop() ?? '').replace(/[ \t]+$/g, '')
const completedLines: string[] = []
const combined = `${boundedPreviousPartialLine}${normalizedChunk}`
let lineStart = 0
for (let index = 0; index < combined.length; index += 1) {
if (combined.charCodeAt(index) !== 0x0a) {
continue
}
completedLines.push(
trimTerminalLineRight(applyTerminalLineControls(combined.slice(lineStart, index)))
)
lineStart = index + 1
}
const nextPartialLine = trimTerminalLineRight(
applyTerminalLineControls(combined.slice(lineStart))
)
const retainedPartialLine = nextPartialLine.slice(-MAX_TAIL_PARTIAL_CHARS)
const newCompleteLines = pieces.length
let nextLines =
newCompleteLines > 0
? [...previousLines, ...pieces.map((line) => line.replace(/[ \t]+$/g, ''))]
: previousLines
const newCompleteLines = completedLines.length
let nextLines = newCompleteLines > 0 ? [...previousLines, ...completedLines] : previousLines
let truncated = previousPartialWasCapped || nextPartialLine.length > MAX_TAIL_PARTIAL_CHARS
if (nextLines.length > MAX_TAIL_LINES) {
@@ -20691,6 +20724,18 @@ export function appendNormalizedToTailBuffer(
}
}
function trimTerminalLineRight(line: string): string {
let end = line.length
while (end > 0) {
const code = line.charCodeAt(end - 1)
if (code !== 0x20 && code !== 0x09) {
break
}
end -= 1
}
return end === line.length ? line : line.slice(0, end)
}
function applyTerminalLineControls(line: string): string {
const carriageIndex = line.lastIndexOf('\r')
const latestRedraw = carriageIndex >= 0 ? line.slice(carriageIndex + 1) : line
@@ -21019,6 +21064,15 @@ function buildSendPayload(action: {
return payload.length > 0 ? payload : null
}
async function assertTerminalInputWithinLimitWithYield(text: string | undefined): Promise<void> {
if (!text) {
return
}
if (await isTerminalInputTooLargeWithYield(text)) {
throw new Error(TERMINAL_INPUT_TOO_LARGE_ERROR)
}
}
// Why: tui-idle relies on recognized agent CLIs setting OSC titles. If the
// terminal runs an unsupported CLI (or a plain shell), no title transition
// will ever fire. A 5-minute ceiling prevents indefinite hangs while still
@@ -21111,29 +21165,47 @@ function findAntigravityReadyPromptIndex(normalized: string): number | null {
if (headerIndex === -1) {
return null
}
const readySegment = normalized.slice(headerIndex)
const lines = readySegment.split('\n')
let offset = 0
let lineStart = headerIndex
let modelIndex: number | null = null
let promptIndex: number | null = null
for (const line of lines) {
const trimmed = line.trim()
const lineIndex = headerIndex + offset
if (lineIndex > headerIndex && trimmed.length > 0) {
if (modelIndex === null && trimmed.startsWith('gemini')) {
modelIndex = lineIndex + line.indexOf(trimmed)
// Why: ready previews can include echoed pasted output after the header;
// scan line bounds directly instead of splitting the whole terminal tail.
for (let cursor = headerIndex; cursor <= normalized.length; cursor += 1) {
if (cursor < normalized.length && normalized.charCodeAt(cursor) !== 10) {
continue
}
let trimmedStart = lineStart
let trimmedEnd = cursor
while (trimmedStart < trimmedEnd && isTerminalWaitWhitespace(normalized, trimmedStart)) {
trimmedStart += 1
}
while (trimmedEnd > trimmedStart && isTerminalWaitWhitespace(normalized, trimmedEnd - 1)) {
trimmedEnd -= 1
}
if (lineStart > headerIndex && trimmedStart < trimmedEnd) {
if (modelIndex === null && normalized.startsWith('gemini', trimmedStart)) {
modelIndex = trimmedStart
}
if (promptIndex === null && trimmed === '>') {
promptIndex = lineIndex + line.indexOf('>')
if (
promptIndex === null &&
trimmedEnd - trimmedStart === 1 &&
normalized.charCodeAt(trimmedStart) === 62
) {
promptIndex = trimmedStart
}
}
offset += line.length + 1
lineStart = cursor + 1
}
return modelIndex !== null && promptIndex !== null ? Math.max(modelIndex, promptIndex) : null
}
function isTerminalWaitWhitespace(value: string, index: number): boolean {
const code = value.charCodeAt(index)
return code === 32 || (code >= 9 && code <= 13)
}
function findTerminalWaitBlockedSignal(
normalized: string
): { reason: RuntimeTerminalWaitBlockedReason; index: number } | null {
@@ -21426,36 +21498,56 @@ function normalizeTerminalChunk(
return { text: chunk, pendingAnsi: '' }
}
const combined = `${pendingAnsi}${chunk}`
let text = ''
const parts: string[] = []
let textStart = 0
for (let index = 0; index < combined.length; index += 1) {
const char = combined[index]
if (char === '\x1b') {
appendTerminalNormalizedSpan(parts, combined, textStart, index)
if (index + 1 >= combined.length) {
return { text, pendingAnsi: combined.slice(index) }
return { text: parts.join(''), pendingAnsi: combined.slice(index) }
}
const parsed = parseAnsiControlSequence(combined, index)
if (!parsed) {
return {
text,
text: parts.join(''),
pendingAnsi: trimPendingAnsiControl(combined.slice(index))
}
}
index = parsed.endIndex
textStart = index + 1
continue
}
if (char === '\r' && combined[index + 1] === '\n') {
text += '\n'
appendTerminalNormalizedSpan(parts, combined, textStart, index)
parts.push('\n')
index += 1
textStart = index + 1
continue
}
const code = combined.charCodeAt(index)
if (code === 0x08 || code === 0x09 || code === 0x0a || code === 0x0d) {
text += char
} else if (isTerminalPreviewPrintableCodeUnit(code)) {
text += char
appendTerminalNormalizedSpan(parts, combined, textStart, index)
parts.push(char)
textStart = index + 1
} else if (!isTerminalPreviewPrintableCodeUnit(code)) {
appendTerminalNormalizedSpan(parts, combined, textStart, index)
textStart = index + 1
}
}
return { text, pendingAnsi: '' }
appendTerminalNormalizedSpan(parts, combined, textStart, combined.length)
return { text: parts.join(''), pendingAnsi: '' }
}
function appendTerminalNormalizedSpan(
parts: string[],
value: string,
start: number,
end: number
): void {
if (end > start) {
parts.push(value.slice(start, end))
}
}
function isTerminalPreviewPrintableCodeUnit(code: number): boolean {
@@ -129,11 +129,16 @@ describe('remote runtime request connection integration', () => {
},
cancelMobileDictationForConnection: () => {},
onClientDisconnected: () => {},
showRepo: (selector: string) => {
if (selector !== repo.id && selector !== `id:${repo.id}`) {
throw new Error('repo_not_found')
}
return repo
},
onClientEvent: (listener: (event: RuntimeClientEvent) => void) => {
clientEventListeners.add(listener)
return () => clientEventListeners.delete(listener)
},
showRepo: () => repo,
listDetectedManagedWorktrees: () => ({
repoId: repo.id,
authoritative: true,
@@ -348,7 +353,12 @@ describe('remote runtime request connection integration', () => {
},
watchFileExplorer: async () => () => {},
listRepos: () => [repo],
showRepo: () => repo,
showRepo: (selector: string) => {
if (selector !== repo.id && selector !== `id:${repo.id}`) {
throw new Error('repo_not_found')
}
return repo
},
listDetectedManagedWorktrees: () => ({
repoId: repo.id,
authoritative: true,
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
import { z } from 'zod'
import { RpcDispatcher } from './dispatcher'
import { defineMethod, type RpcRequest } from './core'
import { defineMethod, InvalidArgumentError, type RpcRequest } from './core'
import type { OrcaRuntimeService } from '../orca-runtime'
function makeRequest(method: string, params?: unknown): RpcRequest {
@@ -24,6 +24,19 @@ const METHODS = [
name: 'browser.click',
params: z.object({ page: z.string().min(1, 'Missing page') }),
handler: () => ({ ok: true })
}),
defineMethod({
name: 'orchestration.throwZod',
params: z.object({}),
handler: () =>
z.object({ title: z.string().min(1, 'Handler title missing') }).parse({ title: '' })
}),
defineMethod({
name: 'orchestration.invalidArgument',
params: z.object({}),
handler: () => {
throw new InvalidArgumentError('Async validation rejected payload')
}
})
]
@@ -81,4 +94,32 @@ describe('RpcDispatcher computer-use validation errors', () => {
})
expect(response.ok === false ? response.error : null).not.toHaveProperty('data')
})
it('preserves formatted Zod issue messages thrown by method handlers', async () => {
const dispatcher = new RpcDispatcher({ runtime: makeRuntime(), methods: METHODS })
const response = await dispatcher.dispatch(makeRequest('orchestration.throwZod', {}))
expect(response).toMatchObject({
ok: false,
error: {
code: 'invalid_argument',
message: 'Handler title missing'
}
})
})
it('maps async validation errors to invalid_argument without shadowing Zod formatting', async () => {
const dispatcher = new RpcDispatcher({ runtime: makeRuntime(), methods: METHODS })
const response = await dispatcher.dispatch(makeRequest('orchestration.invalidArgument', {}))
expect(response).toMatchObject({
ok: false,
error: {
code: 'invalid_argument',
message: 'Async validation rejected payload'
}
})
})
})
+8 -3
View File
@@ -4,6 +4,7 @@
// runtime-rpc.ts focused on framing/auth/connection bookkeeping.
import {
ZodError,
InvalidArgumentError,
buildRegistry,
formatZodError,
isStreamingMethod,
@@ -192,6 +193,13 @@ export class RpcDispatcher {
}
private mapError(request: RpcRequest, meta: RpcEnvelopeMeta, error: unknown): RpcResponse {
if (error instanceof ZodError) {
return this.invalidArgumentResponse(request, meta, formatZodError(error))
}
if (error instanceof InvalidArgumentError) {
return this.invalidArgumentResponse(request, meta, error.message)
}
// Why: browser methods throw BrowserError with a structured `code`;
// every other runtime error has a plain-message code. Routing by method
// prefix keeps the mapping a single decision rather than a per-method
@@ -202,9 +210,6 @@ export class RpcDispatcher {
if (request.method.startsWith('emulator.')) {
return mapEmulatorError(request.id, meta, error)
}
if (error instanceof ZodError) {
return this.invalidArgumentResponse(request, meta, formatZodError(error))
}
return mapRuntimeError(request.id, meta, error)
}
+2 -18
View File
@@ -6,14 +6,12 @@ import {
Element,
Eval,
Exec,
Fill,
Find,
FullScreenshot,
Get,
Goto,
Highlight,
Is,
KeyboardInsert,
Keypress,
LimitParam,
ProfileCreate,
@@ -31,10 +29,10 @@ import {
TabProfileClone,
TabShow,
TabSwitch,
Type,
Upload,
Wait
} from './browser-schemas'
import { BROWSER_TEXT_METHODS } from './browser-text-rpc-methods'
export const BROWSER_CORE_METHODS: RpcMethod[] = [
defineMethod({
@@ -52,16 +50,7 @@ export const BROWSER_CORE_METHODS: RpcMethod[] = [
params: Goto,
handler: async (params, { runtime }) => runtime.browserGoto(params)
}),
defineMethod({
name: 'browser.fill',
params: Fill,
handler: async (params, { runtime }) => runtime.browserFill(params)
}),
defineMethod({
name: 'browser.type',
params: Type,
handler: async (params, { runtime }) => runtime.browserType(params)
}),
...BROWSER_TEXT_METHODS,
defineMethod({
name: 'browser.select',
params: Select,
@@ -247,11 +236,6 @@ export const BROWSER_CORE_METHODS: RpcMethod[] = [
params: Is,
handler: async (params, { runtime }) => runtime.browserIs(params)
}),
defineMethod({
name: 'browser.keyboardInsertText',
params: KeyboardInsert,
handler: async (params, { runtime }) => runtime.browserKeyboardInsertText(params)
}),
defineMethod({
name: 'browser.find',
params: Find,
@@ -1,5 +1,6 @@
import { z } from 'zod'
import { defineMethod, type RpcMethod } from '../core'
import { assertRpcClipboardTextWriteWithinLimit } from '../rpc-clipboard-text-validation'
import { BrowserTarget, OptionalFiniteNumber } from '../schemas'
import {
ClipboardWrite,
@@ -132,7 +133,10 @@ export const BROWSER_EXTRA_METHODS: RpcMethod[] = [
defineMethod({
name: 'browser.clipboardWrite',
params: ClipboardWrite,
handler: async (params, { runtime }) => runtime.browserClipboardWrite(params)
handler: async (params, { runtime }) => {
await assertRpcClipboardTextWriteWithinLimit(params.text)
return runtime.browserClipboardWrite(params)
}
}),
defineMethod({
name: 'browser.dialogAccept',
@@ -9,6 +9,7 @@ import {
OptionalFiniteNumber,
OptionalPlainString,
OptionalString,
requiredStringAllowingEmpty,
requiredString
} from '../schemas'
@@ -22,9 +23,7 @@ export const Goto = BrowserTarget.extend({
export const Fill = BrowserTarget.extend({
element: requiredString('Missing required --element'),
value: z.custom<string>((v) => typeof v === 'string', {
message: 'Missing required --value'
})
value: requiredStringAllowingEmpty('Missing required --value')
})
export const Type = BrowserTarget.extend({
@@ -0,0 +1,30 @@
import { defineMethod, type RpcMethod } from '../core'
import { assertRpcClipboardTextWriteWithinLimit } from '../rpc-clipboard-text-validation'
import { Fill, KeyboardInsert, Type } from './browser-schemas'
export const BROWSER_TEXT_METHODS: RpcMethod[] = [
defineMethod({
name: 'browser.fill',
params: Fill,
handler: async (params, { runtime }) => {
await assertRpcClipboardTextWriteWithinLimit(params.value)
return runtime.browserFill(params)
}
}),
defineMethod({
name: 'browser.type',
params: Type,
handler: async (params, { runtime }) => {
await assertRpcClipboardTextWriteWithinLimit(params.input)
return runtime.browserType(params)
}
}),
defineMethod({
name: 'browser.keyboardInsertText',
params: KeyboardInsert,
handler: async (params, { runtime }) => {
await assertRpcClipboardTextWriteWithinLimit(params.text)
return runtime.browserKeyboardInsertText(params)
}
})
]
@@ -2,9 +2,15 @@ import { describe, expect, it, vi } from 'vitest'
import { RpcDispatcher } from '../dispatcher'
import type { RpcRequest } from '../core'
import type { OrcaRuntimeService } from '../../orca-runtime'
import {
CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS,
CLIPBOARD_TEXT_WRITE_MAX_BYTES,
CLIPBOARD_TEXT_WRITE_TOO_LARGE_ERROR
} from '../../../../shared/clipboard-text'
import { BROWSER_CORE_METHODS } from './browser-core'
import { BROWSER_EXTRA_METHODS } from './browser-extras'
import { BROWSER_SCREENCAST_METHODS } from './browser-screencast'
import { ClipboardWrite, Fill, KeyboardInsert, Type } from './browser-schemas'
function makeRequest(method: string, params?: unknown): RpcRequest {
return { id: 'req-1', authToken: 'tok', method, params }
@@ -235,4 +241,115 @@ describe('browser RPC methods', () => {
})
expect(runtime.browserCheck).not.toHaveBeenCalled()
})
it('rejects oversized browser clipboard writes before runtime dispatch', async () => {
const secret = 'browser-secret-token'
const runtime = {
getRuntimeId: () => 'test-runtime',
browserClipboardWrite: vi.fn().mockResolvedValue({ ok: true })
} as unknown as OrcaRuntimeService
const dispatcher = new RpcDispatcher({ runtime, methods: BROWSER_EXTRA_METHODS })
const response = await dispatcher.dispatch(
makeRequest('browser.clipboardWrite', {
page: 'page-1',
text: secret + 'x'.repeat(CLIPBOARD_TEXT_WRITE_MAX_BYTES + 1)
})
)
expect(response).toMatchObject({
ok: false,
error: {
code: 'invalid_argument',
message: CLIPBOARD_TEXT_WRITE_TOO_LARGE_ERROR
}
})
expect(JSON.stringify(response)).not.toContain(secret)
expect(runtime.browserClipboardWrite).not.toHaveBeenCalled()
})
it('leaves browser text byte limits to async handlers', () => {
const text = 'x'.repeat(CLIPBOARD_TEXT_WRITE_MAX_BYTES + 1)
expect(Fill.safeParse({ element: '@e1', value: text }).success).toBe(true)
expect(Type.safeParse({ input: text }).success).toBe(true)
expect(KeyboardInsert.safeParse({ text }).success).toBe(true)
expect(ClipboardWrite.safeParse({ text }).success).toBe(true)
})
it('yields while validating large accepted browser text insertion before dispatch', async () => {
vi.useFakeTimers()
try {
const text = 'é'.repeat(CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS + 1)
const runtime = {
getRuntimeId: () => 'test-runtime',
browserType: vi.fn().mockResolvedValue({ typed: true })
} as unknown as OrcaRuntimeService
const dispatcher = new RpcDispatcher({ runtime, methods: BROWSER_CORE_METHODS })
const responsePromise = dispatcher.dispatch(makeRequest('browser.type', { input: text }))
await Promise.resolve()
expect(runtime.browserType).not.toHaveBeenCalled()
await vi.runOnlyPendingTimersAsync()
const response = await responsePromise
expect(response).toMatchObject({
ok: true,
result: { typed: true }
})
expect(runtime.browserType).toHaveBeenCalledWith({ input: text })
} finally {
vi.useRealTimers()
}
})
it('rejects oversized browser text insertion before runtime dispatch', async () => {
const secret = 'browser-insert-secret'
const runtime = {
getRuntimeId: () => 'test-runtime',
browserFill: vi.fn().mockResolvedValue({ filled: '@e1' }),
browserType: vi.fn().mockResolvedValue({ typed: true }),
browserKeyboardInsertText: vi.fn().mockResolvedValue({ inserted: true })
} as unknown as OrcaRuntimeService
const dispatcher = new RpcDispatcher({ runtime, methods: BROWSER_CORE_METHODS })
const text = [secret, 'x'.repeat(CLIPBOARD_TEXT_WRITE_MAX_BYTES + 1)].join('')
const fillResponse = await dispatcher.dispatch(
makeRequest('browser.fill', { element: '@e1', value: text })
)
const typeResponse = await dispatcher.dispatch(makeRequest('browser.type', { input: text }))
const keyboardInsertResponse = await dispatcher.dispatch(
makeRequest('browser.keyboardInsertText', { text })
)
expect(fillResponse).toMatchObject({
ok: false,
error: {
code: 'invalid_argument',
message: CLIPBOARD_TEXT_WRITE_TOO_LARGE_ERROR
}
})
expect(typeResponse).toMatchObject({
ok: false,
error: {
code: 'invalid_argument',
message: CLIPBOARD_TEXT_WRITE_TOO_LARGE_ERROR
}
})
expect(keyboardInsertResponse).toMatchObject({
ok: false,
error: {
code: 'invalid_argument',
message: CLIPBOARD_TEXT_WRITE_TOO_LARGE_ERROR
}
})
expect(JSON.stringify([fillResponse, typeResponse, keyboardInsertResponse])).not.toContain(
secret
)
expect(runtime.browserFill).not.toHaveBeenCalled()
expect(runtime.browserType).not.toHaveBeenCalled()
expect(runtime.browserKeyboardInsertText).not.toHaveBeenCalled()
})
})
@@ -2,6 +2,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { RpcDispatcher } from '../dispatcher'
import type { RpcRequest } from '../core'
import type { OrcaRuntimeService } from '../../orca-runtime'
import {
CLIPBOARD_IMAGE_MAX_BASE64_CHARS,
CLIPBOARD_IMAGE_TOO_LARGE_ERROR
} from '../../../../shared/clipboard-image'
const { saveClipboardImageBufferAsTempFile } = vi.hoisted(() => ({
saveClipboardImageBufferAsTempFile: vi.fn()
@@ -73,6 +77,26 @@ describe('clipboard RPC methods', () => {
expect(saveClipboardImageBufferAsTempFile).not.toHaveBeenCalled()
})
it('rejects oversized direct clipboard image payloads before base64 validation', async () => {
const base64Test = vi.spyOn(RegExp.prototype, 'test')
const dispatcher = makeDispatcher()
try {
const response = await dispatcher.dispatch(
makeRequest('clipboard.saveImageAsTempFile', {
contentBase64: 'A'.repeat(CLIPBOARD_IMAGE_MAX_BASE64_CHARS + 1)
})
)
expect(response).toMatchObject({ ok: false })
expect(JSON.stringify(response)).toContain(CLIPBOARD_IMAGE_TOO_LARGE_ERROR)
expect(base64Test).not.toHaveBeenCalled()
expect(saveClipboardImageBufferAsTempFile).not.toHaveBeenCalled()
} finally {
base64Test.mockRestore()
}
})
it('accepts chunked uploads and forwards the recorded connectionId on commit', async () => {
saveClipboardImageBufferAsTempFile.mockResolvedValue('/tmp/orca-paste-image.png')
const dispatcher = makeDispatcher()
@@ -170,6 +194,35 @@ describe('clipboard RPC methods', () => {
).resolves.toMatchObject({ ok: false })
})
it('rejects oversized clipboard image upload chunks before base64 validation', async () => {
const base64Test = vi.spyOn(RegExp.prototype, 'test')
const dispatcher = makeDispatcher()
const start = await dispatcher.dispatch(
makeRequest('clipboard.startImageUpload', {
expectedBase64Length: CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS + 4,
connectionId: null
})
)
const uploadId = (start.ok ? start.result : null) as { uploadId: string }
try {
const response = await dispatcher.dispatch(
makeRequest('clipboard.appendImageUploadChunk', {
uploadId: uploadId.uploadId,
offset: 0,
contentBase64: 'A'.repeat(CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS + 4)
})
)
expect(response).toMatchObject({ ok: false })
expect(JSON.stringify(response)).toContain('Clipboard image chunk is too large')
expect(base64Test).not.toHaveBeenCalled()
expect(saveClipboardImageBufferAsTempFile).not.toHaveBeenCalled()
} finally {
base64Test.mockRestore()
}
})
it('rejects uploads beyond the existing total clipboard image limit', async () => {
const dispatcher = makeDispatcher()
+32 -17
View File
@@ -2,8 +2,12 @@ import { z } from 'zod'
import { defineMethod, type RpcMethod } from '../core'
import { saveClipboardImageBufferAsTempFile } from '../../../window/clipboard-image-temp-file'
import { randomUUID } from 'node:crypto'
import {
CLIPBOARD_IMAGE_MAX_BASE64_CHARS,
CLIPBOARD_IMAGE_TOO_LARGE_ERROR
} from '../../../../shared/clipboard-image'
const MAX_CLIPBOARD_IMAGE_BASE64_CHARS = 24 * 1024 * 1024
const MAX_CLIPBOARD_IMAGE_BASE64_CHARS = CLIPBOARD_IMAGE_MAX_BASE64_CHARS
export const CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS = 512 * 1024
export const CLIPBOARD_IMAGE_UPLOAD_MAX_CONCURRENT = 8
const CLIPBOARD_IMAGE_UPLOAD_TTL_MS = 5 * 60 * 1000
@@ -71,14 +75,29 @@ function assertValidBase64Content(value: string): void {
}
}
function clipboardImageBase64Payload(maxChars: number, tooLargeMessage: string) {
return z.unknown().transform((value, ctx): string => {
if (typeof value !== 'string') {
ctx.addIssue({ code: 'custom', message: 'Missing image content' })
return z.NEVER
}
if (value.length > maxChars) {
ctx.addIssue({ code: 'custom', message: tooLargeMessage })
return z.NEVER
}
if (!isValidBase64(value)) {
ctx.addIssue({ code: 'custom', message: 'Clipboard image content must be base64' })
return z.NEVER
}
return value
})
}
const SaveImageAsTempFile = z.object({
contentBase64: z
.unknown()
.refine((v): v is string => typeof v === 'string', { message: 'Missing image content' })
.refine((value) => value.length <= MAX_CLIPBOARD_IMAGE_BASE64_CHARS, {
message: 'Clipboard image is too large'
})
.refine(isValidBase64, 'Clipboard image content must be base64'),
contentBase64: clipboardImageBase64Payload(
MAX_CLIPBOARD_IMAGE_BASE64_CHARS,
CLIPBOARD_IMAGE_TOO_LARGE_ERROR
),
connectionId: z.string().min(1).nullable().optional()
})
@@ -87,21 +106,17 @@ const StartImageUpload = z.object({
.number()
.int()
.nonnegative()
.max(MAX_CLIPBOARD_IMAGE_BASE64_CHARS, 'Clipboard image is too large'),
.max(MAX_CLIPBOARD_IMAGE_BASE64_CHARS, CLIPBOARD_IMAGE_TOO_LARGE_ERROR),
connectionId: z.string().min(1).nullable().optional()
})
const AppendImageUploadChunk = z.object({
uploadId: z.string().min(1),
offset: z.number().int().nonnegative(),
contentBase64: z
.unknown()
.refine((v): v is string => typeof v === 'string', { message: 'Missing image content' })
.refine(
(value) => value.length <= CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS,
'Clipboard image chunk is too large'
)
.refine(isValidBase64, 'Clipboard image content must be base64')
contentBase64: clipboardImageBase64Payload(
CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS,
'Clipboard image chunk is too large'
)
})
const CommitImageUpload = z.object({
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { CLIPBOARD_TEXT_WRITE_MAX_BYTES } from '../../../../shared/clipboard-text'
const computerMocks = vi.hoisted(() => ({
callComputerSidecarAction: vi.fn(),
@@ -193,6 +194,18 @@ describe('computer action RPC methods', () => {
})
})
it('leaves oversized computer paste text to async sidecar validation', async () => {
const secret = 'computer-paste-secret'
const text = secret + 'x'.repeat(CLIPBOARD_TEXT_WRITE_MAX_BYTES + 1)
expect(
findMethod('computer.pasteText').params!.safeParse({
app: 'Finder',
text
}).success
).toBe(true)
})
it('dispatches scroll and setValue actions through the sidecar', async () => {
computerMocks.callComputerSidecarAction.mockResolvedValue({ ok: true })
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { buildRegistry } from '../core'
import { CLIPBOARD_TEXT_WRITE_MAX_BYTES } from '../../../../shared/clipboard-text'
const computerMocks = vi.hoisted(() => ({
callComputerSidecarAction: vi.fn(),
@@ -237,6 +238,14 @@ describe('computer RPC methods', () => {
findMethod('computer.hotkey').params!.parse({ app: 'Finder', key: 'Ctrl+A+B' })
).toThrow(/Hotkey requires a modifier and one key/)
})
it('leaves pasteText byte limits to async sidecar validation', () => {
const text = 'x'.repeat(CLIPBOARD_TEXT_WRITE_MAX_BYTES + 1)
expect(
findMethod('computer.pasteText').params!.safeParse({ app: 'Finder', text }).success
).toBe(true)
})
})
function findMethod(name: string) {
+132 -44
View File
@@ -1,6 +1,11 @@
/* oxlint-disable max-lines -- Why: terminal RPC methods are co-located for discoverability; splitting would scatter related handlers across files. */
import { z } from 'zod'
import { defineMethod, defineStreamingMethod, type RpcAnyMethod } from '../core'
import {
InvalidArgumentError,
defineMethod,
defineStreamingMethod,
type RpcAnyMethod
} from '../core'
import { OptionalFiniteNumber, OptionalString, requiredString } from '../schemas'
import type { DriverState, OrcaRuntimeService } from '../../orca-runtime'
import {
@@ -14,6 +19,12 @@ import {
} from '../../../../shared/terminal-stream-protocol'
import { TERMINAL_PANE_SPLIT_SOURCES } from '../../../../shared/feature-education-telemetry'
import type { TerminalOscLinkRange } from '../../../../shared/terminal-osc-link-ranges'
import {
TERMINAL_INPUT_MAX_BYTES,
TERMINAL_INPUT_TOO_LARGE_ERROR,
isTerminalInputTooLargeWithYield
} from '../../../../shared/terminal-input'
import { measureClipboardTextByteLength } from '../../../../shared/clipboard-text'
// Why: when a mobile client subscribes the server resizes the PTY to phone
// dims and serializes the buffer. Sending only the visible screen meant
@@ -31,7 +42,6 @@ const TERMINAL_OUTPUT_BATCH_MAX_BYTES = 64 * 1024
// Why: pending output is held for later binary frames, so cap the encoded
// payload bytes rather than UTF-16 code units.
const TERMINAL_MULTIPLEX_PENDING_MAX_BYTES = 256 * 1024
const terminalStreamTextEncoder = new TextEncoder()
let nextTerminalStreamId = 1
type SnapshotFrameOptions = {
@@ -89,6 +99,7 @@ type TerminalMultiplexStream = {
type TerminalOutputChunk = {
data: string
bytes: number
meta?: { seq?: number; rawLength?: number }
}
@@ -136,11 +147,15 @@ function createTerminalOutputBatcher(
return
}
chunks.push(data)
bytes += terminalStreamByteLength(data)
const remainingBudget = Math.max(1, TERMINAL_OUTPUT_BATCH_MAX_BYTES - bytes)
const measurement = measureTerminalStreamByteLength(data, {
stopAfterBytes: remainingBudget
})
bytes += measurement.byteLength
if (typeof meta?.seq === 'number') {
lastSeq = meta.seq
}
if (bytes >= TERMINAL_OUTPUT_BATCH_MAX_BYTES) {
if (measurement.exceededLimit || bytes >= TERMINAL_OUTPUT_BATCH_MAX_BYTES) {
flush()
return
}
@@ -162,50 +177,73 @@ function createTerminalOutputBatcher(
}
}
function splitTerminalOutputFrameChunks(
function* iterateTerminalOutputFrameChunks(
data: string,
meta?: { seq?: number; rawLength?: number }
): TerminalOutputFrameChunk[] {
const bytes = encodeTerminalStreamText(data)
if (bytes.byteLength <= TERMINAL_STREAM_CHUNK_BYTES) {
return [{ bytes, seq: meta?.seq }]
): Generator<TerminalOutputFrameChunk> {
if (!terminalStreamByteLengthExceeds(data, TERMINAL_STREAM_CHUNK_BYTES)) {
yield { bytes: encodeTerminalStreamText(data), seq: meta?.seq }
return
}
const chunks: TerminalOutputFrameChunk[] = []
const rawLength = meta?.rawLength ?? data.length
const canPreserveChunkSeq = typeof meta?.seq === 'number' && rawLength === data.length
const shouldDelayFinalSeq = !canPreserveChunkSeq && typeof meta?.seq === 'number'
const startSeq = canPreserveChunkSeq ? meta.seq! - rawLength : undefined
let chunk = ''
let chunkBytes = 0
let chunkStartOffset = 0
let offset = 0
let delayedChunk: { text: string; seq?: number } | null = null
const flushChunk = (): void => {
const takeChunk = (): { text: string; seq?: number } | null => {
if (!chunk) {
return
return null
}
const chunkSeq = canPreserveChunkSeq ? startSeq! + chunkStartOffset + chunk.length : undefined
chunks.push({ bytes: encodeTerminalStreamText(chunk), seq: chunkSeq })
const current = { text: chunk, seq: chunkSeq }
chunk = ''
chunkBytes = 0
chunkStartOffset = offset
return current
}
for (const part of data) {
const partBytes = terminalStreamByteLength(part)
if (chunkBytes > 0 && chunkBytes + partBytes > TERMINAL_STREAM_CHUNK_BYTES) {
flushChunk()
const nextChunk = takeChunk()
if (nextChunk) {
if (shouldDelayFinalSeq) {
if (delayedChunk) {
yield { bytes: encodeTerminalStreamText(delayedChunk.text) }
}
delayedChunk = nextChunk
} else {
yield { bytes: encodeTerminalStreamText(nextChunk.text), seq: nextChunk.seq }
}
}
}
chunk += part
chunkBytes += partBytes
offset += part.length
}
flushChunk()
if (!canPreserveChunkSeq && typeof meta?.seq === 'number' && chunks.length > 0) {
const finalChunk = takeChunk()
if (shouldDelayFinalSeq) {
// Why: if a future caller reports rawLength that cannot be mapped back to
// UTF-16 offsets, only the final frame can safely carry the high-water mark.
chunks.at(-1)!.seq = meta.seq
if (finalChunk) {
if (delayedChunk) {
yield { bytes: encodeTerminalStreamText(delayedChunk.text) }
}
delayedChunk = finalChunk
}
if (delayedChunk) {
yield { bytes: encodeTerminalStreamText(delayedChunk.text), seq: meta.seq }
}
return
}
if (finalChunk) {
yield { bytes: encodeTerminalStreamText(finalChunk.text), seq: finalChunk.seq }
}
return chunks
}
function isTerminalInputLockedForClient(
@@ -225,6 +263,17 @@ function isTerminalInputLockedForClient(
return runtime.getDriver(ptyId).kind === 'mobile'
}
async function assertTerminalSendTextWithinLimit(text: string | undefined): Promise<void> {
if (!text) {
return
}
// Why: runtime/mobile sends can be paste-sized; validate outside Zod so
// accepted large input yields before terminal runtime dispatch.
if (await isTerminalInputTooLargeWithYield(text, TERMINAL_INPUT_MAX_BYTES)) {
throw new InvalidArgumentError(TERMINAL_INPUT_TOO_LARGE_ERROR)
}
}
function resolveMobileFloorClientId(
driver: DriverState | null,
client: TerminalViewportClient | undefined
@@ -243,15 +292,22 @@ function appendPendingMultiplexOutput(
data: string,
meta?: { seq?: number; rawLength?: number }
): void {
stream.pendingOutput.push({ data, meta })
stream.pendingOutputBytes += terminalStreamByteLength(data)
const remainingBudget = Math.max(
1,
TERMINAL_MULTIPLEX_PENDING_MAX_BYTES - stream.pendingOutputBytes
)
const measurement = measureTerminalStreamByteLength(data, {
stopAfterBytes: remainingBudget
})
stream.pendingOutput.push({ data, bytes: measurement.byteLength, meta })
stream.pendingOutputBytes += measurement.byteLength
const trimmed = trimPendingOutputToBudget(stream.pendingOutput, stream.pendingOutputBytes)
stream.pendingOutputBytes = trimmed.bytes
stream.pendingOutputOverflowed ||= trimmed.overflowed
}
function trimPendingOutputToBudget(
pendingOutput: (string | TerminalOutputChunk)[],
pendingOutput: TerminalOutputChunk[],
pendingOutputBytes: number
): { bytes: number; overflowed: boolean } {
let omittedChunkCount = 0
@@ -260,7 +316,7 @@ function trimPendingOutputToBudget(
omittedChunkCount < pendingOutput.length
) {
const chunk = pendingOutput[omittedChunkCount]
pendingOutputBytes -= terminalStreamByteLength(typeof chunk === 'string' ? chunk : chunk.data)
pendingOutputBytes -= chunk.bytes
omittedChunkCount += 1
}
if (omittedChunkCount > 0) {
@@ -269,8 +325,28 @@ function trimPendingOutputToBudget(
return { bytes: pendingOutputBytes, overflowed: omittedChunkCount > 0 }
}
function measureTerminalStreamByteLength(
data: string,
options: { stopAfterBytes?: number } = {}
): { byteLength: number; exceededLimit: boolean } {
return measureClipboardTextByteLength(data, options)
}
function terminalStreamByteLength(data: string): number {
return terminalStreamTextEncoder.encode(data).byteLength
return measureTerminalStreamByteLength(data).byteLength
}
function terminalStreamByteLengthExceeds(data: string, maxBytes: number): boolean {
return measureTerminalStreamByteLength(data, { stopAfterBytes: maxBytes }).exceededLimit
}
function* iterateTerminalStreamTextPayloads(data: string): Generator<Uint8Array<ArrayBufferLike>> {
if (!data) {
return
}
for (const chunk of iterateTerminalOutputFrameChunks(data)) {
yield chunk.bytes
}
}
function isTerminalReadPayloadIncomplete(read: { truncated: boolean; limited?: boolean }): boolean {
@@ -304,12 +380,15 @@ async function serializeBudgetedRequestedSnapshot(
if (!serialized) {
return null
}
const bytes = terminalStreamByteLength(serialized.data)
if (bytes <= REQUESTED_SNAPSHOT_BYTE_BUDGET || rows === 0) {
const overByteBudget = terminalStreamByteLengthExceeds(
serialized.data,
REQUESTED_SNAPSHOT_BYTE_BUDGET
)
if (!overByteBudget || rows === 0) {
return {
...serialized,
scrollbackRows: rows,
truncatedByByteBudget: rows < requestedRows || bytes > REQUESTED_SNAPSHOT_BYTE_BUDGET
truncatedByByteBudget: rows < requestedRows || overByteBudget
}
}
}
@@ -336,17 +415,15 @@ function sendSnapshotFrames(
truncatedByByteBudget: options.truncatedByByteBudget === true
})
)
const bytes = encodeTerminalStreamText(options.data)
let chunks = 0
for (let offset = 0; offset < bytes.length; offset += TERMINAL_STREAM_CHUNK_BYTES) {
let bytes = 0
for (const chunk of iterateTerminalStreamTextPayloads(options.data)) {
chunks++
sendFrame(
TerminalStreamOpcode.SnapshotChunk,
bytes.slice(offset, offset + TERMINAL_STREAM_CHUNK_BYTES)
)
bytes += chunk.byteLength
sendFrame(TerminalStreamOpcode.SnapshotChunk, chunk)
}
sendFrame(TerminalStreamOpcode.SnapshotEnd)
return { bytes: bytes.byteLength, chunks }
return { bytes, chunks }
}
async function serializeBudgetedMobileSnapshot(
@@ -364,13 +441,15 @@ async function serializeBudgetedMobileSnapshot(
if (!serialized) {
return null
}
const bytes = terminalStreamByteLength(serialized.data)
if (bytes <= MOBILE_SNAPSHOT_BYTE_BUDGET || rows === 0) {
const overByteBudget = terminalStreamByteLengthExceeds(
serialized.data,
MOBILE_SNAPSHOT_BYTE_BUDGET
)
if (!overByteBudget || rows === 0) {
return {
...serialized,
scrollbackRows: rows,
truncatedByByteBudget:
rows < MOBILE_SUBSCRIBE_SCROLLBACK_ROWS || bytes > MOBILE_SNAPSHOT_BYTE_BUDGET
truncatedByByteBudget: rows < MOBILE_SUBSCRIBE_SCROLLBACK_ROWS || overByteBudget
}
}
}
@@ -747,6 +826,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
name: 'terminal.send',
params: TerminalSend,
handler: async (params, { runtime }) => {
await assertTerminalSendTextWithinLimit(params.text)
const leaf = runtime.resolveLeafForHandle(params.terminal)
const driver = leaf?.ptyId ? runtime.getDriver(leaf.ptyId) : null
if (leaf?.ptyId && isTerminalInputLockedForClient(runtime, leaf.ptyId, params.client)) {
@@ -1217,7 +1297,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
lastResizeCols: undefined,
resizeGeneration: 0,
outputBatcher: createTerminalOutputBatcher((data, meta) => {
for (const chunk of splitTerminalOutputFrameChunks(data, meta)) {
for (const chunk of iterateTerminalOutputFrameChunks(data, meta)) {
sendFrame(request.streamId, TerminalStreamOpcode.Output, chunk.bytes, chunk.seq)
}
}),
@@ -1536,7 +1616,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
// resize re-stream so it only fires on an actual width change.
let lastResizeCols: number | undefined
let resizeGeneration = 0
const pendingOutput: string[] = []
const pendingOutput: TerminalOutputChunk[] = []
let pendingOutputBytes = 0
let unsubscribeData = (): void => {}
let unsubscribeResize = (): void => {}
@@ -1583,7 +1663,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
sendBinary(encodeTerminalStreamFrame({ opcode, streamId, seq: cursor++, payload }))
}
outputBatcher = createTerminalOutputBatcher((data) => {
for (const chunk of splitTerminalOutputFrameChunks(data)) {
for (const chunk of iterateTerminalOutputFrameChunks(data)) {
sendFrame(TerminalStreamOpcode.Output, chunk.bytes)
}
})
@@ -1644,9 +1724,17 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
return
}
if (buffering) {
pendingOutput.push(data)
pendingOutputBytes += terminalStreamByteLength(data)
pendingOutputBytes = trimPendingOutputToBudget(pendingOutput, pendingOutputBytes).bytes
const remainingBudget = Math.max(
1,
TERMINAL_MULTIPLEX_PENDING_MAX_BYTES - pendingOutputBytes
)
const measurement = measureTerminalStreamByteLength(data, {
stopAfterBytes: remainingBudget
})
pendingOutput.push({ data, bytes: measurement.byteLength })
pendingOutputBytes += measurement.byteLength
const trimmed = trimPendingOutputToBudget(pendingOutput, pendingOutputBytes)
pendingOutputBytes = trimmed.bytes
return
}
outputBatcher?.push(data)
@@ -1699,7 +1787,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
lastResizeCols = serialized?.cols ?? size?.cols
buffering = false
for (const item of pendingOutput.splice(0)) {
outputBatcher.push(item)
outputBatcher.push(item.data, item.meta)
}
pendingOutputBytes = 0
outputBatcher.flush()
@@ -0,0 +1,19 @@
import {
CLIPBOARD_TEXT_WRITE_TOO_LARGE_ERROR,
assertClipboardTextWriteWithinLimitWithYield,
isClipboardTextWriteTooLargeError
} from '../../../shared/clipboard-text'
import { InvalidArgumentError } from './core'
export async function assertRpcClipboardTextWriteWithinLimit(text: string): Promise<void> {
try {
// Why: large accepted text must yield outside Zod's synchronous parse path
// while preserving the RPC invalid_argument contract for rejected payloads.
await assertClipboardTextWriteWithinLimitWithYield(text)
} catch (error) {
if (isClipboardTextWriteTooLargeError(error)) {
throw new InvalidArgumentError(CLIPBOARD_TEXT_WRITE_TOO_LARGE_ERROR)
}
throw error
}
}
@@ -441,6 +441,7 @@ describe('terminal multiplex RPC', () => {
binaryFrames.splice(0)
const multibyteOutput = '界'.repeat(22_000)
const encodeSpy = vi.spyOn(TextEncoder.prototype, 'encode')
dataListenerRef.current?.(multibyteOutput, {
seq: multibyteOutput.length,
rawLength: multibyteOutput.length
@@ -457,6 +458,8 @@ describe('terminal multiplex RPC', () => {
expect(
outputFrames.map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')).join('')
).toBe(multibyteOutput)
expect(encodeSpy).not.toHaveBeenCalledWith(multibyteOutput)
encodeSpy.mockRestore()
cleanups.get('terminal-multiplex:conn-multibyte-output-batch')?.()
await dispatchPromise
@@ -171,6 +171,93 @@ describe('terminal output batching', () => {
}
})
it('encodes large binary terminal output lazily before the first output frame', async () => {
vi.useFakeTimers()
try {
const messages: string[] = []
const binaryFrames: Uint8Array<ArrayBufferLike>[] = []
const cleanups = new Map<string, () => void>()
const dataListenerRef: { current?: (data: string) => void } = {}
let captureOutputFrames = false
let firstOutputEncodeCount: number | undefined
const encodeSpy = vi.spyOn(TextEncoder.prototype, 'encode')
const runtime = stubRuntime({
resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }),
readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }),
serializeTerminalBuffer: vi.fn().mockResolvedValue(null),
getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }),
getMobileDisplayMode: vi.fn().mockReturnValue('auto'),
getLayout: vi.fn().mockReturnValue({ seq: 1 }),
subscribeToTerminalData: vi.fn((_: string, listener: (data: string) => void) => {
dataListenerRef.current = listener
return vi.fn()
}),
subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()),
subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()),
registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => {
cleanups.set(id, cleanup)
}),
cleanupSubscription: vi.fn((id: string) => {
const cleanup = cleanups.get(id)
cleanups.delete(id)
cleanup?.()
}),
waitForTerminal: vi.fn(() => new Promise<RuntimeTerminalWait>(() => {})),
sendTerminal: vi.fn().mockResolvedValue({ accepted: true }),
updateMobileViewport: vi.fn().mockResolvedValue(false)
})
const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS })
const dispatchPromise = dispatcher.dispatchStreaming(
makeRequest('terminal.subscribe', {
terminal: 'terminal-1',
client: { id: 'desktop-1', type: 'desktop' },
capabilities: { terminalBinaryStream: 1 }
}),
(msg) => messages.push(msg),
{
connectionId: 'conn-1',
sendBinary: (bytes) => {
const frame = decodeTerminalStreamFrame(bytes)
if (
captureOutputFrames &&
firstOutputEncodeCount === undefined &&
frame?.opcode === TerminalStreamOpcode.Output
) {
firstOutputEncodeCount = encodeSpy.mock.calls.length
}
binaryFrames.push(bytes)
}
}
)
await vi.waitFor(() =>
expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true)
)
await vi.waitFor(() => expect(dataListenerRef.current).toBeDefined())
binaryFrames.length = 0
encodeSpy.mockClear()
captureOutputFrames = true
const output = 'x'.repeat(48 * 1024 * 3 + 17)
dataListenerRef.current?.(output)
const outputFrames = binaryFrames
.map((frame) => decodeTerminalStreamFrame(frame))
.filter((frame) => frame?.opcode === TerminalStreamOpcode.Output)
expect(outputFrames.length).toBeGreaterThan(1)
expect(firstOutputEncodeCount).toBe(1)
expect(
outputFrames.map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')).join('')
).toBe(output)
runtime.cleanupSubscription('terminal-1:desktop-1')
await dispatchPromise
} finally {
vi.useRealTimers()
}
})
it('routes binary terminal input frames back to the subscribed PTY', async () => {
const handlers = new Map<
number,
+96 -1
View File
@@ -1,8 +1,13 @@
import { describe, expect, it, vi } from 'vitest'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { RpcDispatcher } from './dispatcher'
import type { RpcRequest } from './core'
import type { OrcaRuntimeService } from '../orca-runtime'
import { TERMINAL_METHODS } from './methods/terminal'
import { CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS } from '../../../shared/clipboard-text'
import {
TERMINAL_INPUT_MAX_BYTES,
TERMINAL_INPUT_TOO_LARGE_ERROR
} from '../../../shared/terminal-input'
function stubRuntime(overrides: Partial<OrcaRuntimeService> = {}): OrcaRuntimeService {
return {
@@ -16,6 +21,10 @@ function makeRequest(method: string, params?: unknown): RpcRequest {
}
describe('terminal send RPC', () => {
afterEach(() => {
vi.useRealTimers()
})
it('reports whether a terminal handle is running a recognized agent', async () => {
const runtime = stubRuntime({
isTerminalRunningAgent: vi.fn().mockResolvedValue(true)
@@ -101,6 +110,92 @@ describe('terminal send RPC', () => {
expect(runtime.mobileTookFloor).toHaveBeenCalledWith('pty-1', 'mobile-1')
})
it('rejects oversized terminal send text before runtime dispatch', async () => {
const secret = 'terminal-send-secret'
const runtime = stubRuntime({
sendTerminal: vi.fn()
})
const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS })
const response = await dispatcher.dispatch(
makeRequest('terminal.send', {
terminal: 'terminal-1',
text: [secret, 'x'.repeat(TERMINAL_INPUT_MAX_BYTES + 1)].join('')
})
)
expect(response).toMatchObject({
ok: false,
error: {
code: 'invalid_argument',
message: TERMINAL_INPUT_TOO_LARGE_ERROR
}
})
expect(JSON.stringify(response)).not.toContain(secret)
expect(runtime.sendTerminal).not.toHaveBeenCalled()
})
it('rejects multibyte oversized terminal send text before runtime dispatch', async () => {
const runtime = stubRuntime({
sendTerminal: vi.fn()
})
const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS })
const text = '😀'.repeat(Math.floor(TERMINAL_INPUT_MAX_BYTES / 4) + 1)
const response = await dispatcher.dispatch(
makeRequest('terminal.send', {
terminal: 'terminal-1',
text
})
)
expect(text.length).toBeLessThan(TERMINAL_INPUT_MAX_BYTES)
expect(response).toMatchObject({
ok: false,
error: {
code: 'invalid_argument',
message: TERMINAL_INPUT_TOO_LARGE_ERROR
}
})
expect(runtime.sendTerminal).not.toHaveBeenCalled()
})
it('yields while validating large accepted terminal send text before runtime dispatch', async () => {
vi.useFakeTimers()
const text = 'é'.repeat(CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS + 1)
const runtime = stubRuntime({
resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }),
getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }),
sendTerminal: vi.fn().mockResolvedValue({
handle: 'terminal-1',
accepted: true,
bytesWritten: text.length
})
})
const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS })
const responsePromise = dispatcher.dispatch(
makeRequest('terminal.send', {
terminal: 'terminal-1',
text
})
)
await Promise.resolve()
expect(runtime.sendTerminal).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(0)
await expect(responsePromise).resolves.toMatchObject({
ok: true,
result: { send: { accepted: true } }
})
expect(runtime.sendTerminal).toHaveBeenCalledWith('terminal-1', {
text,
enter: false,
interrupt: false
})
})
it('routes terminal restore fit through the runtime driver state machine', async () => {
const runtime = stubRuntime({
resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }),