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