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 { MaterialScreenContent } from "../../components/MaterialScreenContent";
19import { AudioFilePreview } from "../../components/AudioFilePreview";
20import { EmptyState } from "../../components/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 { ThreadFileNavigatorPane } from "./thread-file-navigator-pane";
52import { ScreenHeader } from "../../components/ScreenHeader";
53import { WorkspaceFileImagePreview } from "./WorkspaceFileImagePreview";
54import { WorkspaceFilePreviewError } from "./WorkspaceFilePreviewError";
55import { WorkspaceFileVideoPreview } from "./WorkspaceFileVideoPreview";
56import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
57import {
58 basename,
59 fileHeaderSubtitle,
60 isAudioPreviewFile,
61 isMarkdownPreviewFile,
62 isSvgImagePreviewFile,
63 isVideoPreviewFile,
64} from "./filePath";
65import { useWorkspaceFileAssetUrlState } from "./workspaceFileAssetUrl";
66
67function FilesBrowserHeader(props: {
68 readonly projectName: string;
69 readonly searchQuery: string;
70 readonly onSearchQueryChange: (query: string) => void;
71 readonly onRefresh: () => void;
72 readonly onBack: () => void;
73}) {
74 return (
75 <ScreenHeader
76 title="Files"
77 subtitle={props.projectName}
78 onBack={props.onBack}
79 hideBottomBorder
80 matchSearchSurface
81 search={{
82 value: props.searchQuery,
83 onChangeText: props.onSearchQueryChange,
84 placeholder: "Search files",
85 closeAccessibilityLabel: "Close file search",
86 clearAccessibilityLabel: "Clear file search",
87 }}
88 menus={
89 Platform.OS === "android"
90 ? [
91 {
92 title: "File options",
93 icon: "ellipsis",
94 items: [{ id: "refresh", title: "Refresh files", onPress: props.onRefresh }],
95 },
96 ]
97 : undefined
98 }
99 />
100 );
101}
102
103function FileHeader(props: {
104 readonly title: string;
105 readonly subtitle: string;
106 readonly iconColor: string;
107 readonly activeMode: string;
108 readonly fileInspectorSupported: boolean;
109 readonly onBack: () => void;
110 readonly onReturnToThread: () => void;
111 readonly actions: ReadonlyArray<{
112 readonly id: string;
113 readonly title: string;
114 readonly icon: string;
115 readonly inline: boolean;
116 readonly onPress: () => unknown;
117 }>;
118}) {
119 const { panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
120 const modes = props.actions.filter(({ inline }) => inline);
121 return (
122 <ScreenHeader
123 title={props.title}
124 subtitle={props.subtitle}
125 onBack={props.onBack}
126 hideBottomBorder
127 options={{ headerTintColor: props.iconColor, headerTitle: props.title }}
128 backInSplitView={
129 props.fileInspectorSupported
130 ? {
131 accessibilityLabel: "Return to chat",
132 icon: "chevron.left",
133 onPress: props.onReturnToThread,
134 }
135 : undefined
136 }
137 actions={
138 props.fileInspectorSupported
139 ? [
140 {
141 accessibilityLabel: panes.auxiliaryPaneVisible
142 ? "Hide file navigator"
143 : "Show file navigator",
144 icon: "sidebar.right",
145 selected: panes.auxiliaryPaneVisible,
146 onPress: toggleAuxiliaryPane,
147 },
148 ]
149 : undefined
150 }
151 menus={[
152 {
153 title: "File actions",
154 icon: "ellipsis",
155 separateBackground: false,
156 items: [
157 ...(modes.length > 0
158 ? [
159 {
160 id: "modes",
161 inline: true,
162 items: modes.map((action) => ({
163 ...action,
164 selected: action.id === props.activeMode,
165 })),
166 },
167 ]
168 : []),
169 ...props.actions.filter(({ inline }) => !inline),
170 ],
171 },
172 ]}
173 />
174 );
175}
176
177type FileViewMode = "preview" | "source";
178
179// A blank param (a hand-typed deep link) is treated as missing, since branded
180// IDs reject whitespace-only values.
181function firstRouteParam(value: string | string[] | undefined): string | null {
182 const first = Array.isArray(value) ? value[0] : value;
183 return first === undefined || first.trim().length === 0 ? null : first;
184}
185
186function normalizeRoutePath(value: string | string[] | undefined): string | null {
187 const path = Array.isArray(value) ? value.join("/") : value;
188 if (path === undefined || path.trim().length === 0) {
189 return null;
190 }
191 return path;
192}
193
194function normalizeRouteLine(value: string | null): number | null {
195 if (value === null) {
196 return null;
197 }
198 const parsed = Number(value);
199 return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
200}
201
202function defaultViewMode(path: string | null): FileViewMode {
203 return path !== null &&
204 (isWorkspaceBrowserPreviewPath(path) ||
205 isWorkspaceImagePreviewPath(path) ||
206 isVideoPreviewFile(path) ||
207 isAudioPreviewFile(path))
208 ? "preview"
209 : "source";
210}
211
212function FileContent(props: {
213 readonly activeMode: FileViewMode;
214 readonly cwd: string;
215 readonly environmentId: EnvironmentId;
216 readonly previewUri: string | null;
217 readonly previewFailure: AssetUrlFailureReason | null;
218 readonly onRetryPreview: () => void;
219 readonly videoSource: MediaVideoPreviewSource | null;
220 readonly mediaSource?: MediaActionsSource;
221 readonly resolveVideoUri: () => Promise<string | null>;
222 readonly fileContents: string | null;
223 readonly fileError: string | null;
224 readonly relativePath: string;
225 readonly threadId: ThreadId | null;
226 readonly initialLine: number | null;
227 readonly truncated: boolean;
228 readonly onRefresh?: () => Promise<void> | void;
229}) {
230 // Reopening a mutable host file must not reuse a poster from an earlier visit.
231 const thumbnailInstanceId = useId();
232 const isMarkdown = isMarkdownPreviewFile(props.relativePath);
233 const isBrowserFile = isWorkspaceBrowserPreviewPath(props.relativePath);
234 const isImageFile = isWorkspaceImagePreviewPath(props.relativePath);
235 const isVideoFile = isVideoPreviewFile(props.relativePath);
236 const isAudioFile = isAudioPreviewFile(props.relativePath);
237 // Only the surfaces that wait on a signed asset URL can be blocked by one.
238 const needsAssetUrl =
239 isVideoFile ||
240 isAudioFile ||
241 (props.activeMode === "preview" && (isImageFile || isBrowserFile));
242
243 if (needsAssetUrl && props.previewFailure !== null) {
244 return (
245 <WorkspaceFilePreviewError
246 environmentId={props.environmentId}
247 reason={props.previewFailure}
248 onRetry={props.onRetryPreview}
249 />
250 );
251 }
252
253 if (isVideoFile) {
254 return (
255 <WorkspaceFileVideoPreview
256 name={basename(props.relativePath)}
257 thumbnailKey={`workspace-video:${thumbnailInstanceId}`}
258 uri={props.previewUri}
259 source={props.videoSource}
260 resolvePlaybackUri={props.resolveVideoUri}
261 />
262 );
263 }
264
265 if (isAudioFile) {
266 return props.previewUri === null ? (
267 <FilePreviewLoading message="Loading file..." />
268 ) : (
269 <AudioFilePreview uri={props.previewUri} onRetry={props.onRetryPreview} />
270 );
271 }
272
273 if (props.activeMode === "preview" && isImageFile) {
274 if (isSvgImagePreviewFile(props.relativePath)) {
275 return <WorkspaceFileWebPreview uri={props.previewUri} />;
276 }
277 return (
278 <WorkspaceFileImagePreview
279 accessibilityLabel={basename(props.relativePath)}
280 uri={props.previewUri}
281 actionsSource={props.mediaSource}
282 />
283 );
284 }
285
286 if (props.activeMode === "preview" && isBrowserFile) {
287 return <WorkspaceFileWebPreview uri={props.previewUri} />;
288 }
289
290 if (props.fileError && props.fileContents === null) {
291 return (
292 <View className="flex-1 items-center justify-center bg-sheet px-6">
293 <EmptyState title="File unavailable" detail={props.fileError} />
294 </View>
295 );
296 }
297
298 if (props.fileContents === null) {
299 return <FilePreviewLoading message="Loading file..." />;
300 }
301
302 return (
303 <View className="flex-1 bg-sheet">
304 {props.truncated ? (
305 <FilePreviewNotice title="Partial file">
306 Preview limited to the first 1 MB of a truncated file.
307 </FilePreviewNotice>
308 ) : null}
309 {props.activeMode === "preview" && isMarkdown ? (
310 <FileMarkdownPreview
311 cwd={props.cwd}
312 environmentId={props.environmentId}
313 markdown={props.fileContents}
314 relativePath={props.relativePath}
315 threadId={props.threadId}
316 onRefresh={props.onRefresh}
317 />
318 ) : (
319 <SourceFileSurface
320 contents={props.fileContents}
321 path={props.relativePath}
322 initialLine={props.initialLine}
323 onRefresh={props.onRefresh}
324 />
325 )}
326 </View>
327 );
328}
329
330type ThreadFilesRouteScreenProps = StaticScreenProps<{
331 readonly environmentId: string;
332 readonly threadId: string;
333}>;
334
335type ThreadFileRouteScreenProps = StaticScreenProps<{
336 readonly environmentId: string;
337 /** Absent for a project draft, which has no thread yet. */
338 readonly threadId?: string;
339 readonly path: string[];
340 readonly line?: string;
341 /** Supplied when there is no thread to resolve the workspace from. */
342 readonly cwd?: string;
343 readonly projectName?: string;
344}>;
345
346function useThreadFilesWorkspace(params: {
347 readonly environmentId?: string | string[];
348 readonly threadId?: string | string[];
349 readonly cwd?: string | string[];
350 readonly projectName?: string | string[];
351}) {
352 const routeEnvironmentId = firstRouteParam(params.environmentId);
353 const routeThreadId = firstRouteParam(params.threadId);
354 // A project draft has no thread to resolve a workspace from, so it names one itself.
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 <MaterialScreenContent insetHorizontal={layout.usesSplitView}>
561 <FileTreeBrowser
562 key={JSON.stringify([environmentId, cwd])}
563 entries={entriesQuery.entries}
564 loadedDirectories={entriesQuery.loadedDirectories}
565 loadingDirectories={entriesQuery.loadingDirectories}
566 onLoadDirectory={entriesQuery.loadDirectory}
567 error={entriesQuery.error}
568 isPending={entriesQuery.isPending}
569 isRefreshing={entriesQuery.isRefreshing}
570 searchQuery={searchQuery}
571 searchTruncated={entriesQuery.searchTruncated}
572 selectedPath={null}
573 onPreviewFile={handlePreviewFile}
574 onRefresh={entriesQuery.refresh}
575 onSelectFile={handleSelectFile}
576 />
577 <FilesToolbarBottomFade />
578 </MaterialScreenContent>
579 </>
580 );
581
582 return Platform.OS === "android" ? <View className="flex-1 bg-header">{content}</View> : content;
583}
584
585export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
586 useAdaptiveWorkspacePaneRole("inspector");
587 const navigation = useNavigation();
588 const { fileInspector } = useAdaptiveWorkspaceLayout();
589 const { appearance, setCodeWordBreak } = useAppearancePreferences();
590 const iconColor = useUniwindTheme()["--color-icon"];
591 const params = props.route.params;
592 const relativePath = normalizeRoutePath(params.path);
593 const targetLine = normalizeRouteLine(firstRouteParam(params.line));
594 const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
595 props.route.params,
596 );
597 const [modeOverride, setModeOverride] = useState<{
598 readonly path: string;
599 readonly mode: FileViewMode;
600 } | null>(null);
601 const [previewRevision, setPreviewRevision] = useState(0);
602 const previewKey = JSON.stringify([environmentId, cwd, relativePath, previewRevision]);
603 const [fullScreenPreview, setFullScreenPreview] = useState<FilePreviewSource | null>(null);
604 const isVideoFile = relativePath !== null && isVideoPreviewFile(relativePath);
605 const isAudioFile = relativePath !== null && !isVideoFile && isAudioPreviewFile(relativePath);
606 const isBrowserFile =
607 relativePath !== null && !isVideoFile && isWorkspaceBrowserPreviewPath(relativePath);
608 const isImageFile =
609 relativePath !== null && !isVideoFile && isWorkspaceImagePreviewPath(relativePath);
610 const canPreview =
611 relativePath !== null &&
612 (isMarkdownPreviewFile(relativePath) ||
613 isBrowserFile ||
614 isImageFile ||
615 isVideoFile ||
616 isAudioFile);
617 const activeMode =
618 relativePath !== null && modeOverride?.path === relativePath
619 ? modeOverride.mode
620 : defaultViewMode(relativePath);
621 const resolvedActiveMode =
622 isVideoFile || isAudioFile ? "preview" : canPreview ? activeMode : "source";
623 const assetPreviewPath =
624 isBrowserFile || isImageFile || isVideoFile || isAudioFile ? relativePath : null;
625 const assetPreview = useWorkspaceFileAssetUrlState({
626 cwd,
627 environmentId,
628 relativePath: assetPreviewPath,
629 threadId,
630 // A project draft names its workspace root explicitly: there is no thread to resolve one.
631 draftCwd: threadId === null ? cwd : null,
632 });
633 const assetPreviewUri = assetPreview._tag === "Success" ? assetPreview.url : null;
634 const mediaSource = useMemo<MediaActionsSource | undefined>(
635 () =>
636 environmentId !== null &&
637 relativePath !== null &&
638 assetPreview.resource !== null &&
639 "path" in assetPreview.resource &&
640 typeof assetPreview.resource.path === "string" &&
641 (isImageFile || isVideoFile)
642 ? {
643 reference: mediaFileReference(assetPreview.resource.path, cwd),
644 name: basename(relativePath),
645 mimeType:
646 mediaMimeTypeFromExtension(relativePath.slice(relativePath.lastIndexOf("."))) ??
647 "application/octet-stream",
648 environmentId,
649 ...(threadId === null ? {} : { threadId }),
650 resource: assetPreview.resource,
651 }
652 : undefined,
653 [assetPreview.resource, cwd, environmentId, isImageFile, isVideoFile, relativePath, threadId],
654 );
655 const mediaActions = useMediaActions(mediaSource);
656 const videoSource = useMemo<MediaVideoPreviewSource | null>(
657 () =>
658 environmentId !== null &&
659 relativePath !== null &&
660 (assetPreview.resource?._tag === "media-file" ||
661 assetPreview.resource?._tag === "draft-workspace-file")
662 ? {
663 type: "media",
664 environmentId,
665 resource: assetPreview.resource,
666 name: basename(relativePath),
667 mimeType: videoMimeType({ name: relativePath, mimeType: "" }) ?? "video/mp4",
668 actionsSource: mediaSource,
669 }
670 : null,
671 [assetPreview.resource, environmentId, relativePath, mediaSource],
672 );
673 const previewUri =
674 assetPreviewUri === null || previewRevision === 0
675 ? assetPreviewUri
676 : `${assetPreviewUri}${assetPreviewUri.includes("?") ? "&" : "?"}revision=${previewRevision}`;
677 // Remounting the preview after a re-mint is what makes a failed asset URL retryable.
678 const handleRetryPreview = () => {
679 void assetPreview.refresh().finally(() => setPreviewRevision((current) => current + 1));
680 };
681 const needsFileContents =
682 relativePath !== null &&
683 !isVideoFile &&
684 !isAudioFile &&
685 (resolvedActiveMode === "source" || isMarkdownPreviewFile(relativePath));
686 const fileAccessSession = useEnvironmentQuery(
687 environmentId !== null ? environmentSession.sessionStateAtom(environmentId) : null,
688 );
689 const fileEnvironment = useEnvironmentPresentation(environmentId);
690 const fileAccess = resolveFilesystemReadAccess({
691 isCatalogReady: fileEnvironment.isReady,
692 connection: fileEnvironment.presentation?.connection ?? null,
693 session: fileAccessSession.data,
694 sessionError: fileAccessSession.error,
695 });
696 const { canReadFiles } = fileAccess;
697 const fileQuery = useEnvironmentQuery(
698 canReadFiles &&
699 environmentId !== null &&
700 cwd !== null &&
701 relativePath !== null &&
702 needsFileContents
703 ? projectEnvironment.readFile({
704 environmentId,
705 input: { cwd, relativePath },
706 })
707 : null,
708 );
709 const fileData = fileQuery.data as ProjectReadFileResult | null;
710
711 const handleSelectFile = useCallback(
712 (path: string) => {
713 const segments = path.split("/").filter(Boolean);
714 // A draft has no thread. `ThreadFile` would stringify null and then wait forever for a
715 // thread to resolve, so a draft stays on its own route and carries its workspace along.
716 if (threadId === null) {
717 navigation.dispatch(
718 StackActions.push("NewTaskFile", {
719 environmentId: String(environmentId),
720 ...(cwd === null ? {} : { cwd }),
721 projectName,
722 path: segments,
723 }),
724 );
725 return;
726 }
727 navigation.navigate("ThreadFile", {
728 environmentId: String(environmentId),
729 threadId: String(threadId),
730 path: segments,
731 });
732 },
733 [cwd, environmentId, navigation, projectName, threadId],
734 );
735 const renderInspector = useCallback(
736 (headerInset: number) =>
737 fileInspector.supported && environmentId !== null && cwd !== null ? (
738 <ThreadFileNavigatorPane
739 cwd={cwd}
740 environmentId={environmentId}
741 headerInset={headerInset}
742 projectName={projectName}
743 selectedPath={relativePath}
744 onSelectFile={handleSelectFile}
745 />
746 ) : undefined,
747 [cwd, environmentId, fileInspector.supported, handleSelectFile, projectName, relativePath],
748 );
749 // The workspace inspector column spans the full window height. On iOS the
750 // pane brings its own nested native header; elsewhere it pads itself below
751 // the top inset.
752 const safeAreaInsets = useSafeAreaInsets();
753 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
754 // Hand the file navigator to the workspace so it renders beside the
755 // navigator, outside this screen's native header.
756 const renderWorkspaceInspector = useCallback(
757 () => (
758 <ThreadInspectorContentStack
759 mode="files"
760 resetKeys={[threadId, cwd]}
761 renderFiles={() => renderInspector(inspectorHeaderInset)}
762 />
763 ),
764 [cwd, inspectorHeaderInset, renderInspector, threadId],
765 );
766 useRegisterWorkspaceInspector(fileInspector.supported ? renderWorkspaceInspector : undefined);
767
768 const fileMenuActions = useMemo(() => {
769 if (relativePath === null) return [];
770 const canToggleMode = canPreview && !isImageFile && !isVideoFile && !isAudioFile;
771 return [
772 canToggleMode
773 ? ({
774 id: "preview",
775 title: "Preview",
776 icon: "eye",
777 inline: true,
778 onPress: () => setModeOverride({ path: relativePath, mode: "preview" }),
779 } as const)
780 : null,
781 canToggleMode
782 ? ({
783 id: "source",
784 title: "Source",
785 icon: "doc.text",
786 inline: true,
787 onPress: () => setModeOverride({ path: relativePath, mode: "source" }),
788 } as const)
789 : null,
790 // Only the source body wraps; a rendered preview lays itself out.
791 resolvedActiveMode === "source"
792 ? ({
793 id: "word-wrap",
794 title: appearance.codeWordBreak ? "Disable word wrap" : "Enable word wrap",
795 icon: "text.alignleft",
796 inline: false,
797 onPress: () => setCodeWordBreak(!appearance.codeWordBreak),
798 } as const)
799 : null,
800 ...(mediaSource
801 ? mediaActions.actions
802 .filter(({ id }) => id !== "open-file")
803 .map((action) => ({
804 id: action.id,
805 title: action.title,
806 icon:
807 action.id === "save" ? ("square.and.arrow.up" as const) : ("doc.on.doc" as const),
808 inline: false,
809 onPress: action.run,
810 }))
811 : [
812 {
813 id: "copy-path",
814 title: "Copy path",
815 icon: "doc.on.doc",
816 inline: false,
817 onPress: () => copyTextWithHaptic(relativePath),
818 } as const,
819 ]),
820 // Selecting a long file by hand is painful on a phone, so copying the whole thing is
821 // the action most readers actually want. The attachment screen already offers it.
822 fileData?.contents != null
823 ? ({
824 id: "copy-contents",
825 title: fileData.truncated ? "Copy preview" : "Copy contents",
826 icon: "doc.on.doc",
827 inline: false,
828 onPress: () => copyTextWithHaptic(fileData.contents),
829 } as const)
830 : null,
831 isPdfFile({ name: relativePath }) && previewUri !== null
832 ? ({
833 id: "open-pdf",
834 title: "Open PDF",
835 icon: "arrow.up.left.and.arrow.down.right",
836 inline: false,
837 onPress: () =>
838 setFullScreenPreview({
839 kind: "pdf",
840 uri: previewUri,
841 name: basename(relativePath),
842 }),
843 } as const)
844 : null,
845 isBrowserFile && typeof assetPreviewUri === "string"
846 ? ({
847 id: "open-browser",
848 title: Platform.OS === "ios" ? "Open in Safari" : "Open in browser",
849 icon: "safari",
850 inline: false,
851 onPress: () => tryOpenExternalUrl(assetPreviewUri, "file-preview"),
852 } as const)
853 : null,
854 resolvedActiveMode === "preview" &&
855 (isBrowserFile || isImageFile || isVideoFile || isAudioFile)
856 ? ({
857 id: "refresh",
858 title: "Refresh",
859 icon: "arrow.clockwise",
860 inline: false,
861 onPress: async () => {
862 if (isVideoFile || isAudioFile) await assetPreview.refresh();
863 setPreviewRevision((current) => current + 1);
864 },
865 } as const)
866 : null,
867 ].filter((action) => action !== null);
868 }, [
869 appearance.codeWordBreak,
870 setCodeWordBreak,
871 assetPreviewUri,
872 assetPreview.refresh,
873 previewUri,
874 canPreview,
875 isAudioFile,
876 isBrowserFile,
877 isImageFile,
878 isVideoFile,
879 relativePath,
880 resolvedActiveMode,
881 mediaSource,
882 mediaActions.actions,
883 fileData?.contents,
884 fileData?.truncated,
885 ]);
886
887 const handleReturnToThread = useCallback(() => {
888 if (environmentId !== null && threadId !== null) {
889 navigation.dispatch(
890 StackActions.replace("Thread", {
891 environmentId: String(environmentId),
892 threadId: String(threadId),
893 }),
894 );
895 }
896 }, [environmentId, navigation, threadId]);
897 const handleBack = useCallback(() => {
898 if (navigation.canGoBack()) {
899 navigation.goBack();
900 return;
901 }
902 handleReturnToThread();
903 }, [handleReturnToThread, navigation]);
904
905 // A file opened from a project draft has no thread, and needs none: the thread only supplies
906 // the workspace to read from and the target to navigate back to, both of which a draft names
907 // for itself. Wait only for what this file actually cannot render without.
908 if (environmentId === null || (threadId !== null && selectedThread === null)) {
909 return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
910 }
911
912 if (!canReadFiles) {
913 if (fileAccess.isPending) {
914 return <LoadingScreen message="Checking file access..." messagePlacement="above-spinner" />;
915 }
916 return (
917 <FilesUnavailable detail={fileAccess.error ?? "This connection cannot read host files."} />
918 );
919 }
920 if (cwd === null) {
921 return <FilesUnavailable />;
922 }
923
924 if (relativePath === null) {
925 return (
926 <View className="flex-1 items-center justify-center bg-sheet px-6">
927 <NativeStackScreenOptions options={{ title: "Files" }} />
928 <EmptyState title="File unavailable" detail="This file path is invalid." />
929 </View>
930 );
931 }
932
933 const headerSubtitle = fileHeaderSubtitle(projectName, relativePath);
934
935 return (
936 <View className="flex-1 bg-sheet">
937 <FileHeader
938 title={basename(relativePath)}
939 subtitle={headerSubtitle}
940 iconColor={iconColor}
941 activeMode={resolvedActiveMode}
942 fileInspectorSupported={fileInspector.supported}
943 onBack={handleBack}
944 onReturnToThread={handleReturnToThread}
945 actions={fileMenuActions}
946 />
947 <MaterialScreenContent>
948 <FileContent
949 key={previewKey}
950 activeMode={resolvedActiveMode}
951 cwd={cwd}
952 environmentId={environmentId}
953 previewUri={previewUri}
954 previewFailure={assetPreview._tag === "Failure" ? assetPreview.reason : null}
955 onRetryPreview={handleRetryPreview}
956 videoSource={videoSource}
957 mediaSource={mediaSource}
958 resolveVideoUri={assetPreview.refresh}
959 fileContents={fileData?.contents ?? null}
960 fileError={fileQuery.error}
961 initialLine={targetLine}
962 relativePath={relativePath}
963 threadId={threadId}
964 truncated={fileData?.truncated ?? false}
965 onRefresh={() => fileQuery.refresh()}
966 />
967 </MaterialScreenContent>
968 <FilePreviewModal
969 source={fullScreenPreview}
970 onRequestClose={() => setFullScreenPreview(null)}
971 />
972 </View>
973 );
974}