]*>([\s\S]*?)<\/h\1>/gi, (_tag, level, inner) => {
+ const text = stripTags(normalizeInlineHtml(inner))
+ return text ? `\n${'#'.repeat(Number(level))} ${text}\n` : '\n'
+ })
+ next = next.replace(/]*>([\s\S]*?)<\/p>/gi, (_tag, inner) => {
+ const text = stripTags(normalizeInlineHtml(inner))
+ return text ? `\n${text}\n` : '\n'
+ })
+ next = next.replace(/]*>([\s\S]*?)<\/sub>/gi, (_tag, inner) =>
+ stripTags(normalizeInlineHtml(inner))
+ )
+ next = normalizeInlineHtml(next)
+ next = stripTags(next)
+
+ return restoreEscapedHtmlEntities(next)
+}
diff --git a/mobile/src/files/MobileFileExplorerPanel.tsx b/mobile/src/files/MobileFileExplorerPanel.tsx
index 10df79199..8192eb900 100644
--- a/mobile/src/files/MobileFileExplorerPanel.tsx
+++ b/mobile/src/files/MobileFileExplorerPanel.tsx
@@ -21,7 +21,6 @@ import {
} from 'lucide-react-native'
import { useHostClient, useForceReconnect } from '../transport/client-context'
import { getWorktreeLabel } from '../session/worktree-label'
-import { classifyMobileArtifact } from '../session/mobile-artifact-kind'
import {
buildTree,
flattenTree,
@@ -31,9 +30,13 @@ import {
type TreeNode
} from './file-tree'
import type { RpcSuccess } from '../transport/types'
-import { triggerError, triggerSelection } from '../platform/haptics'
+import { triggerSelection } from '../platform/haptics'
import { colors, spacing } from '../theme/mobile-theme'
import { fileExplorerStyles as styles } from './mobile-file-explorer-styles'
+import {
+ canPreviewMobileFileRow,
+ navigateToMobileFilePreview
+} from './mobile-file-preview-navigation'
export function MobileFileExplorerPanel(props: {
hostId: string
@@ -50,7 +53,6 @@ export function MobileFileExplorerPanel(props: {
const [expanded, setExpanded] = useState>(() => new Set())
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
- const [openingPath, setOpeningPath] = useState(null)
const [truncated, setTruncated] = useState(false)
const worktreeLabel = getWorktreeLabel(name, worktreeId)
@@ -96,36 +98,22 @@ export function MobileFileExplorerPanel(props: {
})
}, [])
- const openFile = useCallback(
- async (relativePath: string) => {
- if (!client) {
- return
- }
- setOpeningPath(relativePath)
- try {
- const response = await client.sendRequest('files.open', {
- worktree: `id:${worktreeId}`,
- relativePath
- })
- if (!response.ok) {
- throw new Error(response.error?.message || 'Unable to open file')
- }
- triggerSelection()
- // The file now opens in the session. Full-screen pops back to it; when
- // docked the session is already visible, so just close the panel.
- if (embedded) {
- onRequestClose?.()
- } else {
- router.back()
- }
- } catch (err) {
- triggerError()
- setError(err instanceof Error ? err.message : 'Unable to open file')
- } finally {
- setOpeningPath(null)
- }
+ const previewFile = useCallback(
+ (relativePath: string, displayName: string) => {
+ triggerSelection()
+ navigateToMobileFilePreview(
+ router,
+ {
+ hostId,
+ worktreeId,
+ relativePath,
+ name: displayName,
+ worktreeName: name
+ },
+ { embedded, onRequestClose }
+ )
},
- [client, embedded, onRequestClose, router, worktreeId]
+ [embedded, hostId, name, onRequestClose, router, worktreeId]
)
const renderItem: ListRenderItem = ({ item }) => {
@@ -133,8 +121,11 @@ export function MobileFileExplorerPanel(props: {
const isExpanded = expanded.has(item.relativePath)
// Images render in the mobile viewer (via files.readPreview), so a binary
// image is openable; only non-previewable binaries are unavailable.
- const isImage = item.kind === 'binary' && classifyMobileArtifact(item.relativePath) === 'image'
- const disabled = item.kind === 'binary' && !isImage
+ const previewable =
+ item.kind !== 'directory' &&
+ canPreviewMobileFileRow({ kind: item.kind, relativePath: item.relativePath })
+ const isImage = item.kind === 'binary' && previewable
+ const disabled = item.kind === 'binary' && !previewable
const markdown = item.kind === 'text' && isMarkdownPath(item.relativePath)
return (
{
if (isDirectory) {
toggleDirectory(item.relativePath)
} else if (!disabled) {
- void openFile(item.relativePath)
+ previewFile(item.relativePath, item.name)
}
}}
accessibilityLabel={
@@ -157,7 +148,7 @@ export function MobileFileExplorerPanel(props: {
? `Open folder ${item.name}`
: disabled
? `${item.name} unavailable on mobile`
- : `Open file ${item.name}`
+ : `Preview file ${item.name}`
}
>
{isDirectory ? (
@@ -184,9 +175,6 @@ export function MobileFileExplorerPanel(props: {
{disabled ? Unavailable on mobile : null}
- {openingPath === item.relativePath ? (
-
- ) : null}
)
}
diff --git a/mobile/src/files/MobileFileMarkdownPreview.tsx b/mobile/src/files/MobileFileMarkdownPreview.tsx
new file mode 100644
index 000000000..b6e32f47e
--- /dev/null
+++ b/mobile/src/files/MobileFileMarkdownPreview.tsx
@@ -0,0 +1,69 @@
+import { useState } from 'react'
+import { Pressable, ScrollView, View } from 'react-native'
+import { Code, Pencil } from 'lucide-react-native'
+import { MobileMarkdown } from '../components/MobileMarkdown'
+import { colors } from '../theme/mobile-theme'
+import {
+ MobileFilePreviewSourceText,
+ MobileFilePreviewTruncatedNote
+} from './MobileFilePreviewSourceText'
+import { filePreviewStyles as styles } from './mobile-file-preview-styles'
+
+type Props = {
+ relativePath: string
+ content: string
+ truncated: boolean
+ byteLength: number
+}
+
+export function MobileFileMarkdownPreview({ relativePath, content, truncated, byteLength }: Props) {
+ const [mode, setMode] = useState<'preview' | 'source'>('preview')
+ const previewSelected = mode === 'preview'
+ const sourceSelected = mode === 'source'
+
+ return (
+
+
+ setMode('source')}
+ accessibilityRole="button"
+ accessibilityState={{ selected: sourceSelected }}
+ accessibilityLabel="View Markdown source"
+ >
+
+
+ setMode('preview')}
+ accessibilityRole="button"
+ accessibilityState={{ selected: previewSelected }}
+ accessibilityLabel="View rendered Markdown preview"
+ >
+
+
+
+ {mode === 'preview' ? (
+
+ {truncated ? : null}
+
+
+ ) : (
+
+ )}
+
+ )
+}
diff --git a/mobile/src/files/MobileFilePreviewScreen.tsx b/mobile/src/files/MobileFilePreviewScreen.tsx
new file mode 100644
index 000000000..13bd70547
--- /dev/null
+++ b/mobile/src/files/MobileFilePreviewScreen.tsx
@@ -0,0 +1,220 @@
+import { useCallback, useEffect, useState } from 'react'
+import {
+ ActivityIndicator,
+ Image,
+ Pressable,
+ ScrollView,
+ Text,
+ View,
+ useWindowDimensions
+} from 'react-native'
+import { SafeAreaView } from 'react-native-safe-area-context'
+import { useRouter } from 'expo-router'
+import { ChevronLeft } from 'lucide-react-native'
+import { getWorktreeLabel } from '../session/worktree-label'
+import { colors, spacing } from '../theme/mobile-theme'
+import { useForceReconnect, useHostClient } from '../transport/client-context'
+import {
+ loadMobileFilePreview,
+ previewError,
+ type MobileFilePreviewResult
+} from './mobile-file-preview-request'
+import { MobileFileMarkdownPreview } from './MobileFileMarkdownPreview'
+import { MobileFilePreviewSourceText } from './MobileFilePreviewSourceText'
+import {
+ displayNameFromPreviewPath,
+ type MobileFilePreviewRouteState
+} from './mobile-file-preview-route'
+import { filePreviewStyles as styles } from './mobile-file-preview-styles'
+
+type Props = {
+ route: MobileFilePreviewRouteState
+}
+
+export function MobileFilePreviewScreen({ route }: Props) {
+ const router = useRouter()
+ const previewParams = route.ok ? route.params : null
+ const { client, state: connState } = useHostClient(previewParams?.hostId)
+ const forceReconnect = useForceReconnect()
+ const [preview, setPreview] = useState(() =>
+ route.ok ? { status: 'loading', message: 'Loading preview...' } : previewError(route.message)
+ )
+ const { width, height } = useWindowDimensions()
+
+ const loadPreview = useCallback(async () => {
+ if (!previewParams) {
+ setPreview(previewError(route.ok ? 'Unable to load preview' : route.message))
+ return
+ }
+ if (!client || connState !== 'connected') {
+ setPreview({ status: 'waiting', message: 'Waiting for desktop...', reconnect: true })
+ return
+ }
+ setPreview({ status: 'loading', message: 'Loading preview...' })
+ try {
+ const result = await loadMobileFilePreview(
+ client,
+ previewParams.worktreeId,
+ previewParams.relativePath
+ )
+ setPreview(result)
+ } catch (err) {
+ const message = err instanceof Error ? err.message : 'Unable to load preview'
+ setPreview(previewError(message))
+ }
+ }, [client, connState, previewParams, route])
+
+ useEffect(() => {
+ void loadPreview()
+ }, [loadPreview])
+
+ const retry = useCallback(async () => {
+ if (!previewParams) {
+ void loadPreview()
+ return
+ }
+ if (
+ preview.status === 'waiting' ||
+ (preview.status === 'error' && preview.reconnect) ||
+ connState !== 'connected'
+ ) {
+ await forceReconnect(previewParams.hostId)
+ return
+ }
+ void loadPreview()
+ }, [connState, forceReconnect, loadPreview, preview, previewParams])
+
+ const title = previewParams?.name ?? displayNameFromPreviewPath(previewParams?.relativePath ?? '')
+ const worktreeLabel = getWorktreeLabel(
+ previewParams?.worktreeName,
+ previewParams?.worktreeId ?? ''
+ )
+ const meta = previewParams ? `${worktreeLabel} - ${previewParams.relativePath}` : 'Preview'
+
+ return (
+
+
+
+ [styles.backButton, pressed && styles.backButtonPressed]}
+ onPress={() => router.back()}
+ hitSlop={8}
+ accessibilityLabel="Back to files"
+ >
+
+
+
+
+ {title || 'Preview'}
+
+
+ {meta}
+
+
+
+
+ {renderPreviewBody(preview, {
+ relativePath: previewParams?.relativePath ?? '',
+ title: title || 'File',
+ imageWidth: Math.max(1, width - spacing.md * 2),
+ imageHeight: Math.max(240, height - 160),
+ onImageError: () =>
+ setPreview({ status: 'error', message: 'Unable to load preview', reconnect: false }),
+ onRetry: retry
+ })}
+
+ )
+}
+
+function renderPreviewBody(
+ preview: MobileFilePreviewResult,
+ options: {
+ relativePath: string
+ title: string
+ imageWidth: number
+ imageHeight: number
+ onImageError: () => void
+ onRetry: () => void
+ }
+) {
+ if (preview.status === 'loading') {
+ return (
+
+
+ {preview.message}
+
+ )
+ }
+
+ if (preview.status === 'error' || preview.status === 'waiting') {
+ return (
+
+ {preview.message}
+
+ Retry
+
+
+ )
+ }
+
+ if (preview.status === 'empty') {
+ return (
+
+ Empty file
+
+ )
+ }
+
+ if (preview.kind === 'image') {
+ return (
+
+
+
+
+
+ )
+ }
+
+ if (preview.kind === 'markdown') {
+ return (
+
+ )
+ }
+
+ if (preview.kind === 'html') {
+ return (
+
+ )
+ }
+
+ return (
+
+ )
+}
diff --git a/mobile/src/files/MobileFilePreviewSourceText.tsx b/mobile/src/files/MobileFilePreviewSourceText.tsx
new file mode 100644
index 000000000..408870d01
--- /dev/null
+++ b/mobile/src/files/MobileFilePreviewSourceText.tsx
@@ -0,0 +1,41 @@
+import { useMemo } from 'react'
+import { ScrollView, Text } from 'react-native'
+import { MobileSyntaxSegments } from '../components/MobileSyntaxSegments'
+import { formatPreviewByteLength } from './mobile-file-preview-request'
+import { buildMobileFilePreviewSyntax } from './mobile-file-preview-syntax'
+import { filePreviewStyles as styles } from './mobile-file-preview-styles'
+
+export function MobileFilePreviewSourceText({
+ relativePath,
+ content,
+ truncated,
+ byteLength
+}: {
+ relativePath: string
+ content: string
+ truncated?: boolean
+ byteLength?: number
+}) {
+ const syntax = useMemo(
+ () => buildMobileFilePreviewSyntax(relativePath, content),
+ [content, relativePath]
+ )
+ return (
+
+ {truncated ? (
+
+ ) : null}
+
+
+
+
+ )
+}
+
+export function MobileFilePreviewTruncatedNote({ byteLength }: { byteLength: number }) {
+ return (
+
+ Preview truncated. File size: {formatPreviewByteLength(byteLength)}.
+
+ )
+}
diff --git a/mobile/src/files/mobile-file-preview-navigation.test.ts b/mobile/src/files/mobile-file-preview-navigation.test.ts
new file mode 100644
index 000000000..56d3a6247
--- /dev/null
+++ b/mobile/src/files/mobile-file-preview-navigation.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it, vi } from 'vitest'
+import {
+ canPreviewMobileFileRow,
+ navigateToMobileFilePreview
+} from './mobile-file-preview-navigation'
+
+describe('mobile-file-preview-navigation', () => {
+ it('navigates preview interactions to the encoded Expo target without files.open', () => {
+ const push = vi.fn()
+ const relativePath = 'assets/a #b?c%25 d\\logo.png'
+
+ navigateToMobileFilePreview(
+ { push },
+ {
+ hostId: 'host-1',
+ worktreeId: 'wt-1',
+ relativePath,
+ name: 'logo.png',
+ worktreeName: 'Orca'
+ }
+ )
+
+ expect(push).toHaveBeenCalledWith({
+ pathname: '/h/[hostId]/files/preview/[worktreeId]',
+ params: {
+ hostId: 'host-1',
+ worktreeId: 'wt-1',
+ relativePath,
+ name: 'logo.png',
+ worktreeName: 'Orca'
+ }
+ })
+ expect(push).toHaveBeenCalledTimes(1)
+ })
+
+ it('defers embedded close until after route push', () => {
+ const events: string[] = []
+ const scheduleClose = vi.fn((callback: () => void) => {
+ events.push('schedule')
+ callback()
+ })
+
+ navigateToMobileFilePreview(
+ {
+ push: () => events.push('push')
+ },
+ {
+ hostId: 'host-1',
+ worktreeId: 'wt-1',
+ relativePath: 'README.md'
+ },
+ {
+ embedded: true,
+ scheduleClose,
+ onRequestClose: () => events.push('close')
+ }
+ )
+
+ expect(events).toEqual(['push', 'schedule', 'close'])
+ expect(scheduleClose).toHaveBeenCalledWith(expect.any(Function), 0)
+ })
+
+ it('keeps non-image binary rows disabled while previewing text and raster images', () => {
+ expect(canPreviewMobileFileRow({ kind: 'text', relativePath: 'src/app.ts' })).toBe(true)
+ expect(canPreviewMobileFileRow({ kind: 'binary', relativePath: 'assets/logo.webp' })).toBe(true)
+ expect(canPreviewMobileFileRow({ kind: 'binary', relativePath: 'archive.zip' })).toBe(false)
+ })
+})
diff --git a/mobile/src/files/mobile-file-preview-navigation.ts b/mobile/src/files/mobile-file-preview-navigation.ts
new file mode 100644
index 000000000..e5024a4fb
--- /dev/null
+++ b/mobile/src/files/mobile-file-preview-navigation.ts
@@ -0,0 +1,37 @@
+import { classifyMobileArtifact } from '../session/mobile-artifact-kind'
+import {
+ createMobileFilePreviewHref,
+ type MobileFilePreviewHref,
+ type MobileFilePreviewRouteParams
+} from './mobile-file-preview-route'
+
+export type MobileFilePreviewRouter = {
+ push: (href: MobileFilePreviewHref) => void
+}
+
+type NavigateOptions = {
+ embedded?: boolean
+ onRequestClose?: () => void
+ scheduleClose?: (callback: () => void, delayMs: number) => unknown
+}
+
+export function navigateToMobileFilePreview(
+ router: MobileFilePreviewRouter,
+ params: MobileFilePreviewRouteParams,
+ options: NavigateOptions = {}
+): void {
+ router.push(createMobileFilePreviewHref(params))
+ if (options.embedded && options.onRequestClose) {
+ // Why: closing the dock immediately can unmount the subtree before Expo
+ // commits the route transition.
+ const scheduleClose = options.scheduleClose ?? setTimeout
+ scheduleClose(options.onRequestClose, 0)
+ }
+}
+
+export function canPreviewMobileFileRow(item: {
+ kind: 'text' | 'binary'
+ relativePath: string
+}): boolean {
+ return item.kind === 'text' || classifyMobileArtifact(item.relativePath) === 'image'
+}
diff --git a/mobile/src/files/mobile-file-preview-request.test.ts b/mobile/src/files/mobile-file-preview-request.test.ts
new file mode 100644
index 000000000..d26901113
--- /dev/null
+++ b/mobile/src/files/mobile-file-preview-request.test.ts
@@ -0,0 +1,133 @@
+import { describe, expect, it, vi } from 'vitest'
+import type { RpcFailure, RpcResponse, RpcSuccess } from '../transport/types'
+import {
+ createMobileFilePreviewRequest,
+ formatPreviewByteLength,
+ loadMobileFilePreview,
+ normalizeMobileFilePreviewResponse
+} from './mobile-file-preview-request'
+
+function ok(result: unknown): RpcSuccess {
+ return { id: '1', ok: true, result, _meta: { runtimeId: 'runtime-1' } }
+}
+
+function fail(message: string, code = 'error'): RpcFailure {
+ return { id: '1', ok: false, error: { code, message }, _meta: { runtimeId: 'runtime-1' } }
+}
+
+function clientWith(response: RpcResponse) {
+ return {
+ sendRequest: vi.fn(async () => response)
+ }
+}
+
+describe('mobile-file-preview-request', () => {
+ it('selects readPreview for raster images and read for text-like files', () => {
+ expect(createMobileFilePreviewRequest('wt-1', 'assets/logo.png')).toEqual({
+ method: 'files.readPreview',
+ params: { worktree: 'id:wt-1', relativePath: 'assets/logo.png' }
+ })
+ expect(createMobileFilePreviewRequest('wt-1', 'docs/readme.md')).toEqual({
+ method: 'files.read',
+ params: { worktree: 'id:wt-1', relativePath: 'docs/readme.md' }
+ })
+ expect(createMobileFilePreviewRequest('wt-1', 'public/index.html')).toEqual({
+ method: 'files.read',
+ params: { worktree: 'id:wt-1', relativePath: 'public/index.html' }
+ })
+ })
+
+ it('loads images through readPreview and never calls files.open', async () => {
+ const client = clientWith(
+ ok({ content: 'aW1hZ2U=', isBinary: true, isImage: true, mimeType: 'image/png' })
+ )
+
+ await expect(loadMobileFilePreview(client, 'wt-1', 'assets/logo.png')).resolves.toEqual({
+ status: 'ready',
+ kind: 'image',
+ dataUri: 'data:image/png;base64,aW1hZ2U='
+ })
+ expect(client.sendRequest).toHaveBeenCalledWith('files.readPreview', {
+ worktree: 'id:wt-1',
+ relativePath: 'assets/logo.png'
+ })
+ expect(client.sendRequest).not.toHaveBeenCalledWith('files.open', expect.anything())
+ })
+
+ it.each([
+ ['missing isBinary', { content: 'aW1hZ2U=', isImage: true, mimeType: 'image/png' }],
+ ['missing isImage', { content: 'aW1hZ2U=', isBinary: true, mimeType: 'image/png' }],
+ ['missing mimeType', { content: 'aW1hZ2U=', isBinary: true, isImage: true }],
+ ['empty content', { content: '', isBinary: true, isImage: true, mimeType: 'image/png' }]
+ ])('rejects invalid image preview results: %s', (_label, result) => {
+ expect(normalizeMobileFilePreviewResponse('assets/logo.png', ok(result))).toEqual({
+ status: 'error',
+ message: 'Binary preview unavailable',
+ reconnect: false
+ })
+ })
+
+ it('normalizes markdown, html, text, empty, and truncated reads', () => {
+ expect(
+ normalizeMobileFilePreviewResponse(
+ 'README.md',
+ ok({ content: '# Hi', truncated: false, byteLength: 4 })
+ )
+ ).toEqual({
+ status: 'ready',
+ kind: 'markdown',
+ content: '# Hi',
+ truncated: false,
+ byteLength: 4
+ })
+ expect(
+ normalizeMobileFilePreviewResponse(
+ 'index.html',
+ ok({ content: 'Hi
', truncated: false, byteLength: 11 })
+ )
+ ).toMatchObject({ status: 'ready', kind: 'html' })
+ expect(
+ normalizeMobileFilePreviewResponse(
+ 'src/app.ts',
+ ok({ content: 'const a = 1', truncated: true, byteLength: 700_000 })
+ )
+ ).toEqual({
+ status: 'ready',
+ kind: 'text',
+ content: 'const a = 1',
+ truncated: true,
+ byteLength: 700_000
+ })
+ expect(
+ normalizeMobileFilePreviewResponse(
+ 'empty.txt',
+ ok({ content: '', truncated: false, byteLength: 0 })
+ )
+ ).toEqual({ status: 'empty', kind: 'text' })
+ })
+
+ it.each([
+ ['binary_file', 'Binary preview unavailable', false],
+ ['file_too_large', 'File too large for mobile preview', false],
+ ['ENOENT: no such file or directory', 'File not found', false],
+ [
+ 'Remote connection dropped. Click Reconnect on the SSH target before retrying.',
+ 'Unable to reach the desktop filesystem',
+ true
+ ],
+ ['provider unavailable', 'Unable to reach the desktop filesystem', true],
+ ['permission denied', 'Unable to load preview', false]
+ ])('maps preview failure %s', (message, expected, reconnect) => {
+ expect(normalizeMobileFilePreviewResponse('src/app.ts', fail(message))).toEqual({
+ status: 'error',
+ message: expected,
+ reconnect
+ })
+ })
+
+ it('formats truncation byte counts for the UI note', () => {
+ expect(formatPreviewByteLength(512)).toBe('512 B')
+ expect(formatPreviewByteLength(4096)).toBe('4 KB')
+ expect(formatPreviewByteLength(1_572_864)).toBe('1.5 MB')
+ })
+})
diff --git a/mobile/src/files/mobile-file-preview-request.ts b/mobile/src/files/mobile-file-preview-request.ts
new file mode 100644
index 000000000..d7bdc4d3b
--- /dev/null
+++ b/mobile/src/files/mobile-file-preview-request.ts
@@ -0,0 +1,195 @@
+import { classifyMobileArtifact } from '../session/mobile-artifact-kind'
+import type { RpcFailure, RpcResponse, RpcSuccess } from '../transport/types'
+import type { RpcClient } from '../transport/rpc-client'
+import { isMarkdownPath } from './file-tree'
+
+export type MobileFilePreviewReadMethod = 'files.read' | 'files.readPreview'
+
+export type MobileFilePreviewRequest = {
+ method: MobileFilePreviewReadMethod
+ params: {
+ worktree: string
+ relativePath: string
+ }
+}
+
+export type MobileFilePreviewTextKind = 'html' | 'markdown' | 'text'
+
+export type MobileFilePreviewResult =
+ | {
+ status: 'loading'
+ message: string
+ }
+ | {
+ status: 'waiting'
+ message: string
+ reconnect: true
+ }
+ | {
+ status: 'ready'
+ kind: 'image'
+ dataUri: string
+ }
+ | {
+ status: 'ready'
+ kind: MobileFilePreviewTextKind
+ content: string
+ truncated: boolean
+ byteLength: number
+ }
+ | {
+ status: 'empty'
+ kind: MobileFilePreviewTextKind
+ }
+ | {
+ status: 'error'
+ message: string
+ reconnect: boolean
+ }
+
+type MobileFilePreviewClient = Pick
+
+export function createMobileFilePreviewRequest(
+ worktreeId: string,
+ relativePath: string
+): MobileFilePreviewRequest {
+ return {
+ method: classifyMobileArtifact(relativePath) === 'image' ? 'files.readPreview' : 'files.read',
+ params: {
+ worktree: `id:${worktreeId}`,
+ relativePath
+ }
+ }
+}
+
+export async function loadMobileFilePreview(
+ client: MobileFilePreviewClient,
+ worktreeId: string,
+ relativePath: string
+): Promise {
+ const request = createMobileFilePreviewRequest(worktreeId, relativePath)
+ const response = await client.sendRequest(request.method, request.params)
+ return normalizeMobileFilePreviewResponse(relativePath, response)
+}
+
+export function normalizeMobileFilePreviewResponse(
+ relativePath: string,
+ response: RpcResponse
+): MobileFilePreviewResult {
+ if (!response.ok) {
+ return previewError(
+ (response as RpcFailure).error.message || (response as RpcFailure).error.code
+ )
+ }
+
+ const result = (response as RpcSuccess).result
+ if (classifyMobileArtifact(relativePath) === 'image') {
+ return normalizeImagePreviewResult(result)
+ }
+ return normalizeTextPreviewResult(relativePath, result)
+}
+
+export function previewError(message: string): MobileFilePreviewResult {
+ const normalized = message.toLowerCase()
+ if (normalized === 'binary_file' || normalized.includes('binary_file')) {
+ return { status: 'error', message: 'Binary preview unavailable', reconnect: false }
+ }
+ if (normalized === 'file_too_large' || normalized.includes('file_too_large')) {
+ return { status: 'error', message: 'File too large for mobile preview', reconnect: false }
+ }
+ if (
+ normalized.includes('remote connection dropped') ||
+ normalized.includes('provider unavailable') ||
+ normalized.includes('disconnected')
+ ) {
+ return { status: 'error', message: 'Unable to reach the desktop filesystem', reconnect: true }
+ }
+ if (
+ normalized.includes('enoent') ||
+ normalized.includes('no such file') ||
+ normalized.includes('not found') ||
+ normalized.includes('does not exist')
+ ) {
+ return { status: 'error', message: 'File not found', reconnect: false }
+ }
+ return { status: 'error', message: 'Unable to load preview', reconnect: false }
+}
+
+export function formatPreviewByteLength(byteLength: number): string {
+ if (!Number.isFinite(byteLength) || byteLength < 0) {
+ return 'unknown size'
+ }
+ if (byteLength < 1024) {
+ return `${byteLength} B`
+ }
+ if (byteLength < 1024 * 1024) {
+ return `${Math.round(byteLength / 1024)} KB`
+ }
+ return `${(byteLength / (1024 * 1024)).toFixed(1)} MB`
+}
+
+function normalizeImagePreviewResult(result: unknown): MobileFilePreviewResult {
+ if (!result || typeof result !== 'object') {
+ return previewError('binary_file')
+ }
+ const preview = result as {
+ content?: unknown
+ isBinary?: unknown
+ isImage?: unknown
+ mimeType?: unknown
+ }
+ if (
+ preview.isBinary !== true ||
+ preview.isImage !== true ||
+ typeof preview.mimeType !== 'string' ||
+ preview.mimeType.length === 0 ||
+ typeof preview.content !== 'string' ||
+ preview.content.length === 0
+ ) {
+ return previewError('binary_file')
+ }
+ return {
+ status: 'ready',
+ kind: 'image',
+ dataUri: `data:${preview.mimeType};base64,${preview.content}`
+ }
+}
+
+function normalizeTextPreviewResult(
+ relativePath: string,
+ result: unknown
+): MobileFilePreviewResult {
+ if (!result || typeof result !== 'object') {
+ return previewError('Unable to load preview')
+ }
+ const preview = result as {
+ content?: unknown
+ truncated?: unknown
+ byteLength?: unknown
+ isBinary?: unknown
+ }
+ if (preview.isBinary === true) {
+ return previewError('binary_file')
+ }
+ if (typeof preview.content !== 'string') {
+ return previewError('Unable to load preview')
+ }
+ const kind = textKindForPreviewPath(relativePath)
+ if (preview.content.length === 0) {
+ return { status: 'empty', kind }
+ }
+ return {
+ status: 'ready',
+ kind,
+ content: preview.content,
+ truncated: preview.truncated === true,
+ byteLength: typeof preview.byteLength === 'number' ? preview.byteLength : preview.content.length
+ }
+}
+
+function textKindForPreviewPath(relativePath: string): MobileFilePreviewTextKind {
+ if (classifyMobileArtifact(relativePath) === 'html') {
+ return 'html'
+ }
+ return isMarkdownPath(relativePath) ? 'markdown' : 'text'
+}
diff --git a/mobile/src/files/mobile-file-preview-route.test.ts b/mobile/src/files/mobile-file-preview-route.test.ts
new file mode 100644
index 000000000..b4cab9418
--- /dev/null
+++ b/mobile/src/files/mobile-file-preview-route.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from 'vitest'
+import {
+ createMobileFilePreviewHref,
+ displayNameFromPreviewPath,
+ normalizeMobileFilePreviewRouteParams
+} from './mobile-file-preview-route'
+
+describe('mobile-file-preview-route', () => {
+ it('normalizes valid route params without changing encoded-sensitive path characters', () => {
+ const relativePath = 'docs/a #b?c%25 d\\note.md'
+ const route = normalizeMobileFilePreviewRouteParams({
+ hostId: 'host-1',
+ worktreeId: 'wt-1',
+ relativePath,
+ name: 'note.md',
+ worktreeName: 'Orca'
+ })
+
+ expect(route).toEqual({
+ ok: true,
+ params: {
+ hostId: 'host-1',
+ worktreeId: 'wt-1',
+ relativePath,
+ name: 'note.md',
+ worktreeName: 'Orca'
+ }
+ })
+ })
+
+ it('rejects missing, empty, or array-valued required params', () => {
+ expect(normalizeMobileFilePreviewRouteParams({ hostId: 'h', worktreeId: 'w' })).toEqual({
+ ok: false,
+ message: 'Unable to load preview'
+ })
+ expect(
+ normalizeMobileFilePreviewRouteParams({
+ hostId: 'h',
+ worktreeId: 'w',
+ relativePath: ''
+ })
+ ).toEqual({ ok: false, message: 'Unable to load preview' })
+ expect(
+ normalizeMobileFilePreviewRouteParams({
+ hostId: 'h',
+ worktreeId: 'w',
+ relativePath: ['a.ts', 'b.ts']
+ })
+ ).toEqual({ ok: false, message: 'Unable to load preview' })
+ })
+
+ it('builds the Expo href object so Expo owns URL encoding', () => {
+ const relativePath = 'src/#hash ?query%20\\file.ts'
+
+ expect(
+ createMobileFilePreviewHref({
+ hostId: 'host-1',
+ worktreeId: 'wt-1',
+ relativePath,
+ name: 'file.ts'
+ })
+ ).toEqual({
+ pathname: '/h/[hostId]/files/preview/[worktreeId]',
+ params: {
+ hostId: 'host-1',
+ worktreeId: 'wt-1',
+ relativePath,
+ name: 'file.ts'
+ }
+ })
+ })
+
+ it('derives display names from slash or backslash paths only for display', () => {
+ expect(displayNameFromPreviewPath('src/app.ts')).toBe('app.ts')
+ expect(displayNameFromPreviewPath('src\\app.ts')).toBe('app.ts')
+ })
+})
diff --git a/mobile/src/files/mobile-file-preview-route.ts b/mobile/src/files/mobile-file-preview-route.ts
new file mode 100644
index 000000000..b758c1214
--- /dev/null
+++ b/mobile/src/files/mobile-file-preview-route.ts
@@ -0,0 +1,68 @@
+export type MobileFilePreviewParamValue = string | string[] | undefined
+
+export type MobileFilePreviewRouteParams = {
+ hostId: string
+ worktreeId: string
+ relativePath: string
+ name?: string
+ worktreeName?: string
+}
+
+export type MobileFilePreviewRouteState =
+ | { ok: true; params: MobileFilePreviewRouteParams }
+ | { ok: false; message: string }
+
+export type MobileFilePreviewHref = {
+ pathname: '/h/[hostId]/files/preview/[worktreeId]'
+ params: MobileFilePreviewRouteParams
+}
+
+type RawPreviewRouteParams = {
+ hostId?: MobileFilePreviewParamValue
+ worktreeId?: MobileFilePreviewParamValue
+ relativePath?: MobileFilePreviewParamValue
+ name?: MobileFilePreviewParamValue
+ worktreeName?: MobileFilePreviewParamValue
+}
+
+function singleParam(value: MobileFilePreviewParamValue): string | null {
+ return typeof value === 'string' ? value : null
+}
+
+function optionalSingleParam(value: MobileFilePreviewParamValue): string | undefined {
+ return typeof value === 'string' && value.length > 0 ? value : undefined
+}
+
+export function normalizeMobileFilePreviewRouteParams(
+ params: RawPreviewRouteParams
+): MobileFilePreviewRouteState {
+ const hostId = singleParam(params.hostId)
+ const worktreeId = singleParam(params.worktreeId)
+ const relativePath = singleParam(params.relativePath)
+ if (!hostId || !worktreeId || !relativePath) {
+ return { ok: false, message: 'Unable to load preview' }
+ }
+ return {
+ ok: true,
+ params: {
+ hostId,
+ worktreeId,
+ relativePath,
+ name: optionalSingleParam(params.name),
+ worktreeName: optionalSingleParam(params.worktreeName)
+ }
+ }
+}
+
+export function createMobileFilePreviewHref(
+ params: MobileFilePreviewRouteParams
+): MobileFilePreviewHref {
+ return {
+ pathname: '/h/[hostId]/files/preview/[worktreeId]',
+ params
+ }
+}
+
+export function displayNameFromPreviewPath(relativePath: string): string {
+ return relativePath.split(/[\\/]/).filter(Boolean).at(-1) ?? relativePath
+}
diff --git a/mobile/src/files/mobile-file-preview-styles.ts b/mobile/src/files/mobile-file-preview-styles.ts
new file mode 100644
index 000000000..0e7c2c5db
--- /dev/null
+++ b/mobile/src/files/mobile-file-preview-styles.ts
@@ -0,0 +1,140 @@
+import { StyleSheet } from 'react-native'
+import { colors, radii, spacing, typography } from '../theme/mobile-theme'
+
+export const filePreviewStyles = StyleSheet.create({
+ container: {
+ flex: 1,
+ backgroundColor: colors.bgBase
+ },
+ header: {
+ backgroundColor: colors.bgPanel,
+ borderBottomWidth: StyleSheet.hairlineWidth,
+ borderBottomColor: colors.borderSubtle
+ },
+ topBar: {
+ minHeight: 58,
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: spacing.md,
+ paddingHorizontal: spacing.md
+ },
+ backButton: {
+ width: 36,
+ height: 36,
+ alignItems: 'center',
+ justifyContent: 'center',
+ borderRadius: radii.button
+ },
+ backButtonPressed: {
+ backgroundColor: colors.bgRaised
+ },
+ titleBlock: {
+ flex: 1,
+ minWidth: 0
+ },
+ title: {
+ color: colors.textPrimary,
+ fontSize: typography.titleSize,
+ fontWeight: '600'
+ },
+ meta: {
+ marginTop: 2,
+ color: colors.textSecondary,
+ fontSize: typography.metaSize
+ },
+ state: {
+ flex: 1,
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: spacing.md,
+ padding: spacing.xl
+ },
+ stateText: {
+ color: colors.textSecondary,
+ fontSize: typography.bodySize,
+ textAlign: 'center'
+ },
+ errorText: {
+ color: colors.statusRed,
+ fontSize: typography.bodySize,
+ textAlign: 'center'
+ },
+ retryButton: {
+ minHeight: 36,
+ alignItems: 'center',
+ justifyContent: 'center',
+ borderRadius: radii.button,
+ borderWidth: StyleSheet.hairlineWidth,
+ borderColor: colors.borderSubtle,
+ paddingHorizontal: spacing.lg
+ },
+ retryText: {
+ color: colors.textPrimary,
+ fontSize: typography.bodySize,
+ fontWeight: '600'
+ },
+ scroll: {
+ flex: 1,
+ backgroundColor: colors.editorSurface
+ },
+ textContent: {
+ padding: spacing.md,
+ paddingBottom: spacing.xl
+ },
+ textPreview: {
+ color: colors.textPrimary,
+ fontFamily: typography.monoFamily,
+ fontSize: 13,
+ lineHeight: 19
+ },
+ markdownContent: {
+ padding: spacing.md,
+ paddingBottom: spacing.xl
+ },
+ modeContainer: {
+ flex: 1,
+ backgroundColor: colors.editorSurface
+ },
+ modeToolbar: {
+ flexDirection: 'row',
+ alignSelf: 'flex-start',
+ marginHorizontal: spacing.md,
+ marginVertical: spacing.sm,
+ padding: 1,
+ borderWidth: StyleSheet.hairlineWidth,
+ borderColor: colors.borderSubtle,
+ borderRadius: radii.button,
+ backgroundColor: colors.bgPanel
+ },
+ modeToggle: {
+ width: 34,
+ height: 28,
+ alignItems: 'center',
+ justifyContent: 'center',
+ borderRadius: radii.row,
+ backgroundColor: 'transparent',
+ opacity: 0.72
+ },
+ modeToggleActive: {
+ backgroundColor: colors.bgRaised,
+ opacity: 1
+ },
+ truncatedNote: {
+ marginBottom: spacing.md,
+ color: colors.textSecondary,
+ fontSize: typography.metaSize
+ },
+ imageContainer: {
+ flex: 1,
+ backgroundColor: colors.editorSurface
+ },
+ imageScrollContent: {
+ flexGrow: 1,
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: spacing.md
+ },
+ image: {
+ backgroundColor: colors.editorSurface
+ }
+})
diff --git a/mobile/src/files/mobile-file-preview-syntax.test.ts b/mobile/src/files/mobile-file-preview-syntax.test.ts
new file mode 100644
index 000000000..a4f0a598c
--- /dev/null
+++ b/mobile/src/files/mobile-file-preview-syntax.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest'
+import { buildMobileFilePreviewSyntax } from './mobile-file-preview-syntax'
+
+describe('mobile-file-preview-syntax', () => {
+ it('returns syntax segments for supported source paths', () => {
+ const syntax = buildMobileFilePreviewSyntax('src/app.ts', 'const answer = 42')
+
+ expect(syntax.language).toBe('typescript')
+ expect(syntax.segments.map((segment) => segment.text).join('')).toBe('const answer = 42')
+ })
+
+ it('falls back to a plain segment when highlighting is unavailable', () => {
+ expect(buildMobileFilePreviewSyntax('README.unknown', 'plain text')).toEqual({
+ language: 'plaintext',
+ segments: [{ kind: 'plain', text: 'plain text' }]
+ })
+ })
+})
diff --git a/mobile/src/files/mobile-file-preview-syntax.ts b/mobile/src/files/mobile-file-preview-syntax.ts
new file mode 100644
index 000000000..5288ef807
--- /dev/null
+++ b/mobile/src/files/mobile-file-preview-syntax.ts
@@ -0,0 +1,30 @@
+import {
+ highlightMobileCode,
+ resolveMobileSyntaxLanguage,
+ type MobileSyntaxSegment
+} from '../session/mobile-file-syntax'
+
+export type MobileFilePreviewSyntax = {
+ language: string
+ segments: MobileSyntaxSegment[]
+}
+
+export function buildMobileFilePreviewSyntax(
+ relativePath: string,
+ content: string
+): MobileFilePreviewSyntax {
+ try {
+ const language = resolveMobileSyntaxLanguage(relativePath)
+ const result = highlightMobileCode(content, language)
+ return {
+ language,
+ segments: result.segments.length > 0 ? result.segments : plainSegments(content)
+ }
+ } catch {
+ return { language: 'plaintext', segments: plainSegments(content) }
+ }
+}
+
+function plainSegments(content: string): MobileSyntaxSegment[] {
+ return [{ kind: 'plain', text: content }]
+}