The best way to control Claude Code, Codex and more from any computer or phone

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