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

ThreadFilesRouteScreen.tsx

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