Fix mobile file previews (#6315)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Brennan Benson
2026-06-26 12:10:58 -07:00
committed by GitHub
co-authored by Orca
parent af52e418ea
commit 55c0c74951
20 changed files with 1375 additions and 63 deletions
@@ -0,0 +1,14 @@
import { useLocalSearchParams } from 'expo-router'
import { MobileFilePreviewScreen } from '../../../../../src/files/MobileFilePreviewScreen'
import { normalizeMobileFilePreviewRouteParams } from '../../../../../src/files/mobile-file-preview-route'
export default function MobileFilePreviewRoute() {
const params = useLocalSearchParams<{
hostId?: string | string[]
worktreeId?: string | string[]
relativePath?: string | string[]
name?: string | string[]
worktreeName?: string | string[]
}>()
return <MobileFilePreviewScreen route={normalizeMobileFilePreviewRouteParams(params)} />
}
@@ -0,0 +1,82 @@
import type { RpcRequest, RpcResponse } from './mock-server-rpc-handlers'
type Respond = (response: RpcResponse) => void
type Success = (id: string, result: unknown, streaming?: boolean) => RpcResponse
type ErrorResponse = (id: string, code: string, message: string) => RpcResponse
const MOCK_IMAGE_PNG_BASE64 =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/l8sm7wAAAABJRU5ErkJggg=='
const MOCK_FILE_CONTENT: Record<string, string> = {
'README.md': '# Mobile preview\n\nThis markdown file is served by the mock desktop.',
'src/app.ts': "export const mobilePreview = 'ready'\n",
'public/index.html': '<main><h1>Mobile preview</h1><p>HTML preview is ready.</p></main>'
}
const MOCK_FILE_LIST = [
{ relativePath: 'README.md', basename: 'README.md', kind: 'text' },
{ relativePath: 'src/app.ts', basename: 'app.ts', kind: 'text' },
{ relativePath: 'public/index.html', basename: 'index.html', kind: 'text' },
{ relativePath: 'assets/logo.png', basename: 'logo.png', kind: 'binary' },
{ relativePath: 'dist/archive.zip', basename: 'archive.zip', kind: 'binary' }
]
export function handleMockFilePreviewRequest(
request: RpcRequest,
respond: Respond,
success: Success,
error: ErrorResponse
): boolean {
switch (request.method) {
case 'files.list':
respond(
success(request.id, {
worktree: request.params?.worktree ?? 'id:mock',
rootPath: '/tmp/orca-mobile-repro/orca',
files: MOCK_FILE_LIST,
totalCount: MOCK_FILE_LIST.length,
truncated: false
})
)
return true
case 'files.read': {
const relativePath = String(request.params?.relativePath ?? '')
const content = MOCK_FILE_CONTENT[relativePath]
if (content == null) {
respond(error(request.id, 'not_found', 'File not found'))
return true
}
respond(
success(request.id, {
worktree: request.params?.worktree ?? 'id:mock',
relativePath,
content,
truncated: false,
byteLength: Buffer.byteLength(content, 'utf8')
})
)
return true
}
case 'files.readPreview': {
const relativePath = String(request.params?.relativePath ?? '')
if (relativePath !== 'assets/logo.png') {
respond(error(request.id, 'binary_file', 'binary_file'))
return true
}
respond(
success(request.id, {
content: MOCK_IMAGE_PNG_BASE64,
isBinary: true,
isImage: true,
mimeType: 'image/png'
})
)
return true
}
default:
return false
}
}
+5 -22
View File
@@ -3,7 +3,9 @@ import {
DESKTOP_PROTOCOL_VERSION,
MIN_COMPATIBLE_MOBILE_VERSION
} from '../../src/shared/protocol-version'
import { handleMockFilePreviewRequest } from './mock-server-file-preview-data'
import { handleMockGitRequest } from './mock-server-git-state'
import { FAKE_SCROLLBACK, STREAMING_CHUNKS } from './mock-server-terminal-fixtures'
import { createMockRepos, createMockWorktrees, readScenarioNumber } from './mobile-lag-scenario'
const MOCK_REPO_COUNT = readScenarioNumber('MOCK_REPO_COUNT', 2)
@@ -30,28 +32,6 @@ const FAKE_TERMINALS = [
}
]
const FAKE_SCROLLBACK = [
'$ claude "refactor the auth module to use JWT tokens"',
'',
'⏳ Working on it...',
'',
"I'll refactor the auth module. Here's my plan:",
'1. Replace session-based auth with JWT',
'2. Add token refresh endpoint',
'3. Update middleware',
'',
'Let me start by reading the current auth module...',
''
].join('\n')
const STREAMING_CHUNKS = [
'Reading src/auth/middleware.ts...\n',
'Reading src/auth/session.ts...\n',
'\nI see the current implementation uses express-session.\n',
"I'll replace it with jsonwebtoken.\n",
'\nUpdating src/auth/middleware.ts...\n'
]
export type RpcRequest = {
id: string
method: string
@@ -120,6 +100,9 @@ export function handleRequest(
if (handleMockGitRequest(request, respond, success)) {
return
}
if (handleMockFilePreviewRequest(request, respond, success, error)) {
return
}
switch (request.method) {
case 'status.get':
@@ -0,0 +1,21 @@
export const FAKE_SCROLLBACK = [
'$ claude "refactor the auth module to use JWT tokens"',
'',
'⏳ Working on it...',
'',
"I'll refactor the auth module. Here's my plan:",
'1. Replace session-based auth with JWT',
'2. Add token refresh endpoint',
'3. Update middleware',
'',
'Let me start by reading the current auth module...',
''
].join('\n')
export const STREAMING_CHUNKS = [
'Reading src/auth/middleware.ts...\n',
'Reading src/auth/session.ts...\n',
'\nI see the current implementation uses express-session.\n',
"I'll replace it with jsonwebtoken.\n",
'\nUpdating src/auth/middleware.ts...\n'
]
@@ -1,4 +1,5 @@
import { describe, expect, it } from 'vitest'
import { normalizeMobileMarkdownPreviewHtml } from './mobile-markdown-preview-html'
import { parseMobileMarkdown } from './mobile-markdown-parser'
describe('parseMobileMarkdown', () => {
@@ -21,4 +22,31 @@ describe('parseMobileMarkdown', () => {
}
])
})
it('normalizes common README HTML into readable Markdown preview text', () => {
const normalized = normalizeMobileMarkdownPreviewHtml(`
<h1 align="center">
<a href="https://onOrca.dev"><img src="resources/build/icon.png" alt="Orca" width="64" /></a>
Orca
</h1>
<p align="center">
<a href="https://github.com/stablyai/orca/stargazers"><img src="https://badgen.net/github/stars/stablyai/orca" alt="GitHub stars" /></a>
<strong>The AI Orchestrator</strong><br/>
Run Codex side-by-side.
</p>
`)
expect(normalized).toContain('# [Orca](https://onOrca.dev)')
expect(normalized).toContain('[GitHub stars](https://github.com/stablyai/orca/stargazers)')
expect(normalized).toContain('**The AI Orchestrator**')
expect(normalized).not.toContain('<h1')
expect(normalized).not.toContain('<img')
})
it('preserves documented HTML entities while normalizing preview HTML', () => {
expect(
normalizeMobileMarkdownPreviewHtml('<p>Use <code>&amp;lt;button&amp;gt;</code></p>')
).toBe('Use `&lt;button&gt;`')
})
})
+3 -1
View File
@@ -1,6 +1,7 @@
import { Fragment, memo, useMemo, type ReactNode } from 'react'
import { Linking, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native'
import { colors, radii, spacing, typography } from '../theme/mobile-theme'
import { normalizeMobileMarkdownPreviewHtml } from './mobile-markdown-preview-html'
import { parseMobileMarkdown } from './mobile-markdown-parser'
type Props = {
@@ -87,7 +88,8 @@ function renderInline(text: string): ReactNode[] {
function MobileMarkdownInner({ content, fallback = '' }: Props) {
const text = content?.trim() ?? ''
const blocks = useMemo(() => parseMobileMarkdown(text), [text])
const previewText = useMemo(() => normalizeMobileMarkdownPreviewHtml(text), [text])
const blocks = useMemo(() => parseMobileMarkdown(previewText), [previewText])
if (!text) {
return fallback ? <Text style={styles.paragraph}>{fallback}</Text> : null
}
@@ -0,0 +1,98 @@
// Why: README HTML snippets can document escaped entities; repeated cleanup
// passes must not turn `&amp;lt;` into a real tag and strip it.
const escapedHtmlEntityTokens = [
{ pattern: /&amp;nbsp;/gi, token: '\uE000ORCA_MD_ENTITY_NBSP\uE000', value: '&nbsp;' },
{ pattern: /&amp;lt;/gi, token: '\uE000ORCA_MD_ENTITY_LT\uE000', value: '&lt;' },
{ pattern: /&amp;gt;/gi, token: '\uE000ORCA_MD_ENTITY_GT\uE000', value: '&gt;' },
{ pattern: /&amp;quot;/gi, token: '\uE000ORCA_MD_ENTITY_QUOT\uE000', value: '&quot;' },
{ pattern: /&amp;#39;/gi, token: '\uE000ORCA_MD_ENTITY_APOS\uE000', value: '&#39;' }
] as const
function protectEscapedHtmlEntities(value: string): string {
return escapedHtmlEntityTokens.reduce(
(next, entity) => next.replace(entity.pattern, entity.token),
value
)
}
function restoreEscapedHtmlEntities(value: string): string {
return escapedHtmlEntityTokens.reduce(
(next, entity) => next.replaceAll(entity.token, entity.value),
value
)
}
function decodeHtmlEntities(value: string, preserveEscapedEntities = false): string {
const next = preserveEscapedEntities ? protectEscapedHtmlEntities(value) : value
return next
.replace(/&nbsp;/gi, ' ')
.replace(/&lt;/gi, '<')
.replace(/&gt;/gi, '>')
.replace(/&quot;/gi, '"')
.replace(/&#39;/gi, "'")
.replace(/&amp;/gi, '&')
}
function stripTags(value: string): string {
return decodeHtmlEntities(value.replace(/<[^>]+>/g, ''), true)
.replace(/[ \t]+\n/g, '\n')
.replace(/\n{3,}/g, '\n\n')
.trim()
}
function attrValue(tag: string, name: string): string {
const pattern = new RegExp(`${name}\\s*=\\s*("[^"]*"|'[^']*'|[^\\s>]+)`, 'i')
const match = tag.match(pattern)
const raw = match?.[1] ?? ''
return decodeHtmlEntities(raw.replace(/^["']|["']$/g, ''))
}
function normalizeInlineHtml(value: string): string {
return value
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<img\b[^>]*>/gi, (tag) => attrValue(tag, 'alt') || 'image')
.replace(
/<a\b[^>]*href\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)[^>]*>([\s\S]*?)<\/a>/gi,
(tag, _href, label) => {
const href = attrValue(tag, 'href')
const text = stripTags(label)
return href && text ? `[${text}](${href})` : text
}
)
.replace(/<(strong|b)\b[^>]*>([\s\S]*?)<\/\1>/gi, (_tag, _name, inner) => {
const text = stripTags(inner)
return text ? `**${text}**` : ''
})
.replace(/<(em|i)\b[^>]*>([\s\S]*?)<\/\1>/gi, (_tag, _name, inner) => {
const text = stripTags(inner)
return text ? `*${text}*` : ''
})
.replace(/<(code|kbd)\b[^>]*>([\s\S]*?)<\/\1>/gi, (_tag, _name, inner) => {
const text = stripTags(inner)
return text ? `\`${text}\`` : ''
})
}
export function normalizeMobileMarkdownPreviewHtml(content: string): string {
let next = content.replace(/\r\n?/g, '\n')
// Why: repository Markdown often uses small HTML islands for centered README
// headers and badges. Preview mode should read like Markdown, while Source
// mode remains the exact file bytes.
next = next.replace(/<h([1-6])\b[^>]*>([\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(/<p\b[^>]*>([\s\S]*?)<\/p>/gi, (_tag, inner) => {
const text = stripTags(normalizeInlineHtml(inner))
return text ? `\n${text}\n` : '\n'
})
next = next.replace(/<sub\b[^>]*>([\s\S]*?)<\/sub>/gi, (_tag, inner) =>
stripTags(normalizeInlineHtml(inner))
)
next = normalizeInlineHtml(next)
next = stripTags(next)
return restoreEscapedHtmlEntities(next)
}
+28 -40
View File
@@ -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<Set<string>>(() => new Set())
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [openingPath, setOpeningPath] = useState<string | null>(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<TreeNode> = ({ 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 (
<Pressable
@@ -144,12 +135,12 @@ export function MobileFileExplorerPanel(props: {
pressed && !disabled && styles.rowPressed,
disabled && styles.rowDisabled
]}
disabled={disabled || openingPath !== null}
disabled={disabled}
onPress={() => {
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: {
</Text>
{disabled ? <Text style={styles.rowMeta}>Unavailable on mobile</Text> : null}
</View>
{openingPath === item.relativePath ? (
<ActivityIndicator size="small" color={colors.textSecondary} />
) : null}
</Pressable>
)
}
@@ -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 (
<View style={styles.modeContainer}>
<View style={styles.modeToolbar}>
<Pressable
style={[styles.modeToggle, sourceSelected && styles.modeToggleActive]}
onPress={() => setMode('source')}
accessibilityRole="button"
accessibilityState={{ selected: sourceSelected }}
accessibilityLabel="View Markdown source"
>
<Code
size={15}
color={sourceSelected ? colors.textPrimary : colors.textSecondary}
strokeWidth={2.2}
/>
</Pressable>
<Pressable
style={[styles.modeToggle, previewSelected && styles.modeToggleActive]}
onPress={() => setMode('preview')}
accessibilityRole="button"
accessibilityState={{ selected: previewSelected }}
accessibilityLabel="View rendered Markdown preview"
>
<Pencil
size={15}
color={previewSelected ? colors.textPrimary : colors.textSecondary}
strokeWidth={2.2}
/>
</Pressable>
</View>
{mode === 'preview' ? (
<ScrollView style={styles.scroll} contentContainerStyle={styles.markdownContent}>
{truncated ? <MobileFilePreviewTruncatedNote byteLength={byteLength} /> : null}
<MobileMarkdown content={content} />
</ScrollView>
) : (
<MobileFilePreviewSourceText
relativePath={relativePath}
content={content}
truncated={truncated}
byteLength={byteLength}
/>
)}
</View>
)
}
@@ -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<MobileFilePreviewResult>(() =>
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 (
<View style={styles.container}>
<SafeAreaView style={styles.header} edges={['top']}>
<View style={styles.topBar}>
<Pressable
style={({ pressed }) => [styles.backButton, pressed && styles.backButtonPressed]}
onPress={() => router.back()}
hitSlop={8}
accessibilityLabel="Back to files"
>
<ChevronLeft size={22} color={colors.textSecondary} strokeWidth={2.2} />
</Pressable>
<View style={styles.titleBlock}>
<Text style={styles.title} numberOfLines={1}>
{title || 'Preview'}
</Text>
<Text style={styles.meta} numberOfLines={1}>
{meta}
</Text>
</View>
</View>
</SafeAreaView>
{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
})}
</View>
)
}
function renderPreviewBody(
preview: MobileFilePreviewResult,
options: {
relativePath: string
title: string
imageWidth: number
imageHeight: number
onImageError: () => void
onRetry: () => void
}
) {
if (preview.status === 'loading') {
return (
<View style={styles.state}>
<ActivityIndicator size="small" color={colors.textSecondary} />
<Text style={styles.stateText}>{preview.message}</Text>
</View>
)
}
if (preview.status === 'error' || preview.status === 'waiting') {
return (
<View style={styles.state}>
<Text style={styles.errorText}>{preview.message}</Text>
<Pressable style={styles.retryButton} onPress={options.onRetry}>
<Text style={styles.retryText}>Retry</Text>
</Pressable>
</View>
)
}
if (preview.status === 'empty') {
return (
<View style={styles.state}>
<Text style={styles.stateText}>Empty file</Text>
</View>
)
}
if (preview.kind === 'image') {
return (
<View style={styles.imageContainer}>
<ScrollView
style={styles.scroll}
contentContainerStyle={styles.imageScrollContent}
maximumZoomScale={4}
minimumZoomScale={1}
centerContent
>
<Image
source={{ uri: preview.dataUri }}
style={[styles.image, { width: options.imageWidth, height: options.imageHeight }]}
resizeMode="contain"
onError={options.onImageError}
accessibilityLabel={`${options.title} image`}
/>
</ScrollView>
</View>
)
}
if (preview.kind === 'markdown') {
return (
<MobileFileMarkdownPreview
relativePath={options.relativePath}
content={preview.content}
truncated={preview.truncated}
byteLength={preview.byteLength}
/>
)
}
if (preview.kind === 'html') {
return (
<MobileFilePreviewSourceText
relativePath={options.relativePath}
content={preview.content}
truncated={preview.truncated}
byteLength={preview.byteLength}
/>
)
}
return (
<MobileFilePreviewSourceText
relativePath={options.relativePath}
content={preview.content}
truncated={preview.truncated}
byteLength={preview.byteLength}
/>
)
}
@@ -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 (
<ScrollView style={styles.scroll} contentContainerStyle={styles.textContent}>
{truncated ? (
<MobileFilePreviewTruncatedNote byteLength={byteLength ?? content.length} />
) : null}
<Text selectable style={styles.textPreview} accessibilityLabel="File preview">
<MobileSyntaxSegments segments={syntax.segments} />
</Text>
</ScrollView>
)
}
export function MobileFilePreviewTruncatedNote({ byteLength }: { byteLength: number }) {
return (
<Text style={styles.truncatedNote}>
Preview truncated. File size: {formatPreviewByteLength(byteLength)}.
</Text>
)
}
@@ -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)
})
})
@@ -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'
}
@@ -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: '<h1>Hi</h1>', 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')
})
})
@@ -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<RpcClient, 'sendRequest'>
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<MobileFilePreviewResult> {
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'
}
@@ -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')
})
})
@@ -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
}
@@ -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
}
})
@@ -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' }]
})
})
})
@@ -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 }]
}