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

ThreadFilesRouteScreen.tsx

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