Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadFilesRouteScreen.tsx

1,124 lines38.7 KB

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