diff --git a/mobile/src/session/MobileNativeChatMessage.test.ts b/mobile/src/session/MobileNativeChatMessage.test.ts index 4584ded81b3b..92121f8d5698 100644 --- a/mobile/src/session/MobileNativeChatMessage.test.ts +++ b/mobile/src/session/MobileNativeChatMessage.test.ts @@ -20,6 +20,7 @@ import { colors, typography } from '../theme/mobile-theme' import { ANSWERED_PROMPT_ITEMS } from './mobile-native-chat-answered-prompts.test-fixture' import { MobileNativeChatRowOverlaysContext } from './mobile-native-chat-row-overlays' import { styles } from './mobile-native-chat-message-styles' +import { stubRpcClient } from '../transport/rpc-client-test-stub' vi.mock('react-native', async () => { const React = await import('react') @@ -82,6 +83,9 @@ vi.mock('./MobileNativeChatMessageActionsSheet', () => ({ import { MobileNativeChatMessage } from './MobileNativeChatMessage' import { findAllByHostType, findByHostType } from '../test-support/react-test-renderer-host-nodes' +const PNG = + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==' + function userMessage(blocks: NativeChatMessage['blocks']): NativeChatMessage { return { id: 'u1', role: 'user', blocks, timestamp: null, source: 'transcript' } } @@ -634,6 +638,43 @@ describe('MobileNativeChatMessage', () => { expect(texts.some((text) => text.includes('/tmp/host.png'))).toBe(true) }) + // An older host refuses the read; the row keeps today's placeholder. + it.each([ + [ + { ok: true, result: { content: PNG, isBinary: true, isImage: true, mimeType: 'image/png' } }, + [`data:image/png;base64,${PNG}`] + ], + [{ ok: false, error: { code: 'forbidden', message: 'not available to mobile clients' } }, []] + ] as const)('reads a stored image from the chat host: %j', async (reply, thumbnails) => { + const path = '/home/me/.orca/agent-session-attachments/6f1c2a4e/shot.png' + const sendRequest = vi.fn(async () => ({ id: '1', ...reply })) + await act(async () => { + renderer = create( + createElement( + MobileNativeChatRowOverlaysContext.Provider, + { + value: { + openImage: vi.fn(), + openActions: vi.fn(), + imageClient: stubRpcClient({ sendRequest }) + } + }, + createElement(MobileNativeChatMessage, { + message: userMessage([{ type: 'image-ref', path, alt: 'shot' }]) + }) + ) + ) + }) + expect(sendRequest).toHaveBeenCalledWith( + 'agentSessionAttachment.read', + { path }, + expect.anything() + ) + expect( + findAllByHostType(renderer!.root, 'Image').map((image) => image.props.source.uri) + ).toEqual(thumbnails) + }) + it('draws your message as selectable Markdown in the bubble’s dark-on-light colours', () => { const tree = render(userMessage([{ type: 'text', text: '**Fix** `src/a.ts`' }])) const markdown = findByHostType(tree.root, 'MobileMarkdown') diff --git a/mobile/src/session/MobileNativeChatOverlay.tsx b/mobile/src/session/MobileNativeChatOverlay.tsx index c7947c0c83f8..208301df7a23 100644 --- a/mobile/src/session/MobileNativeChatOverlay.tsx +++ b/mobile/src/session/MobileNativeChatOverlay.tsx @@ -125,7 +125,10 @@ export function MobileNativeChatOverlay({ return null } return ( - + diff --git a/mobile/src/session/MobileNativeChatProse.tsx b/mobile/src/session/MobileNativeChatProse.tsx index d78ea9a72dee..c181bea24ca6 100644 --- a/mobile/src/session/MobileNativeChatProse.tsx +++ b/mobile/src/session/MobileNativeChatProse.tsx @@ -1,5 +1,5 @@ -import { useContext } from 'react' -import { Image, Pressable, Text } from 'react-native' +import { useContext, useEffect, useState } from 'react' +import { Image, Pressable, Text, View } from 'react-native' import { INLINE_TEXT_SELECTION } from '../components/inline-text-selection' import { MobileMarkdown } from '../components/MobileMarkdown' import { isImageRefBlock, isTextBlock } from '../../../src/shared/native-chat-types' @@ -12,8 +12,10 @@ import { isAgentSessionHostStatusPresentation } from '../../../src/shared/agent-session-host-status-rows' import { withoutPendingNativeChatVisualDirectiveTail } from '../../../src/shared/native-chat-visual-directive' +import { isAgentSessionAttachmentStorePath } from '../../../src/shared/agent-session-attachments' import { MobileNativeChatRowOverlaysContext } from './mobile-native-chat-row-overlays' -import { isRenderableImageUri } from './mobile-native-chat-image-preview' +import { isRenderableImageUri, readStoredChatImage } from './mobile-native-chat-image-preview' +import type { RpcClient } from '../transport/rpc-client' import { CHAT_PROSE_SCALE, scaledType, @@ -91,7 +93,7 @@ export function Prose({ return null } -// Host paths cannot load on the phone; show a placeholder unless a preview or real URL exists. +// Host paths cannot load on the phone; the chat's host reads its attachment store, anything else stays a placeholder. function ImageAttachment({ block, fontScale, @@ -101,10 +103,38 @@ function ImageAttachment({ fontScale: number onLongPress?: () => void }): React.JSX.Element { - const { openImage } = useContext(MobileNativeChatRowOverlaysContext) - const uri = block.url ?? block.path + const { openImage, imageClient } = useContext(MobileNativeChatRowOverlaysContext) + const direct = block.url ?? block.path + const renderable = isRenderableImageUri(direct) ? direct : null + const storedPath = + !renderable && imageClient && block.path && isAgentSessionAttachmentStorePath(block.path) + ? block.path + : null + const [stored, setStored] = useState<{ + client: RpcClient + path: string + uri: string | null + } | null>(null) + useEffect(() => { + if (!imageClient || !storedPath) { + return + } + const unmounted = new AbortController() + void readStoredChatImage(imageClient, storedPath, unmounted.signal).then((uri) => { + if (!unmounted.signal.aborted) { + setStored({ client: imageClient, path: storedPath, uri }) + } + }) + return () => unmounted.abort() + }, [imageClient, storedPath]) + const read = + storedPath && stored?.path === storedPath && stored.client === imageClient ? stored : null + const uri = renderable ?? read?.uri const label = block.alt ?? 'Attached image' - if (!isRenderableImageUri(uri)) { + if (storedPath && !read) { + return + } + if (!uri) { return ( 🖼 {block.alt ?? block.path ?? block.url ?? 'image'} diff --git a/mobile/src/session/MobileNativeChatRowOverlaysHost.tsx b/mobile/src/session/MobileNativeChatRowOverlaysHost.tsx index f8d5f23c38b1..acb560630764 100644 --- a/mobile/src/session/MobileNativeChatRowOverlaysHost.tsx +++ b/mobile/src/session/MobileNativeChatRowOverlaysHost.tsx @@ -10,12 +10,15 @@ import { useMobileNativeChatConversationState, type MobileNativeChatConversation } from './use-mobile-native-chat-conversation-state' +import type { RpcClient } from '../transport/rpc-client' export function MobileNativeChatRowOverlaysHost({ conversation, + imageClient, children }: { conversation: MobileNativeChatConversation + imageClient?: RpcClient children?: React.ReactNode }): React.JSX.Element { // Keep pressed message text with its conversation so streaming cannot rewrite an open sheet. @@ -26,9 +29,10 @@ export function MobileNativeChatRowOverlaysHost({ const overlays = useMemo( () => ({ openImage: (image: MobileNativeChatViewedImage) => setShown({ image }), - openActions: (actionsFor: NativeChatMessage) => setShown({ actionsFor }) + openActions: (actionsFor: NativeChatMessage) => setShown({ actionsFor }), + imageClient }), - [setShown] + [setShown, imageClient] ) // Memoize overlay callbacks so streamed words cannot rebuild them. const opened = useMemo(() => { diff --git a/mobile/src/session/mobile-native-chat-image-preview.test.ts b/mobile/src/session/mobile-native-chat-image-preview.test.ts index 93078fd654ad..71d386358749 100644 --- a/mobile/src/session/mobile-native-chat-image-preview.test.ts +++ b/mobile/src/session/mobile-native-chat-image-preview.test.ts @@ -1,5 +1,8 @@ -import { describe, expect, it } from 'vitest' -import { isRenderableImageUri } from './mobile-native-chat-image-preview' +import { describe, expect, it, vi } from 'vitest' +import { stubRpcClient } from '../transport/rpc-client-test-stub' +import type { RpcClient } from '../transport/rpc-client' +import type { RpcResponse } from '../transport/types' +import { isRenderableImageUri, readStoredChatImage } from './mobile-native-chat-image-preview' describe('isRenderableImageUri', () => { it('accepts local previews and real URLs the device can load', () => { @@ -29,3 +32,32 @@ describe('isRenderableImageUri', () => { } }) }) + +describe('readStoredChatImage', () => { + it('reads two images at a time and drops reads whose row went away while queued', async () => { + const replies: ((reply: RpcResponse) => void)[] = [] + const sendRequest = vi.fn( + () => new Promise((resolve) => replies.push(resolve)) + ) + const client = stubRpcClient({ sendRequest }) + const gone = new AbortController() + const reads = [ + readStoredChatImage(client, '/a.png', new AbortController().signal), + readStoredChatImage(client, '/b.png', new AbortController().signal), + readStoredChatImage(client, '/c.png', gone.signal), + readStoredChatImage(client, '/d.png', new AbortController().signal) + ] + await vi.waitFor(() => expect(sendRequest).toHaveBeenCalledTimes(2)) + gone.abort() + replies[0]!({ id: '1', ok: false, error: { code: 'forbidden', message: 'refused' } }) + await vi.waitFor(() => expect(sendRequest).toHaveBeenCalledTimes(3)) + expect(sendRequest.mock.calls.map((call) => call[1])).toEqual([ + { path: '/a.png' }, + { path: '/b.png' }, + { path: '/d.png' } + ]) + replies[1]!({ id: '2', ok: false, error: { code: 'forbidden', message: 'refused' } }) + replies[2]!({ id: '3', ok: false, error: { code: 'forbidden', message: 'refused' } }) + await expect(Promise.all(reads)).resolves.toEqual([null, null, null, null]) + }) +}) diff --git a/mobile/src/session/mobile-native-chat-image-preview.ts b/mobile/src/session/mobile-native-chat-image-preview.ts index e0bc6f9214d1..559e52406737 100644 --- a/mobile/src/session/mobile-native-chat-image-preview.ts +++ b/mobile/src/session/mobile-native-chat-image-preview.ts @@ -1,6 +1,52 @@ +import { buildImageDataUri } from '../../../src/shared/image-data-uri' +import { PrioritySemaphore } from '../../../src/shared/priority-semaphore' +import { filePreviewImageSchema } from '../files/file-preview-reply-schema' +import { bindDeferredRpcOperation, defineRpcOperation } from '../transport/rpc-operation' +import { rpcResultVariant } from '../transport/rpc-operation-result-reader' +import type { RpcClient } from '../transport/rpc-client' + // Accept device-loadable URI schemes only; a bare host/SSH path must remain a text placeholder. const RENDERABLE_IMAGE_URI = /^(file:|data:|https?:|content:|blob:)/i export function isRenderableImageUri(uri: string | undefined): uri is string { return typeof uri === 'string' && RENDERABLE_IMAGE_URI.test(uri) } + +const storedImageRead = bindDeferredRpcOperation( + defineRpcOperation({ + name: 'agent-session-attachment.read-image', + method: 'agentSessionAttachment.read', + acceptance: 'object-result-or-null', + barrier: 'after-caller-barrier', + read: rpcResultVariant('chat-attachment-image', filePreviewImageSchema) + }) +) + +// Each reply can be megabytes; a burst over a slow link overflows the host's outbound queue, which drops the socket. +const storedImageReads = new PrioritySemaphore(2) + +// Null on any failure, including older hosts that refuse this method to phones: the row keeps its placeholder. +export async function readStoredChatImage( + client: RpcClient, + path: string, + signal: AbortSignal +): Promise { + const release = await storedImageReads.acquire(0, signal).catch(() => null) + if (!release || signal.aborted) { + release?.() + return null + } + try { + const reply = await storedImageRead.request( + client, + { path }, + { timeoutMs: 15_000, budgetSpansConnect: true } + ) + const image = storedImageRead.interpret(reply) + return image?.isImage && image.content ? buildImageDataUri(image.mimeType, image.content) : null + } catch { + return null + } finally { + release() + } +} diff --git a/mobile/src/session/mobile-native-chat-row-overlays.ts b/mobile/src/session/mobile-native-chat-row-overlays.ts index 1354ef56fcba..ffe9834cb654 100644 --- a/mobile/src/session/mobile-native-chat-row-overlays.ts +++ b/mobile/src/session/mobile-native-chat-row-overlays.ts @@ -1,5 +1,6 @@ import { createContext } from 'react' import type { NativeChatMessage } from '../../../src/shared/native-chat-types' +import type { RpcClient } from '../transport/rpc-client' export type MobileNativeChatViewedImage = { uri: string; label: string } @@ -7,6 +8,8 @@ export type MobileNativeChatViewedImage = { uri: string; label: string } export type MobileNativeChatRowOverlays = { openImage: (image: MobileNativeChatViewedImage) => void openActions: (message: NativeChatMessage) => void + /** A structured chat's host client, which reads images from its attachment store. */ + imageClient?: RpcClient } export const MobileNativeChatRowOverlaysContext = createContext({ diff --git a/src/main/runtime/mobile-rpc-allowlist.test.ts b/src/main/runtime/mobile-rpc-allowlist.test.ts index fa59fa77ffa3..bb1e14683e5f 100644 --- a/src/main/runtime/mobile-rpc-allowlist.test.ts +++ b/src/main/runtime/mobile-rpc-allowlist.test.ts @@ -228,14 +228,15 @@ describe('mobile RPC allowlist', () => { expect(mobileRpcAllowlist().has('agentSession.attach')).toBe(false) }) - it('lets a phone upload chat attachments but not read the store back', () => { + it('lets a phone upload chat attachments and read stored images back', () => { expect( [...mobileRpcAllowlist()].filter((method) => method.startsWith('agentSessionAttachment.')) ).toEqual([ 'agentSessionAttachment.uploadStart', 'agentSessionAttachment.uploadAppend', 'agentSessionAttachment.uploadCommit', - 'agentSessionAttachment.uploadAbort' + 'agentSessionAttachment.uploadAbort', + 'agentSessionAttachment.read' ]) }) }) diff --git a/src/main/runtime/runtime-rpc/runtime-rpc-mobile-agent-session-methods.ts b/src/main/runtime/runtime-rpc/runtime-rpc-mobile-agent-session-methods.ts index 00d2758720a6..24a29f566aa0 100644 --- a/src/main/runtime/runtime-rpc/runtime-rpc-mobile-agent-session-methods.ts +++ b/src/main/runtime/runtime-rpc/runtime-rpc-mobile-agent-session-methods.ts @@ -35,6 +35,8 @@ export const MOBILE_AGENT_SESSION_RPC_METHODS = [ 'agentSessionAttachment.uploadAppend', 'agentSessionAttachment.uploadCommit', 'agentSessionAttachment.uploadAbort', + // Stored images back as previews when the phone has no copy of its own. + 'agentSessionAttachment.read', // No-ops on a current host; kept until MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION passes the // mobile builds that still call them. 'agentSession.hold',