Open History to see the last commit
1import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
2import { environmentSession } from "../../state/session";
3import { NativeStackScreenOptions } from "../../native/StackHeader";
4import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
5import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
6import { Platform, View } from "react-native";
7import { useSafeAreaInsets } from "react-native-safe-area-context";
8import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
9import { EnvironmentId, type ProjectReadFileResult, ThreadId } from "@t3tools/contracts";
10import { videoMimeType } from "@t3tools/shared/video";
11import {
12 isWorkspaceBrowserPreviewPath,
13 isWorkspaceImagePreviewPath,
14 mediaMimeTypeFromExtension,
15} from "@t3tools/shared/filePreview";
16import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
17
18import { ScreenContent } from "../../components/ui/ScreenContent";
19import { AudioFilePreview } from "./AudioFilePreview";
20import { EmptyState } from "../../components/ui/EmptyState";
21import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
22import { LoadingScreen } from "../../components/LoadingScreen";
23import { resolveFileSelectionNavigationAction } from "../../lib/adaptive-navigation";
24import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
25import { isPdfFile } from "../../lib/filePreview";
26import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
27import { useUniwindTheme } from "../../lib/useUniwindTheme";
28import type { MediaVideoPreviewSource } from "../../lib/videoPreviewSource";
29import { useMediaActions } from "../../state/mediaActions";
30import { type MediaActionsSource } from "../../lib/mediaActionsSource";
31import { useThreadSelection } from "../../state/use-thread-selection";
32import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
33import { useEnvironmentQuery } from "../../state/query";
34import { useEnvironmentPresentation } from "../../state/presentation";
35import { projectEnvironment } from "../../state/projects";
36import type { AssetUrlFailureReason } from "../../state/asset-url-state";
37import {
38 useAdaptiveWorkspaceLayout,
39 useAdaptiveWorkspacePaneRole,
40 useRegisterWorkspaceInspector,
41} from "../layout/AdaptiveWorkspaceLayout";
42import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
43import { ThreadRouteScreen } from "../threads/ThreadRouteScreen";
44import { FilePreviewLoading, FilePreviewNotice } from "./FilePreviewFeedback";
45import { FileMarkdownPreview } from "./FileMarkdownPreview";
46import { ThreadInspectorContentStack } from "../threads/thread-inspector-content-stack";
47import { FileTreeBrowser } from "./FileTreeBrowser";
48import { useFileTreeEntries } from "./useFileTreeEntries";
49import { preloadWorkspaceFileContents } from "./preload-workspace-file";
50import { SourceFileSurface } from "./SourceFileSurface";
51import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
52import { ThreadFileNavigatorPane } from "./thread-file-navigator-pane";
53import { AppBar } from "../../components/ui/AppBar";
54import { WorkspaceFileImagePreview } from "./WorkspaceFileImagePreview";
55import { WorkspaceFilePreviewError } from "./WorkspaceFilePreviewError";
56import { WorkspaceFileVideoPreview } from "./WorkspaceFileVideoPreview";
57import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
58import {
59 basename,
60 fileHeaderSubtitle,
61 isAudioPreviewFile,
62 isMarkdownPreviewFile,
63 isSvgImagePreviewFile,
64 isVideoPreviewFile,
65} from "./filePath";
66import { useWorkspaceFileAssetUrlState } from "./workspaceFileAssetUrl";
67
68function FilesBrowserHeader(props: {
69 readonly projectName: string;
70 readonly searchQuery: string;
71 readonly onSearchQueryChange: (query: string) => void;
72 readonly onRefresh: () => void;
73 readonly onBack: () => void;
74}) {
75 return (
76 <AppBar
77 title="Files"
78 subtitle={props.projectName}
79 onBack={props.onBack}
80 hideBottomBorder
81 matchSearchSurface
82 search={{
83 value: props.searchQuery,
84 onChangeText: props.onSearchQueryChange,
85 placeholder: "Search files",
86 closeAccessibilityLabel: "Close file search",
87 clearAccessibilityLabel: "Clear file search",
88 }}
89 menus={
90 Platform.OS === "android"
91 ? [
92 {
93 title: "File options",
94 icon: "ellipsis",
95 items: [{ id: "refresh", title: "Refresh files", onPress: props.onRefresh }],
96 },
97 ]
98 : undefined
99 }
100 />
101 );
102}
103
104function FileHeader(props: {
105 readonly title: string;
106 readonly subtitle: string;
107 readonly iconColor: string;
108 readonly activeMode: string;
109 readonly fileInspectorSupported: boolean;
110 readonly onBack: () => void;
111 readonly onReturnToThread: () => void;
112 readonly actions: ReadonlyArray<{
113 readonly id: string;
114 readonly title: string;
115 readonly icon: string;
116 readonly inline: boolean;
117 readonly onPress: () => unknown;
118 }>;
119}) {
120 const { panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
121 const modes = props.actions.filter(({ inline }) => inline);
122 return (
123 <AppBar
124 title={props.title}
125 subtitle={props.subtitle}
126 onBack={props.onBack}
127 hideBottomBorder
128 options={{ headerTintColor: props.iconColor, headerTitle: props.title }}
129 backInSplitView={
130 props.fileInspectorSupported
131 ? {
132 accessibilityLabel: "Return to chat",
133 icon: "chevron.left",
134 onPress: props.onReturnToThread,
135 }
136 : undefined
137 }
138 actions={
139 props.fileInspectorSupported
140 ? [
141 {
142 accessibilityLabel: panes.auxiliaryPaneVisible
143 ? "Hide file navigator"
144 : "Show file navigator",
145 icon: "sidebar.right",
146 selected: panes.auxiliaryPaneVisible,
147 onPress: toggleAuxiliaryPane,
148 },
149 ]
150 : undefined
151 }
152 menus={[
153 {
154 title: "File actions",
155 icon: "ellipsis",
156 separateBackground: false,
157 items: [
158 ...(modes.length > 0
159 ? [
160 {
161 id: "modes",
162 inline: true,
163 items: modes.map((action) => ({
164 ...action,
165 selected: action.id === props.activeMode,
166 })),
167 },
168 ]
169 : []),
170 ...props.actions.filter(({ inline }) => !inline),
171 ],
172 },
173 ]}
174 />
175 );
176}
177
178type FileViewMode = "preview" | "source";
179
180function firstRouteParam(value: string | string[] | undefined): string | null {
181 const first = Array.isArray(value) ? value[0] : value;
182 return first === undefined || first.trim().length === 0 ? null : first;
183}
184
185function normalizeRoutePath(value: string | string[] | undefined): string | null {
186 const path = Array.isArray(value) ? value.join("/") : value;
187 if (path === undefined || path.trim().length === 0) {
188 return null;
189 }
190 return path;
191}
192
193function normalizeRouteLine(value: string | null): number | null {
194 if (value === null) {
195 return null;
196 }
197 const parsed = Number(value);
198 return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
199}
200
201function defaultViewMode(path: string | null): FileViewMode {
202 return path !== null &&
203 (isWorkspaceBrowserPreviewPath(path) ||
204 isWorkspaceImagePreviewPath(path) ||
205 isVideoPreviewFile(path) ||
206 isAudioPreviewFile(path))
207 ? "preview"
208 : "source";
209}
210
211function FileContent(props: {
212 readonly activeMode: FileViewMode;
213 readonly cwd: string;
214 readonly environmentId: EnvironmentId;
215 readonly previewUri: string | null;
216 readonly previewFailure: AssetUrlFailureReason | null;
217 readonly onRetryPreview: () => void;
218 readonly videoSource: MediaVideoPreviewSource | null;
219 readonly mediaSource?: MediaActionsSource;
220 readonly resolveVideoUri: () => Promise<string | null>;
221 readonly fileContents: string | null;
222 readonly fileError: string | null;
223 readonly relativePath: string;
224 readonly threadId: ThreadId | null;
225 readonly initialLine: number | null;
226 readonly truncated: boolean;
227 readonly onRefresh?: () => Promise<void> | void;
228}) {
229 // Reopening a mutable host file must not reuse a poster from an earlier visit.
230 const thumbnailInstanceId = useId();
231 const insets = useSafeAreaInsets();
232 const columnMetrics = useNativeColumnLayoutMetrics();
233 const reservedHeaderInset =
234 Platform.OS === "ios" && props.truncated ? (columnMetrics?.safeArea.top ?? insets.top) : 0;
235 const isMarkdown = isMarkdownPreviewFile(props.relativePath);
236 const isBrowserFile = isWorkspaceBrowserPreviewPath(props.relativePath);
237 const isImageFile = isWorkspaceImagePreviewPath(props.relativePath);
238 const isVideoFile = isVideoPreviewFile(props.relativePath);
239 const isAudioFile = isAudioPreviewFile(props.relativePath);
240 const needsAssetUrl =
241 isVideoFile ||
242 isAudioFile ||
243 (props.activeMode === "preview" && (isImageFile || isBrowserFile));
244
245 if (needsAssetUrl && props.previewFailure !== null) {
246 return (
247 <WorkspaceFilePreviewError
248 environmentId={props.environmentId}
249 reason={props.previewFailure}
250 onRetry={props.onRetryPreview}
251 />
252 );
253 }
254
255 if (isVideoFile) {
256 return (
257 <WorkspaceFileVideoPreview
258 name={basename(props.relativePath)}
259 thumbnailKey={`workspace-video:${thumbnailInstanceId}`}
260 uri={props.previewUri}
261 source={props.videoSource}
262 resolvePlaybackUri={props.resolveVideoUri}
263 />
264 );
265 }
266
267 if (isAudioFile) {
268 return props.previewUri === null ? (
269 <FilePreviewLoading message="Loading file..." />
270 ) : (
271 <AudioFilePreview uri={props.previewUri} onRetry={props.onRetryPreview} />
272 );
273 }
274
275 if (props.activeMode === "preview" && isImageFile) {
276 if (isSvgImagePreviewFile(props.relativePath)) {
277 return <WorkspaceFileWebPreview uri={props.previewUri} />;
278 }
279 return (
280 <WorkspaceFileImagePreview
281 accessibilityLabel={basename(props.relativePath)}
282 uri={props.previewUri}
283 actionsSource={props.mediaSource}
284 />
285 );
286 }
287
288 if (props.activeMode === "preview" && isBrowserFile) {
289 return <WorkspaceFileWebPreview uri={props.previewUri} />;
290 }
291
292 if (props.fileError && props.fileContents === null) {
293 return (
294 <View className="flex-1 items-center justify-center bg-sheet px-6">
295 <EmptyState title="File unavailable" detail={props.fileError} />
296 </View>
297 );
298 }
299
300 if (props.fileContents === null) {
301 return <FilePreviewLoading message="Loading file..." />;
302 }
303
304 return (
305 <View className="flex-1 bg-sheet" style={{ paddingTop: reservedHeaderInset }}>
306 {props.truncated ? (
307 <FilePreviewNotice title="Partial file">
308 Preview limited to the first 1 MB of a truncated file.
309 </FilePreviewNotice>
310 ) : null}
311 {props.activeMode === "preview" && isMarkdown ? (
312 <FileMarkdownPreview
313 cwd={props.cwd}
314 environmentId={props.environmentId}
315 markdown={props.fileContents}
316 relativePath={props.relativePath}
317 threadId={props.threadId}
318 onRefresh={props.onRefresh}
319 />
320 ) : (
321 <SourceFileSurface
322 contents={props.fileContents}
323 path={props.relativePath}
324 initialLine={props.initialLine}
325 headerInsetTop={props.truncated ? 0 : undefined}
326 onRefresh={props.onRefresh}
327 />
328 )}
329 </View>
330 );
331}
332
333type ThreadFilesRouteScreenProps = StaticScreenProps<{
334 readonly environmentId: string;
335 readonly threadId: string;
336}>;
337
338type ThreadFileRouteScreenProps = StaticScreenProps<{
339 readonly environmentId: string;
340 readonly threadId?: string;
341 readonly path: string[];
342 readonly line?: string;
343 readonly cwd?: string;
344 readonly projectName?: string;
345}>;
346
347function useThreadFilesWorkspace(params: {
348 readonly environmentId?: string | string[];
349 readonly threadId?: string | string[];
350 readonly cwd?: string | string[];
351 readonly projectName?: string | string[];
352}) {
353 const routeEnvironmentId = firstRouteParam(params.environmentId);
354 const routeThreadId = firstRouteParam(params.threadId);
355 const routeCwd = firstRouteParam(params.cwd);
356 const routeProjectName = firstRouteParam(params.projectName);
357 const { selectedThread, selectedThreadProject } = useThreadSelection();
358 const { selectedThreadCwd } = useSelectedThreadWorktree();
359 const environmentId =
360 routeEnvironmentId !== null
361 ? EnvironmentId.make(routeEnvironmentId)
362 : (selectedThread?.environmentId ?? null);
363 const threadId = routeThreadId !== null ? ThreadId.make(routeThreadId) : null;
364 const project = selectedThreadProject as {
365 readonly title?: string;
366 readonly workspaceRoot?: string;
367 } | null;
368
369 return {
370 cwd: routeCwd ?? selectedThreadCwd ?? project?.workspaceRoot ?? null,
371 environmentId,
372 projectName: routeProjectName ?? project?.title ?? "Files",
373 selectedThread,
374 threadId,
375 };
376}
377
378function FilesUnavailable({
379 detail = "This thread does not have an active workspace path.",
380}: {
381 detail?: string;
382}) {
383 return (
384 <View className="flex-1 items-center justify-center bg-sheet px-6">
385 <NativeStackScreenOptions options={{ title: "Files" }} />
386 <EmptyState title="Files unavailable" detail={detail} />
387 </View>
388 );
389}
390
391function FilesToolbarBottomFade() {
392 const sheetColor = String(useUniwindTheme()["--color-sheet"]);
393
394 if (process.env.EXPO_OS !== "ios") {
395 return null;
396 }
397
398 return (
399 <View
400 pointerEvents="none"
401 accessibilityElementsHidden
402 importantForAccessibility="no-hide-descendants"
403 className="absolute inset-x-0 bottom-0 z-[1] h-28"
404 >
405 <Svg width="100%" height="100%">
406 <Defs>
407 <LinearGradient id="files-toolbar-bottom-fade" x1="0%" x2="0%" y1="0%" y2="100%">
408 <Stop offset="0%" stopColor={sheetColor} stopOpacity={0} />
409 <Stop offset="58%" stopColor={sheetColor} stopOpacity={0.72} />
410 <Stop offset="100%" stopColor={sheetColor} stopOpacity={0.96} />
411 </LinearGradient>
412 </Defs>
413 <Rect width="100%" height="100%" fill="url(#files-toolbar-bottom-fade)" />
414 </Svg>
415 </View>
416 );
417}
418
419export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
420 useAdaptiveWorkspacePaneRole("inspector");
421 const navigation = useNavigation();
422 const { fileInspector, layout, showAuxiliaryPane } = useAdaptiveWorkspaceLayout();
423 const [searchQuery, setSearchQuery] = useState("");
424 const { themeAppearance: highlightTheme } = useAppearancePreferences();
425 const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
426 props.route.params,
427 );
428 const revealedInspectorRef = useRef(false);
429 const fileAccessSession = useEnvironmentQuery(
430 environmentId !== null ? environmentSession.sessionStateAtom(environmentId) : null,
431 );
432 const fileEnvironment = useEnvironmentPresentation(environmentId);
433 const fileAccess = resolveFilesystemReadAccess({
434 isCatalogReady: fileEnvironment.isReady,
435 connection: fileEnvironment.presentation?.connection ?? null,
436 session: fileAccessSession.data,
437 sessionError: fileAccessSession.error,
438 });
439 const { canReadFiles } = fileAccess;
440 const entriesQuery = useFileTreeEntries({
441 environmentId,
442 cwd: !canReadFiles || fileInspector.supported ? null : cwd,
443 searchQuery,
444 });
445 const handleReturnToThread = useCallback(() => {
446 if (navigation.canGoBack()) {
447 navigation.goBack();
448 return;
449 }
450 if (environmentId !== null && threadId !== null) {
451 navigation.dispatch(
452 StackActions.replace("Thread", {
453 environmentId: String(environmentId),
454 threadId: String(threadId),
455 }),
456 );
457 }
458 }, [environmentId, navigation, threadId]);
459
460 const handleSelectFile = useCallback(
461 (path: string) => {
462 if (environmentId === null || threadId === null) {
463 return;
464 }
465 const params = {
466 environmentId: String(environmentId),
467 threadId: String(threadId),
468 path: path.split("/").filter((segment) => segment.length > 0),
469 };
470 const navigationAction = resolveFileSelectionNavigationAction({
471 hasPersistentFileInspector: fileInspector.supported,
472 });
473 if (navigationAction === "replace") {
474 navigation.dispatch(StackActions.replace("ThreadFile", params));
475 return;
476 }
477 navigation.navigate("ThreadFile", params);
478 },
479 [environmentId, fileInspector.supported, navigation, threadId],
480 );
481 const renderInspector = useCallback(
482 (headerInset: number) =>
483 environmentId !== null && cwd !== null ? (
484 <ThreadFileNavigatorPane
485 cwd={cwd}
486 environmentId={environmentId}
487 headerInset={headerInset}
488 projectName={projectName}
489 selectedPath={null}
490 onSelectFile={handleSelectFile}
491 />
492 ) : null,
493 [cwd, environmentId, handleSelectFile, projectName],
494 );
495 const handlePreviewFile = useCallback(
496 (relativePath: string) => {
497 if (environmentId === null || cwd === null) {
498 return;
499 }
500 preloadWorkspaceFileContents({
501 cwd,
502 environmentId,
503 relativePath,
504 theme: highlightTheme,
505 });
506 },
507 [cwd, environmentId, highlightTheme],
508 );
509 useEffect(() => {
510 if (fileInspector.supported && cwd !== null && !revealedInspectorRef.current) {
511 revealedInspectorRef.current = true;
512 showAuxiliaryPane("inspector");
513 }
514 }, [cwd, fileInspector.supported, showAuxiliaryPane]);
515
516 if (selectedThread === null || environmentId === null || threadId === null) {
517 if (fileInspector.supported) {
518 return (
519 <ThreadRouteScreen
520 onReturnToThread={handleReturnToThread}
521 renderInspector={renderInspector}
522 route={props.route}
523 />
524 );
525 }
526 return <LoadingScreen message="Opening files..." messagePlacement="above-spinner" />;
527 }
528
529 if (!canReadFiles) {
530 if (fileAccess.isPending) {
531 return <LoadingScreen message="Checking file access..." messagePlacement="above-spinner" />;
532 }
533 return (
534 <FilesUnavailable detail={fileAccess.error ?? "This connection cannot read host files."} />
535 );
536 }
537 if (cwd === null) {
538 return <FilesUnavailable />;
539 }
540
541 if (fileInspector.supported) {
542 return (
543 <ThreadRouteScreen
544 onReturnToThread={handleReturnToThread}
545 renderInspector={renderInspector}
546 route={props.route}
547 />
548 );
549 }
550
551 const content = (
552 <>
553 <FilesBrowserHeader
554 projectName={projectName}
555 searchQuery={searchQuery}
556 onSearchQueryChange={setSearchQuery}
557 onRefresh={entriesQuery.refresh}
558 onBack={handleReturnToThread}
559 />
560 <ScreenContent insetHorizontal={layout.usesSplitView}>
561 <FileTreeBrowser
562 key={JSON.stringify([environmentId, cwd])}
563 entries={entriesQuery.entries}
564 loadingDirectories={entriesQuery.loadingDirectories}
565 onLoadDirectory={entriesQuery.loadDirectory}
566 error={entriesQuery.error}
567 isPending={entriesQuery.isPending}
568 isRefreshing={entriesQuery.isRefreshing}
569 searchQuery={searchQuery}
570 searchTruncated={entriesQuery.searchTruncated}
571 selectedPath={null}
572 onPreviewFile={handlePreviewFile}
573 onRefresh={entriesQuery.refresh}
574 onSelectFile={handleSelectFile}
575 />
576 <FilesToolbarBottomFade />
577 </ScreenContent>
578 </>
579 );
580
581 return Platform.OS === "android" ? <View className="flex-1 bg-header">{content}</View> : content;
582}
583
584export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
585 useAdaptiveWorkspacePaneRole("inspector");
586 const navigation = useNavigation();
587 const { fileInspector } = useAdaptiveWorkspaceLayout();
588 const { appearance, setCodeWordBreak } = useAppearancePreferences();
589 const iconColor = useUniwindTheme()["--color-icon"];
590 const params = props.route.params;
591 const relativePath = normalizeRoutePath(params.path);
592 const targetLine = normalizeRouteLine(firstRouteParam(params.line));
593 const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
594 props.route.params,
595 );
596 const [modeOverride, setModeOverride] = useState<{
597 readonly path: string;
598 readonly mode: FileViewMode;
599 } | null>(null);
600 const [previewRevision, setPreviewRevision] = useState(0);
601 const previewKey = JSON.stringify([environmentId, cwd, relativePath, previewRevision]);
602 const [fullScreenPreview, setFullScreenPreview] = useState<FilePreviewSource | null>(null);
603 const isVideoFile = relativePath !== null && isVideoPreviewFile(relativePath);
604 const isAudioFile = relativePath !== null && !isVideoFile && isAudioPreviewFile(relativePath);
605 const isBrowserFile =
606 relativePath !== null && !isVideoFile && isWorkspaceBrowserPreviewPath(relativePath);
607 const isImageFile =
608 relativePath !== null && !isVideoFile && isWorkspaceImagePreviewPath(relativePath);
609 const canPreview =
610 relativePath !== null &&
611 (isMarkdownPreviewFile(relativePath) ||
612 isBrowserFile ||
613 isImageFile ||
614 isVideoFile ||
615 isAudioFile);
616 const activeMode =
617 relativePath !== null && modeOverride?.path === relativePath
618 ? modeOverride.mode
619 : defaultViewMode(relativePath);
620 const resolvedActiveMode =
621 isVideoFile || isAudioFile ? "preview" : canPreview ? activeMode : "source";
622 const assetPreviewPath =
623 isBrowserFile || isImageFile || isVideoFile || isAudioFile ? relativePath : null;
624 const assetPreview = useWorkspaceFileAssetUrlState({
625 cwd,
626 environmentId,
627 relativePath: assetPreviewPath,
628 threadId,
629 draftCwd: threadId === null ? cwd : null,
630 });
631 const assetPreviewUri = assetPreview._tag === "Success" ? assetPreview.url : null;
632 const mediaSource = useMemo<MediaActionsSource | undefined>(
633 () =>
634 environmentId !== null &&
635 relativePath !== null &&
636 assetPreview.resource !== null &&
637 "path" in assetPreview.resource &&
638 typeof assetPreview.resource.path === "string" &&
639 (isImageFile || isVideoFile)
640 ? {
641 reference: mediaFileReference(assetPreview.resource.path, cwd),
642 name: basename(relativePath),
643 mimeType:
644 mediaMimeTypeFromExtension(relativePath.slice(relativePath.lastIndexOf("."))) ??
645 "application/octet-stream",
646 environmentId,
647 ...(threadId === null ? {} : { threadId }),
648 resource: assetPreview.resource,
649 }
650 : undefined,
651 [assetPreview.resource, cwd, environmentId, isImageFile, isVideoFile, relativePath, threadId],
652 );
653 const mediaActions = useMediaActions(mediaSource);
654 const videoSource = useMemo<MediaVideoPreviewSource | null>(
655 () =>
656 environmentId !== null &&
657 relativePath !== null &&
658 (assetPreview.resource?._tag === "media-file" ||
659 assetPreview.resource?._tag === "draft-workspace-file")
660 ? {
661 type: "media",
662 environmentId,
663 resource: assetPreview.resource,
664 name: basename(relativePath),
665 mimeType: videoMimeType({ name: relativePath, mimeType: "" }) ?? "video/mp4",
666 actionsSource: mediaSource,
667 }
668 : null,
669 [assetPreview.resource, environmentId, relativePath, mediaSource],
670 );
671 const previewUri =
672 assetPreviewUri === null || previewRevision === 0
673 ? assetPreviewUri
674 : `${assetPreviewUri}${assetPreviewUri.includes("?") ? "&" : "?"}revision=${previewRevision}`;
675 // Remounting the preview after a re-mint is what makes a failed asset URL retryable.
676 const handleRetryPreview = () => {
677 void assetPreview.refresh().finally(() => setPreviewRevision((current) => current + 1));
678 };
679 const needsFileContents =
680 relativePath !== null &&
681 !isVideoFile &&
682 !isAudioFile &&
683 (resolvedActiveMode === "source" || isMarkdownPreviewFile(relativePath));
684 const fileAccessSession = useEnvironmentQuery(
685 environmentId !== null ? environmentSession.sessionStateAtom(environmentId) : null,
686 );
687 const fileEnvironment = useEnvironmentPresentation(environmentId);
688 const fileAccess = resolveFilesystemReadAccess({
689 isCatalogReady: fileEnvironment.isReady,
690 connection: fileEnvironment.presentation?.connection ?? null,
691 session: fileAccessSession.data,
692 sessionError: fileAccessSession.error,
693 });
694 const { canReadFiles } = fileAccess;
695 const fileQuery = useEnvironmentQuery(
696 canReadFiles &&
697 environmentId !== null &&
698 cwd !== null &&
699 relativePath !== null &&
700 needsFileContents
701 ? projectEnvironment.readFile({
702 environmentId,
703 input: { cwd, relativePath },
704 })
705 : null,
706 );
707 const fileData = fileQuery.data as ProjectReadFileResult | null;
708
709 const handleSelectFile = useCallback(
710 (path: string) => {
711 const segments = path.split("/").filter(Boolean);
712 // A draft has no thread. `ThreadFile` would stringify null and then wait forever for a
713 // thread to resolve, so a draft stays on its own route and carries its workspace along.
714 if (threadId === null) {
715 navigation.dispatch(
716 StackActions.push("NewTaskFile", {
717 environmentId: String(environmentId),
718 ...(cwd === null ? {} : { cwd }),
719 projectName,
720 path: segments,
721 }),
722 );
723 return;
724 }
725 navigation.navigate("ThreadFile", {
726 environmentId: String(environmentId),
727 threadId: String(threadId),
728 path: segments,
729 });
730 },
731 [cwd, environmentId, navigation, projectName, threadId],
732 );
733 const renderInspector = useCallback(
734 (headerInset: number) =>
735 fileInspector.supported && environmentId !== null && cwd !== null ? (
736 <ThreadFileNavigatorPane
737 cwd={cwd}
738 environmentId={environmentId}
739 headerInset={headerInset}
740 projectName={projectName}
741 selectedPath={relativePath}
742 onSelectFile={handleSelectFile}
743 />
744 ) : undefined,
745 [cwd, environmentId, fileInspector.supported, handleSelectFile, projectName, relativePath],
746 );
747 const safeAreaInsets = useSafeAreaInsets();
748 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
749 const renderWorkspaceInspector = useCallback(
750 () => (
751 <ThreadInspectorContentStack
752 mode="files"
753 resetKeys={[threadId, cwd]}
754 renderFiles={() => renderInspector(inspectorHeaderInset)}
755 />
756 ),
757 [cwd, inspectorHeaderInset, renderInspector, threadId],
758 );
759 useRegisterWorkspaceInspector(fileInspector.supported ? renderWorkspaceInspector : undefined);
760
761 const fileMenuActions = useMemo(() => {
762 if (relativePath === null) return [];
763 const canToggleMode = canPreview && !isImageFile && !isVideoFile && !isAudioFile;
764 return [
765 canToggleMode
766 ? ({
767 id: "preview",
768 title: "Preview",
769 icon: "eye",
770 inline: true,
771 onPress: () => setModeOverride({ path: relativePath, mode: "preview" }),
772 } as const)
773 : null,
774 canToggleMode
775 ? ({
776 id: "source",
777 title: "Source",
778 icon: "doc.text",
779 inline: true,
780 onPress: () => setModeOverride({ path: relativePath, mode: "source" }),
781 } as const)
782 : null,
783 resolvedActiveMode === "source"
784 ? ({
785 id: "word-wrap",
786 title: appearance.codeWordBreak ? "Disable word wrap" : "Enable word wrap",
787 icon: "text.alignleft",
788 inline: false,
789 onPress: () => setCodeWordBreak(!appearance.codeWordBreak),
790 } as const)
791 : null,
792 ...(mediaSource
793 ? mediaActions.actions
794 .filter(({ id }) => id !== "open-file")
795 .map((action) => ({
796 id: action.id,
797 title: action.title,
798 icon:
799 action.id === "save" ? ("square.and.arrow.up" as const) : ("doc.on.doc" as const),
800 inline: false,
801 onPress: action.run,
802 }))
803 : [
804 {
805 id: "copy-path",
806 title: "Copy path",
807 icon: "doc.on.doc",
808 inline: false,
809 onPress: () => copyTextWithHaptic(relativePath),
810 } as const,
811 ]),
812 fileData?.contents != null
813 ? ({
814 id: "copy-contents",
815 title: fileData.truncated ? "Copy preview" : "Copy contents",
816 icon: "doc.on.doc",
817 inline: false,
818 onPress: () => copyTextWithHaptic(fileData.contents),
819 } as const)
820 : null,
821 isPdfFile({ name: relativePath }) && previewUri !== null
822 ? ({
823 id: "open-pdf",
824 title: "Open PDF",
825 icon: "arrow.up.left.and.arrow.down.right",
826 inline: false,
827 onPress: () =>
828 setFullScreenPreview({
829 kind: "pdf",
830 uri: previewUri,
831 name: basename(relativePath),
832 }),
833 } as const)
834 : null,
835 isBrowserFile && typeof assetPreviewUri === "string"
836 ? ({
837 id: "open-browser",
838 title: Platform.OS === "ios" ? "Open in Safari" : "Open in browser",
839 icon: "safari",
840 inline: false,
841 onPress: () => tryOpenExternalUrl(assetPreviewUri, "file-preview"),
842 } as const)
843 : null,
844 resolvedActiveMode === "preview" &&
845 (isBrowserFile || isImageFile || isVideoFile || isAudioFile)
846 ? ({
847 id: "refresh",
848 title: "Refresh",
849 icon: "arrow.clockwise",
850 inline: false,
851 onPress: async () => {
852 if (isVideoFile || isAudioFile) await assetPreview.refresh();
853 setPreviewRevision((current) => current + 1);
854 },
855 } as const)
856 : null,
857 ].filter((action) => action !== null);
858 }, [
859 appearance.codeWordBreak,
860 setCodeWordBreak,
861 assetPreviewUri,
862 assetPreview.refresh,
863 previewUri,
864 canPreview,
865 isAudioFile,
866 isBrowserFile,
867 isImageFile,
868 isVideoFile,
869 relativePath,
870 resolvedActiveMode,
871 mediaSource,
872 mediaActions.actions,
873 fileData?.contents,
874 fileData?.truncated,
875 ]);
876
877 const handleReturnToThread = useCallback(() => {
878 if (environmentId !== null && threadId !== null) {
879 navigation.dispatch(
880 StackActions.replace("Thread", {
881 environmentId: String(environmentId),
882 threadId: String(threadId),
883 }),
884 );
885 }
886 }, [environmentId, navigation, threadId]);
887 const handleBack = useCallback(() => {
888 if (navigation.canGoBack()) {
889 navigation.goBack();
890 return;
891 }
892 handleReturnToThread();
893 }, [handleReturnToThread, navigation]);
894
895 if (environmentId === null || (threadId !== null && selectedThread === null)) {
896 return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
897 }
898
899 if (!canReadFiles) {
900 if (fileAccess.isPending) {
901 return <LoadingScreen message="Checking file access..." messagePlacement="above-spinner" />;
902 }
903 return (
904 <FilesUnavailable detail={fileAccess.error ?? "This connection cannot read host files."} />
905 );
906 }
907 if (cwd === null) {
908 return <FilesUnavailable />;
909 }
910
911 if (relativePath === null) {
912 return (
913 <View className="flex-1 items-center justify-center bg-sheet px-6">
914 <NativeStackScreenOptions options={{ title: "Files" }} />
915 <EmptyState title="File unavailable" detail="This file path is invalid." />
916 </View>
917 );
918 }
919
920 const headerSubtitle = fileHeaderSubtitle(projectName, relativePath);
921
922 return (
923 <View className="flex-1 bg-sheet">
924 <FileHeader
925 title={basename(relativePath)}
926 subtitle={headerSubtitle}
927 iconColor={iconColor}
928 activeMode={resolvedActiveMode}
929 fileInspectorSupported={fileInspector.supported}
930 onBack={handleBack}
931 onReturnToThread={handleReturnToThread}
932 actions={fileMenuActions}
933 />
934 <ScreenContent>
935 <FileContent
936 key={previewKey}
937 activeMode={resolvedActiveMode}
938 cwd={cwd}
939 environmentId={environmentId}
940 previewUri={previewUri}
941 previewFailure={assetPreview._tag === "Failure" ? assetPreview.reason : null}
942 onRetryPreview={handleRetryPreview}
943 videoSource={videoSource}
944 mediaSource={mediaSource}
945 resolveVideoUri={assetPreview.refresh}
946 fileContents={fileData?.contents ?? null}
947 fileError={fileQuery.error}
948 initialLine={targetLine}
949 relativePath={relativePath}
950 threadId={threadId}
951 truncated={fileData?.truncated ?? false}
952 onRefresh={() => fileQuery.refresh()}
953 />
954 </ScreenContent>
955 <FilePreviewModal
956 source={fullScreenPreview}
957 onRequestClose={() => setFullScreenPreview(null)}
958 />
959 </View>
960 );
961}