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