feat(mobile): paste clipboard images into terminals (#5264)
This commit is contained in:
@@ -130,6 +130,10 @@ import {
|
||||
type MobileNewTabAgentOption,
|
||||
type MobileNewTabAgentSettings
|
||||
} from '../../../../src/session/mobile-new-tab-agent-options'
|
||||
import {
|
||||
buildMobileImagePastePayload,
|
||||
saveMobileClipboardImageAsTempFile
|
||||
} from '../../../../src/session/mobile-clipboard-image'
|
||||
import { resolveMarkdownFloatingActionsBottom } from '../../../../src/session/markdown-floating-actions-layout'
|
||||
import { resolveTabStripScrollOffset } from '../../../../src/session/tab-strip-scroll'
|
||||
import {
|
||||
@@ -3196,30 +3200,64 @@ export default function SessionScreen() {
|
||||
}
|
||||
}, [])
|
||||
|
||||
const getActiveWorktreeConnectionId = useCallback(async (): Promise<string | null> => {
|
||||
if (!client) {
|
||||
return null
|
||||
}
|
||||
const repoId = getRepoIdFromMobileWorktreeId(worktreeId)
|
||||
const repoResponse = await client.sendRequest('repo.list')
|
||||
if (!repoResponse.ok) {
|
||||
throw new Error((repoResponse as RpcFailure).error.message)
|
||||
}
|
||||
const repos = ((repoResponse as RpcSuccess).result as { repos?: RuntimeRepoSummary[] }).repos ?? []
|
||||
return repos.find((repo) => repo.id === repoId)?.connectionId?.trim() || null
|
||||
}, [client, worktreeId])
|
||||
|
||||
const refreshCanPaste = useCallback(() => {
|
||||
void Promise.all([
|
||||
Clipboard.hasStringAsync().catch(() => false),
|
||||
Clipboard.hasImageAsync().catch(() => false)
|
||||
]).then(([hasString, hasImage]) => {
|
||||
setCanPaste(hasString || hasImage)
|
||||
})
|
||||
}, [])
|
||||
|
||||
const handlePaste = useCallback(async () => {
|
||||
if (!client || !activeHandle || !canSend) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
const text = await Clipboard.getStringAsync()
|
||||
if (text.length === 0) {
|
||||
return
|
||||
let payload: string | null = null
|
||||
if (text.length > 0) {
|
||||
const modes = ptyModesRef.current.get(activeHandle) || {
|
||||
bracketedPasteMode: false,
|
||||
altScreen: false,
|
||||
mouseTrackingMode: 'none',
|
||||
sgrMouseMode: false,
|
||||
sgrMousePixelsMode: false
|
||||
}
|
||||
const wrap = modes.bracketedPasteMode && !modes.altScreen
|
||||
// Why: strip embedded bracketed-paste markers from clipboard text so a
|
||||
// malicious copy containing `\x1b[201~` can't terminate paste mode early
|
||||
// and have the trailing bytes interpreted as shell commands. Matches
|
||||
// xterm.js / iTerm2 behavior.
|
||||
// eslint-disable-next-line no-control-regex -- intentional bracketed-paste marker stripping
|
||||
const sanitized = wrap ? text.replace(/\x1b\[20[01]~/g, '') : text
|
||||
payload = wrap ? `\x1b[200~${sanitized}\x1b[201~` : sanitized
|
||||
} else {
|
||||
const image = await Clipboard.getImageAsync({ format: 'png' })
|
||||
if (!image) {
|
||||
refreshCanPaste()
|
||||
return
|
||||
}
|
||||
const connectionId = await getActiveWorktreeConnectionId()
|
||||
const imagePath = await saveMobileClipboardImageAsTempFile(client, image.data, {
|
||||
connectionId
|
||||
})
|
||||
payload = buildMobileImagePastePayload(imagePath)
|
||||
}
|
||||
const modes = ptyModesRef.current.get(activeHandle) || {
|
||||
bracketedPasteMode: false,
|
||||
altScreen: false,
|
||||
mouseTrackingMode: 'none',
|
||||
sgrMouseMode: false,
|
||||
sgrMousePixelsMode: false
|
||||
}
|
||||
const wrap = modes.bracketedPasteMode && !modes.altScreen
|
||||
// Why: strip embedded bracketed-paste markers from clipboard text so a
|
||||
// malicious copy containing `\x1b[201~` can't terminate paste mode early
|
||||
// and have the trailing bytes interpreted as shell commands. Matches
|
||||
// xterm.js / iTerm2 behavior.
|
||||
// eslint-disable-next-line no-control-regex -- intentional bracketed-paste marker stripping
|
||||
const sanitized = wrap ? text.replace(/\x1b\[20[01]~/g, '') : text
|
||||
const payload = wrap ? `\x1b[200~${sanitized}\x1b[201~` : sanitized
|
||||
|
||||
const wrappedBytes = new TextEncoder().encode(payload).byteLength
|
||||
if (wrappedBytes > 256 * 1024) {
|
||||
triggerError()
|
||||
@@ -3237,7 +3275,7 @@ export default function SessionScreen() {
|
||||
: {})
|
||||
})
|
||||
triggerSelection()
|
||||
void Clipboard.hasStringAsync().then(setCanPaste)
|
||||
refreshCanPaste()
|
||||
} catch (e) {
|
||||
triggerError()
|
||||
const err = e as { name?: string; message?: string }
|
||||
@@ -3246,17 +3284,24 @@ export default function SessionScreen() {
|
||||
console.warn('[mobile-clip] paste failed', { name: err.name, message: err.message })
|
||||
if (isDisconnected) {
|
||||
showToast('Paste failed (disconnected)', 1500)
|
||||
} else if (err.message === 'Clipboard image is too large') {
|
||||
showToast('Image too large to paste', 1500)
|
||||
} else {
|
||||
showToast('Paste failed', 1500)
|
||||
}
|
||||
}
|
||||
}, [client, activeHandle, canSend, connState, showToast])
|
||||
}, [client, activeHandle, canSend, connState, getActiveWorktreeConnectionId, refreshCanPaste, showToast])
|
||||
|
||||
// Why: refresh canPaste on mount, AppState active, after paste.
|
||||
useEffect(() => {
|
||||
let mounted = true
|
||||
const refresh = () => {
|
||||
void Clipboard.hasStringAsync().then((has) => {
|
||||
void Promise.all([
|
||||
Clipboard.hasStringAsync().catch(() => false),
|
||||
Clipboard.hasImageAsync().catch(() => false)
|
||||
]).then(([hasString, hasImage]) => {
|
||||
if (mounted) {
|
||||
setCanPaste(has)
|
||||
setCanPaste(hasString || hasImage)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
buildMobileImagePastePayload,
|
||||
MOBILE_CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS,
|
||||
normalizeMobileClipboardImageBase64,
|
||||
saveMobileClipboardImageAsTempFile
|
||||
} from './mobile-clipboard-image'
|
||||
import type { RpcClient } from '../transport/rpc-client'
|
||||
import type { RpcFailure, RpcResponse, RpcSuccess } from '../transport/types'
|
||||
|
||||
function ok(id: string, result: unknown): RpcSuccess {
|
||||
return { id, ok: true, result, _meta: { runtimeId: 'runtime-1' } }
|
||||
}
|
||||
|
||||
function fail(id: string, code: string, message: string): RpcFailure {
|
||||
return { id, ok: false, error: { code, message }, _meta: { runtimeId: 'runtime-1' } }
|
||||
}
|
||||
|
||||
function clientWithResponses(responses: RpcResponse[]): Pick<RpcClient, 'sendRequest'> & {
|
||||
calls: Array<{ method: string; params: unknown }>
|
||||
} {
|
||||
const calls: Array<{ method: string; params: unknown }> = []
|
||||
return {
|
||||
calls,
|
||||
sendRequest: vi.fn(async (method: string, params?: unknown) => {
|
||||
calls.push({ method, params })
|
||||
const response = responses.shift()
|
||||
if (!response) {
|
||||
throw new Error(`unexpected request: ${method}`)
|
||||
}
|
||||
return response
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
describe('mobile clipboard image paste helpers', () => {
|
||||
it('strips data URL image prefixes', () => {
|
||||
expect(normalizeMobileClipboardImageBase64('data:image/png;base64,aGVsbG8=')).toBe('aGVsbG8=')
|
||||
})
|
||||
|
||||
it('rejects non-base64 image data', () => {
|
||||
expect(() => normalizeMobileClipboardImageBase64('not base64!')).toThrow(
|
||||
'Clipboard image content must be base64'
|
||||
)
|
||||
})
|
||||
|
||||
it('uploads mobile clipboard images in ordered chunks and commits', async () => {
|
||||
const base64 = 'a'.repeat(MOBILE_CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS + 4)
|
||||
const client = clientWithResponses([
|
||||
ok('start', { uploadId: 'upload-1' }),
|
||||
ok('append-1', { receivedBase64Length: MOBILE_CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS }),
|
||||
ok('append-2', { receivedBase64Length: base64.length }),
|
||||
ok('commit', '/tmp/orca-paste-image.png')
|
||||
])
|
||||
|
||||
await expect(
|
||||
saveMobileClipboardImageAsTempFile(client, `data:image/png;base64,${base64}`, {
|
||||
connectionId: 'ssh-1'
|
||||
})
|
||||
).resolves.toBe('/tmp/orca-paste-image.png')
|
||||
|
||||
expect(client.calls).toEqual([
|
||||
{
|
||||
method: 'clipboard.startImageUpload',
|
||||
params: { expectedBase64Length: base64.length, connectionId: 'ssh-1' }
|
||||
},
|
||||
{
|
||||
method: 'clipboard.appendImageUploadChunk',
|
||||
params: {
|
||||
uploadId: 'upload-1',
|
||||
offset: 0,
|
||||
contentBase64: base64.slice(0, MOBILE_CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS)
|
||||
}
|
||||
},
|
||||
{
|
||||
method: 'clipboard.appendImageUploadChunk',
|
||||
params: {
|
||||
uploadId: 'upload-1',
|
||||
offset: MOBILE_CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS,
|
||||
contentBase64: base64.slice(MOBILE_CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS)
|
||||
}
|
||||
},
|
||||
{ method: 'clipboard.commitImageUpload', params: { uploadId: 'upload-1' } }
|
||||
])
|
||||
})
|
||||
|
||||
it('falls back to the legacy single-frame image save method when needed', async () => {
|
||||
const client = clientWithResponses([
|
||||
fail('start', 'method_not_found', 'missing'),
|
||||
ok('save', '/tmp/orca-paste-image.png')
|
||||
])
|
||||
|
||||
await expect(saveMobileClipboardImageAsTempFile(client, 'aGVsbG8=')).resolves.toBe(
|
||||
'/tmp/orca-paste-image.png'
|
||||
)
|
||||
|
||||
expect(client.calls).toEqual([
|
||||
{
|
||||
method: 'clipboard.startImageUpload',
|
||||
params: { expectedBase64Length: 8, connectionId: null }
|
||||
},
|
||||
{
|
||||
method: 'clipboard.saveImageAsTempFile',
|
||||
params: { contentBase64: 'aGVsbG8=', connectionId: null }
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it('aborts chunked upload state when append fails', async () => {
|
||||
const client = clientWithResponses([
|
||||
ok('start', { uploadId: 'upload-1' }),
|
||||
fail('append', 'invalid_argument', 'bad chunk'),
|
||||
ok('abort', { aborted: true })
|
||||
])
|
||||
|
||||
await expect(saveMobileClipboardImageAsTempFile(client, 'aGVsbG8=')).rejects.toThrow(
|
||||
'bad chunk'
|
||||
)
|
||||
expect(client.calls.at(-1)).toEqual({
|
||||
method: 'clipboard.abortImageUpload',
|
||||
params: { uploadId: 'upload-1' }
|
||||
})
|
||||
})
|
||||
|
||||
it('brackets generated image paths before sending to the terminal', () => {
|
||||
expect(buildMobileImagePastePayload('/tmp/orca.png')).toBe('\x1b[200~/tmp/orca.png\x1b[201~')
|
||||
expect(buildMobileImagePastePayload('/tmp/\x1b.png')).toBe(
|
||||
'\x1b[200~/tmp/\u241b.png\x1b[201~'
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { RpcClient } from '../transport/rpc-client'
|
||||
import type { RpcFailure, RpcSuccess } from '../transport/types'
|
||||
|
||||
export const MOBILE_CLIPBOARD_IMAGE_MAX_BASE64_CHARS = 24 * 1024 * 1024
|
||||
export const MOBILE_CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS = 512 * 1024
|
||||
export const MOBILE_CLIPBOARD_IMAGE_SINGLE_FRAME_FALLBACK_BASE64_CHARS = 256 * 1024
|
||||
|
||||
const DATA_URL_PREFIX_RE = /^data:image\/[a-z0-9.+-]+;base64,/i
|
||||
const BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/
|
||||
|
||||
export function normalizeMobileClipboardImageBase64(data: string): string {
|
||||
const contentBase64 = data.replace(DATA_URL_PREFIX_RE, '')
|
||||
if (contentBase64.length > MOBILE_CLIPBOARD_IMAGE_MAX_BASE64_CHARS) {
|
||||
throw new Error('Clipboard image is too large')
|
||||
}
|
||||
if (contentBase64.length % 4 === 1 || !BASE64_PATTERN.test(contentBase64)) {
|
||||
throw new Error('Clipboard image content must be base64')
|
||||
}
|
||||
return contentBase64
|
||||
}
|
||||
|
||||
function assertSuccess<T>(response: RpcSuccess | RpcFailure): T {
|
||||
if (!response.ok) {
|
||||
throw new Error(response.error.message)
|
||||
}
|
||||
return response.result as T
|
||||
}
|
||||
|
||||
export async function saveMobileClipboardImageAsTempFile(
|
||||
client: Pick<RpcClient, 'sendRequest'>,
|
||||
imageData: string,
|
||||
args?: { connectionId?: string | null }
|
||||
): Promise<string> {
|
||||
const contentBase64 = normalizeMobileClipboardImageBase64(imageData)
|
||||
const connectionId = args?.connectionId ?? null
|
||||
const startResponse = await client.sendRequest('clipboard.startImageUpload', {
|
||||
expectedBase64Length: contentBase64.length,
|
||||
connectionId
|
||||
})
|
||||
|
||||
if (!startResponse.ok) {
|
||||
if (
|
||||
startResponse.error.code === 'method_not_found' &&
|
||||
contentBase64.length <= MOBILE_CLIPBOARD_IMAGE_SINGLE_FRAME_FALLBACK_BASE64_CHARS
|
||||
) {
|
||||
return assertSuccess<string>(
|
||||
await client.sendRequest('clipboard.saveImageAsTempFile', { contentBase64, connectionId })
|
||||
)
|
||||
}
|
||||
throw new Error(startResponse.error.message)
|
||||
}
|
||||
|
||||
const { uploadId } = startResponse.result as { uploadId: string }
|
||||
try {
|
||||
for (
|
||||
let offset = 0;
|
||||
offset < contentBase64.length;
|
||||
offset += MOBILE_CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS
|
||||
) {
|
||||
assertSuccess(
|
||||
await client.sendRequest('clipboard.appendImageUploadChunk', {
|
||||
uploadId,
|
||||
offset,
|
||||
contentBase64: contentBase64.slice(
|
||||
offset,
|
||||
offset + MOBILE_CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS
|
||||
)
|
||||
})
|
||||
)
|
||||
}
|
||||
return assertSuccess<string>(
|
||||
await client.sendRequest('clipboard.commitImageUpload', { uploadId })
|
||||
)
|
||||
} catch (error) {
|
||||
// Why: failed mobile image sends create server-side upload state; abort so
|
||||
// the bounded upload slot is released immediately instead of waiting for TTL.
|
||||
await client.sendRequest('clipboard.abortImageUpload', { uploadId }).catch(() => {})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export function buildMobileImagePastePayload(filePath: string): string {
|
||||
// Why: generated image paths are paste payloads, not ordinary typed input.
|
||||
// Bracket the path even when it is one line so agents receive it atomically
|
||||
// and stale terminal paste state cannot turn it into shell commands.
|
||||
return `\x1b[200~${filePath.split('\x1b').join('\u241b')}\x1b[201~`
|
||||
}
|
||||
Reference in New Issue
Block a user