import { useEffect, useRef, useState } from 'react' import { ActivityIndicator, Alert, FlatList, Image, NativeModules, Pressable, ScrollView, StyleSheet, Text, ToastAndroid, View } from 'react-native' import * as FileSystem from 'expo-file-system/legacy' import { File as LocalFile, FileMode, Paths } from 'expo-file-system' import { randomUUID } from 'expo-crypto' import { ChevronLeft, Download, File, Folder, RefreshCw } from 'lucide-react-native' import { requireSessionTools } from '../state/store' import type { WorkspaceDirectory, WorkspaceText } from '../services/session-tools' import { classifyWorkspaceFile, loadWorkspaceDownload, loadWorkspacePreview, MAX_DOWNLOAD_BYTES, PREVIEW_CHUNK_BYTES } from '../services/workspace-file-preview' import { strings as t } from '../locales/i18n' import { BlurHeaderFrame, Button, IconButton, TopBar } from '../ui/components' import { useTheme } from '../ui/theme-context' import { MarkdownLinkProvider, NativeMarkdown } from '../ui/markdown' import { spacing, type } from '../ui/theme' import { sessionToolsError } from './session-tools-error' import { PdfPreview } from './pdf-preview' const downloads = NativeModules.DshRemoteDownloads as { supported: boolean prepare(source: string, name: string): Promise finish(uri: string, publish: boolean): Promise } | undefined export function WorkspaceFilesPanel({ sessionId, initialFile, onClose }: { sessionId: string; initialFile?: string; onClose: () => void }) { const { colors } = useTheme() const [path, setPath] = useState('') const [file, setFile] = useState(initialFile) const [offset, setOffset] = useState(1) const [listing, setListing] = useState() const [page, setPage] = useState() const [binary, setBinary] = useState>>() const [loading, setLoading] = useState(true) const [error, setError] = useState() const [revision, setRevision] = useState(0) const [fileBytes, setFileBytes] = useState() const tooLargeToSave = fileBytes !== undefined && fileBytes > MAX_DOWNLOAD_BYTES const [downloading, setDownloading] = useState(false) const downloadController = useRef(undefined) useEffect(() => { setDownloading(false) return () => { downloadController.current?.abort(); downloadController.current = undefined } }, [sessionId, file]) const download = async () => { if (file === undefined || tooLargeToSave || downloadController.current) return const controller = new AbortController() downloadController.current = controller setDownloading(true) let uri: string | undefined let temporary: LocalFile | undefined try { const directory = downloads?.supported ? undefined : await FileSystem.StorageAccessFramework.requestDirectoryPermissionsAsync() if (controller.signal.aborted || (directory !== undefined && !directory.granted)) return temporary = new LocalFile(Paths.cache, `workspace-download-${randomUUID()}`) temporary.create() const handle = temporary.open() try { await loadWorkspaceDownload(requireSessionTools(sessionId), sessionId, file, bytes => handle.writeBytes(bytes), controller.signal) } finally { handle.close() } if (controller.signal.aborted) return const name = file.split(/[\\/]/).pop() || 'download' if (downloads?.supported) { const pending = await downloads.prepare(temporary.uri, name) await downloads.finish(pending, !controller.signal.aborted) if (!controller.signal.aborted) ToastAndroid.show(t.tools.savedToDownloads, ToastAndroid.SHORT) return } if (directory === undefined || !directory.granted) return uri = await FileSystem.StorageAccessFramework.createFileAsync(directory.directoryUri, name, 'application/octet-stream') if (controller.signal.aborted) return const source = temporary.open(FileMode.ReadOnly) try { const destination = new LocalFile(uri).open(FileMode.Truncate) try { let remaining = source.size ?? temporary.size while (remaining > 0 && !controller.signal.aborted) { const bytes = source.readBytes(Math.min(PREVIEW_CHUNK_BYTES, remaining)) if (bytes.byteLength === 0) throw new Error('Unexpected end of temporary download') destination.writeBytes(bytes) remaining -= bytes.byteLength // Yield between bounded writes so navigation can cancel local saving too. await new Promise(resolve => setTimeout(resolve, 0)) } } finally { destination.close() } } finally { source.close() } if (controller.signal.aborted) return uri = undefined if (!controller.signal.aborted) ToastAndroid.show(t.tools.downloaded, ToastAndroid.SHORT) } catch (e) { if (!controller.signal.aborted) Alert.alert(t.tools.download, typeof e === 'object' && e !== null && 'code' in e && e.code === 'workspace-preview/too-large' ? t.tools.downloadTooLarge : sessionToolsError(e)) } finally { try { if (temporary?.exists) temporary.delete() } catch (e) { if (!controller.signal.aborted) Alert.alert(t.tools.download, sessionToolsError(e)) } if (uri) await FileSystem.deleteAsync(uri, { idempotent: true }).catch(() => {}) if (downloadController.current === controller) { downloadController.current = undefined setDownloading(false) } } } const preview = useRef(null) const kind = file === undefined ? undefined : classifyWorkspaceFile(file) const markdown = file !== undefined && /\.(?:md|markdown|mdown)$/i.test(file) useEffect(() => { const controller = new AbortController() setLoading(true) setError(undefined) setPage(undefined) setBinary(undefined) setListing(undefined) const run = async () => { const tools = requireSessionTools(sessionId) if (file === undefined) { const result = await tools.listFiles(sessionId, path, controller.signal) if (!controller.signal.aborted) setListing(result) } else if (kind === 'text') { const result = await tools.readFile(sessionId, file, offset, controller.signal) if (!controller.signal.aborted) { setPage(result); preview.current?.scrollTo({ y: 0, animated: false }) } } else if (kind === 'image' || kind === 'pdf' || kind === 'office') { const result = await loadWorkspacePreview(tools, sessionId, file, kind, controller.signal) if (!controller.signal.aborted) setBinary(result) } else if (kind === 'unsupported') { // Linked paths can be folders; the stat endpoint does not report the // type, so an unclassifiable path falls back to a directory listing. const result = await tools.listFiles(sessionId, file, controller.signal) // listFiles only succeeds for a directory; reopen it as the listing path. if (!controller.signal.aborted && result !== undefined) { setPath(file.replace(/\/+$/u, '')); setFile(undefined) } } } void run().catch(e => { if (!controller.signal.aborted) setError(sessionToolsError(e)) }) .finally(() => { if (!controller.signal.aborted) setLoading(false) }) return () => controller.abort() }, [sessionId, path, file, kind, offset, revision]) useEffect(() => { const controller = new AbortController() setFileBytes(undefined) if (file !== undefined) { void Promise.resolve().then(() => requireSessionTools(sessionId).statFile(sessionId, file, controller.signal)) .then(stat => { if (!controller.signal.aborted) setFileBytes(stat.bytes) }).catch(() => {}) } return () => controller.abort() }, [sessionId, file, revision]) const back = () => { if (file !== undefined) setFile(undefined) else if (path !== '') setPath(path.split('/').slice(0, -1).join('/')) else onClose() } return {file !== undefined && (downloading ? : void download()} disabled={tooLargeToSave} />)} setRevision(v => v + 1)} disabled={loading || downloading} /> } />}> {file ?? (path || t.tools.root)} {file !== undefined && kind === 'unsupported' && {t.tools.previewUnsupported}} {file !== undefined && tooLargeToSave && {t.tools.downloadTooLarge}} {loading && {kind === 'office' ? t.tools.officeLoading : t.tools.previewLoading}} {error && {error}