Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions mobile/src/session/MobileNativeChatMessage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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' }
}
Expand Down Expand Up @@ -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')
Expand Down
5 changes: 4 additions & 1 deletion mobile/src/session/MobileNativeChatOverlay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,10 @@ export function MobileNativeChatOverlay({
return null
}
return (
<MobileNativeChatRowOverlaysHost conversation={{ surfaceId: sendSurfaceId, sessionId }}>
<MobileNativeChatRowOverlaysHost
conversation={{ surfaceId: sendSurfaceId, sessionId }}
imageClient={controller.nativeChatVisualSource?.client}
>
<View style={styles.overlay}>
<MobileNativeChatVisualContext.Provider value={visuals}>
<MobileNativeChatRootItemSourceContext.Provider value={detailSource}>
Expand Down
38 changes: 31 additions & 7 deletions mobile/src/session/MobileNativeChatProse.tsx
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -12,8 +12,9 @@ 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 {
CHAT_PROSE_SCALE,
scaledType,
Expand Down Expand Up @@ -91,7 +92,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,
Expand All @@ -101,10 +102,33 @@ 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<{ 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({ path: storedPath, uri })
}
})
return () => unmounted.abort()
}, [imageClient, storedPath])
const read = storedPath && stored?.path === storedPath ? stored : null
const uri = renderable ?? read?.uri
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const label = block.alt ?? 'Attached image'
if (!isRenderableImageUri(uri)) {
if (storedPath && !read) {
return <View style={styles.imageThumb} accessibilityLabel={label} />
}
if (!uri) {
return (
<Text style={[styles.imageRef, { fontSize: TEXT_SIZE * fontScale }]}>
🖼 {block.alt ?? block.path ?? block.url ?? 'image'}
Expand Down
8 changes: 6 additions & 2 deletions mobile/src/session/MobileNativeChatRowOverlaysHost.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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(() => {
Expand Down
36 changes: 34 additions & 2 deletions mobile/src/session/mobile-native-chat-image-preview.test.ts
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand Down Expand Up @@ -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<RpcClient['sendRequest']>(
() => new Promise<RpcResponse>((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])
})
})
45 changes: 45 additions & 0 deletions mobile/src/session/mobile-native-chat-image-preview.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,51 @@
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<string | null> {
const release = await storedImageReads.acquire(0, signal).catch(() => null)
if (!release) {
return null
}
try {
const reply = await storedImageRead.request(
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
client,
{ path },
{ timeoutMs: 15_000, budgetSpansConnect: true }
Comment thread
AmoabaKelvin marked this conversation as resolved.
Resolved
)
const image = storedImageRead.interpret(reply)
return image?.isImage && image.content ? buildImageDataUri(image.mimeType, image.content) : null
} catch {
return null
} finally {
release()
}
}
3 changes: 3 additions & 0 deletions mobile/src/session/mobile-native-chat-row-overlays.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
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 }

// Keep overlays above replaceable rows so echo/transcript swaps cannot close a selected image or actions sheet.
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<MobileNativeChatRowOverlays>({
Expand Down
5 changes: 3 additions & 2 deletions src/main/runtime/mobile-rpc-allowlist.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
])
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
Loading