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

FilePreviewPanel.tsx

1,483 lines54.5 KB

1import { Spinner } from "~/components/ui/spinner";
2import {
3 AuthPreviewOperateScope,
4 type EditorId,
5 type EnvironmentId,
6 type ResolvedKeybindingsConfig,
7 type ScopedThreadRef,
8} from "@t3tools/contracts";
9import { filePreviewDelimiter } from "@t3tools/shared/delimitedPreview";
10import { AuthFilesystemWriteScope } from "@t3tools/contracts";
11import {
12 isWorkspaceAudioPreviewPath,
13 isWorkspaceImagePreviewPath,
14 isWorkspaceVideoPreviewPath,
15} from "@t3tools/shared/filePreview";
16import { useAtomValue } from "@effect/atom-react";
17import {
18 DEFAULT_TOKENIZE_MAX_LENGTH,
19 VirtualizedFile,
20 getFiletypeFromFileName,
21 type File as FileInstance,
22 type FileContents,
23 type PostRenderPhase,
24 type SelectedLineRange,
25} from "@pierre/diffs";
26import {
27 Editor,
28 type EditorChangeEvent,
29 type EditorFactory,
30 type EditorOptions,
31} from "@pierre/diffs/edit";
32import type { WorkerPoolManager } from "@pierre/diffs/worker";
33import { EditProvider, File, Virtualizer, useWorkerPool } from "@pierre/diffs/react";
34import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";
35import { useFilesystemReadAccess } from "~/state/filesystem";
36import {
37 isAtomCommandInterrupted,
38 squashAtomCommandFailure,
39} from "@t3tools/client-runtime/state/runtime";
40import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
41import { FolderTree, Globe2, WrapTextIcon } from "lucide-react";
42import { Code2, Eye, Table2 } from "lucide";
43import * as Schema from "effect/Schema";
44import { useEffect, useRef, useState } from "react";
45​
46import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview";
47import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
48import { OpenInPicker } from "~/components/chat/OpenInPicker";
49import { MediaVideoPlayer } from "~/components/media/MediaVideoPlayer";
50import { MediaActions, type MediaActionSource } from "~/components/media/MediaActions";
51import { MorphIcon } from "~/components/MorphIcon";
52import { useRemoteOpenState } from "~/remoteOpen";
53import { useClientSettings, updateClientSettings } from "~/hooks/useSettings";
54import { useTheme } from "~/hooks/useTheme";
55import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "~/hooks/useLocalStorage";
56import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";
57import { resolveDiffThemeName } from "~/lib/diffRendering";
58import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";
59import { cn } from "~/lib/utils";
60import type { ChatFileAttachment } from "~/types";
61import { isHostPath } from "@t3tools/shared/path";
62import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
63import { ScrollArea } from "~/components/ui/scroll-area";
64import { stackedThreadToast, toastManager } from "~/components/ui/toast";
65import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
66import { buildFileReviewComment } from "~/reviewCommentContext";
67import { assetEnvironment } from "~/state/assets";
68import { usePreviewAvailable } from "~/browser/previewRuntime";
69import { useEnvironmentHttpBaseUrl, usePrimaryEnvironmentId } from "~/state/environments";
70import { previewEnvironment } from "~/state/preview";
71import { serverEnvironment } from "~/state/server";
72import { useEnvironmentScope } from "~/state/session";
73import { useAtomCommand } from "~/state/use-atom-command";
74import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
75​
76import { AttachmentFilePreview } from "./AttachmentFilePreview";
77import { AudioPreview } from "./AudioPreview";
78import { BrowserDocumentFrame, isPdfPreviewFile } from "./BrowserDocumentFrame";
79import { DelimitedTablePreview } from "./DelimitedTablePreview";
80import FileBrowserPanel from "./FileBrowserPanel";
81import { FileBreadcrumbs } from "./FileBreadcrumbs";
82import { breadcrumbPathOf, retainedBreadcrumbTrail, trailChildOf } from "./filePath";
83import { FileMarkdownPreview } from "./FileMarkdownPreview";
84import {
85 type FileCommentAnnotationEntry,
86 type FileCommentAnnotationGroup,
87 type FileCommentLineAnnotation,
88 formatFileCommentRange,
89 nextFileCommentId,
90 normalizeFileCommentRange,
91 remapFileCommentAnnotations,
92} from "./fileCommentAnnotations";
93import { installFileEditorDismissal } from "./fileEditorDismissal";
94import {
95 FILE_LINK_REVEAL_ATTRIBUTE,
96 FILE_LINK_REVEAL_UNSAFE_CSS,
97 FILE_SURFACE_SUBHEADER_CLASS,
98 FileSurfaceAction,
99 FileSurfaceFailure,
100 FileSurfaceLoading,
101} from "./fileSurfaceChrome";
102import SourceFilePreview from "./ReadOnlySourcePreview";
103import { resolveCenteredFileLineScrollTop } from "./fileLineReveal";
104import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation";
105import { projectFileCacheKey } from "./fileContentRevision";
106import {
107 filePreviewReadErrorMessage,
108 isMarkdownPreviewFile,
109 resolveFilePreviewPath,
110 setMarkdownTaskChecked,
111 shouldShowFileExplorer,
112 workspaceAssetResource,
113} from "./filePreviewMode";
114import { useFileSaveCoordinator } from "./useFileSaveCoordinator";
115import {
116 getOptimisticProjectFileQueryData,
117 getProjectFileContents,
118 setProjectFileQueryData,
119 useProjectFileQuery,
120} from "./projectFilesQueryState";
121​
122interface FilePreviewPanelProps {
123 environmentId: EnvironmentId;
124 cwd: string;
125 projectName: string;
126 relativePath: string | null;
127 attachment?: ChatFileAttachment;
128 threadRef: ScopedThreadRef;
129 composerDraftTarget: ScopedThreadRef | DraftId;
130 keybindings: ResolvedKeybindingsConfig;
131 availableEditors: ReadonlyArray<EditorId>;
132 openInShortcutEnabled: boolean;
133 revealLine: number | null;
134 revealRequestId: number;
135 onOpenFile: (relativePath: string) => void;
136 onNavigateFolder: (relativePath: string, folderTrail: string, keepSource: boolean) => void;
137 /** Retained descendant breadcrumb path after navigating up; see navigateFolder. */
138 folderTrail: string | undefined;
139 onPendingChange: (relativePath: string, pending: boolean) => void;
140 selectedFilePending: boolean;
141 workspaceMutationId: string | null;
143​
144const FILE_EXPLORER_STORAGE_KEY = "t3code.fileExplorerOpen";
145const RENDER_MARKDOWN_STORAGE_KEY = "t3code.renderMarkdown";
146const RENDER_BROWSER_FILE_STORAGE_KEY = "t3code.renderBrowserFile";
147const RENDER_TABLE_STORAGE_KEY = "t3code.renderTable";
148type FilePostRender = <LAnnotation>(
149 fileContainer: HTMLElement,
150 instance: FileInstance<LAnnotation, undefined>,
151 phase: PostRenderPhase,
152) => void;
153​
154function WorkspaceImagePreview(props: {
155 readonly environmentId: EnvironmentId;
156 readonly threadRef: ScopedThreadRef;
157 readonly draft: boolean;
158 readonly absolutePath: string;
159 readonly workspaceRoot: string;
160 readonly alt: string;
161 readonly workspaceMutationId: string | null;
162}) {
163 const resource = workspaceAssetResource({
164 kind: "workspace-file",
165 threadRef: props.threadRef,
166 draft: props.draft,
167 workspaceRoot: props.workspaceRoot,
168 absolutePath: props.absolutePath,
169 });
170 const assetUrl = useAssetUrlState(props.environmentId, resource);
171 const [failedUrl, setFailedUrl] = useState<string | null>(null);
172 const revisionSuffix =
173 props.workspaceMutationId === null
174 ? ""
175 : `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}workspace-revision=${encodeURIComponent(props.workspaceMutationId)}`;
176 const imageUrl = assetUrl._tag === "Success" ? `${assetUrl.url}${revisionSuffix}` : null;
177 const actionsSource: MediaActionSource = {
178 kind: "image",
179 name: props.alt,
180 src: imageUrl,
181 reference: mediaFileReference(props.absolutePath, props.workspaceRoot),
182 asset: { environmentId: props.environmentId, resource },
183 };
184​
185 if (assetUrl._tag === "Failure" || (imageUrl !== null && failedUrl === imageUrl)) {
186 return (
187 <MediaActions source={actionsSource}>
188 <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
189 Unable to load workspace image.
190 </div>
191 </MediaActions>
192 );
193 }
194​
195 return assetUrl._tag === "Success" && imageUrl !== null ? (
196 // oxlint-disable-next-line t3code/require-centered-scroll-gutter -- The image is capped at max-h-full max-w-full, so this never scrolls.
197 <div className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-4">
198 <MediaActions source={actionsSource}>
199 <img
200 className="max-h-full max-w-full object-contain"
201 src={imageUrl}
202 alt={props.alt}
203 onError={() => setFailedUrl(imageUrl)}
204 />
205 </MediaActions>
206 </div>
207 ) : (
208 <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
209 <Spinner size="lg" />
210 </div>
211 );
213​
214function WorkspaceBrowserPreview(props: {
215 readonly environmentId: EnvironmentId;
216 readonly threadRef: ScopedThreadRef;
217 readonly draft: boolean;
218 readonly absolutePath: string;
219 readonly workspaceRoot: string;
220 readonly title: string;
221 readonly workspaceMutationId: string | null;
222}) {
223 const resource = workspaceAssetResource({
224 kind: "workspace-file",
225 threadRef: props.threadRef,
226 draft: props.draft,
227 workspaceRoot: props.workspaceRoot,
228 absolutePath: props.absolutePath,
229 });
230 const assetUrl = useAssetUrlState(props.environmentId, resource);
231 const revisionSuffix =
232 props.workspaceMutationId === null
233 ? ""
234 : `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}workspace-revision=${encodeURIComponent(props.workspaceMutationId)}`;
235​
236 if (assetUrl._tag === "Failure") {
237 return (
238 <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
239 Unable to load file preview.
240 </div>
241 );
242 }
243 if (assetUrl._tag !== "Success") {
244 return (
245 <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
246 <Spinner size="lg" />
247 </div>
248 );
249 }
250 return (
251 <BrowserDocumentFrame
252 src={`${assetUrl.url}${revisionSuffix}`}
253 documentKey={`${props.environmentId}:${resource._tag}:${props.threadRef.threadId}:${props.absolutePath}:${props.workspaceMutationId}`}
254 title={props.title}
255 pdf={isPdfPreviewFile(props.absolutePath)}
256 />
257 );
259​
260function WorkspaceVideoPreview(props: {
261 readonly environmentId: EnvironmentId;
262 readonly threadRef: ScopedThreadRef;
263 readonly draft: boolean;
264 readonly absolutePath: string;
265 readonly workspaceRoot: string;
266 readonly name: string;
267 readonly workspaceMutationId: string | null;
268}) {
269 const resource = workspaceAssetResource({
270 kind: "media-file",
271 threadRef: props.threadRef,
272 draft: props.draft,
273 workspaceRoot: props.workspaceRoot,
274 absolutePath: props.absolutePath,
275 });
276 const assetUrl = useAssetUrlState(props.environmentId, resource);
277 const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
278 useWorkspaceMutationRefresh({
279 mutationId: props.workspaceMutationId,
280 resourceKey: JSON.stringify([props.environmentId, resource]),
281 refresh: () => {
282 void refreshAssetUrl().catch(() => undefined);
283 },
284 });
285 // Servers that report the file's revision let an unchanged file stay loaded; older ones
286 // only offer the workspace mutation, which changes after every command. The revision also
287 // goes in the URL, since two mints in the same millisecond sign identical URLs.
288 const fileRevision = assetUrl._tag === "Success" ? assetUrl.fileRevision : undefined;
289 const revision = fileRevision ?? props.workspaceMutationId;
290 const revisionSuffix =
291 revision === null
292 ? ""
293 : `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}${fileRevision !== undefined ? "file" : "workspace"}-revision=${encodeURIComponent(revision)}`;
294 const latestUrl = assetUrl._tag === "Success" ? `${assetUrl.url}${revisionSuffix}` : null;
295​
296 return (
297 <div className="flex min-h-0 flex-1 items-center justify-center overflow-hidden p-4">
298 <MediaVideoPlayer
299 src={latestUrl}
300 sourceFailed={assetUrl._tag === "Failure"}
301 label={props.name}
302 revision={revision}
303 preload="metadata"
304 className="flex h-full min-h-0 w-full max-w-5xl items-center justify-center"
305 onRetry={refreshAssetUrl}
306 actionsSource={{
307 kind: "video",
308 name: props.name,
309 src: latestUrl,
310 reference: mediaFileReference(props.absolutePath, props.workspaceRoot),
311 asset: { environmentId: props.environmentId, resource },
312 }}
313 />
314 </div>
315 );
317​
318function WorkspaceAudioPreview(props: {
319 readonly environmentId: EnvironmentId;
320 readonly threadRef: ScopedThreadRef;
321 readonly draft: boolean;
322 readonly absolutePath: string;
323 readonly workspaceRoot: string;
324 readonly name: string;
325 readonly workspaceMutationId: string | null;
326}) {
327 const resource = workspaceAssetResource({
328 kind: "media-file",
329 threadRef: props.threadRef,
330 draft: props.draft,
331 workspaceRoot: props.workspaceRoot,
332 absolutePath: props.absolutePath,
333 });
334 const assetUrl = useAssetUrlState(props.environmentId, resource);
335 const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
336 const [failedUrl, setFailedUrl] = useState<string | null>(null);
337 useWorkspaceMutationRefresh({
338 mutationId: props.workspaceMutationId,
339 resourceKey: JSON.stringify([props.environmentId, resource]),
340 refresh: () => {
341 void refreshAssetUrl().catch(() => undefined);
342 },
343 });
344 const fileRevision = assetUrl._tag === "Success" ? assetUrl.fileRevision : undefined;
345 const revision = fileRevision ?? props.workspaceMutationId;
346 const revisionSuffix =
347 revision === null
348 ? ""
349 : `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}${fileRevision !== undefined ? "file" : "workspace"}-revision=${encodeURIComponent(revision)}`;
350 const url = assetUrl._tag === "Success" ? `${assetUrl.url}${revisionSuffix}` : null;
351 if (assetUrl._tag === "Failure" || (url !== null && failedUrl === url)) {
352 return (
353 <FileSurfaceFailure
354 message="Unable to load audio."
355 onRetry={() => {
356 setFailedUrl(null);
357 void refreshAssetUrl().catch(() => undefined);
358 }}
359 />
360 );
361 }
362 if (url === null) return <FileSurfaceLoading />;
363 return (
364 <AudioPreview
365 src={url}
366 name={props.name}
367 revision={revision}
368 onError={() => setFailedUrl(url)}
369 />
370 );
372​
373function clampFileLine(contents: string, requestedLine: number): number {
374 let lineCount = 1;
375 for (let index = 0; index < contents.length; index += 1) {
376 const character = contents.charCodeAt(index);
377 if (character === 10) {
378 lineCount += 1;
379 } else if (character === 13) {
380 lineCount += 1;
381 if (contents.charCodeAt(index + 1) === 10) index += 1;
382 }
383 }
384 return Math.min(Math.max(1, requestedLine), lineCount);
386​
387function updateFileLinkReveal(fileContainer: HTMLElement, line: number | null): void {
388 const root = fileContainer.shadowRoot ?? fileContainer;
389 for (const element of root.querySelectorAll<HTMLElement>(`[${FILE_LINK_REVEAL_ATTRIBUTE}]`)) {
390 element.removeAttribute(FILE_LINK_REVEAL_ATTRIBUTE);
391 }
392 if (line === null) return;
393​
394 root
395 .querySelector<HTMLElement>(`[data-line="${line}"]`)
396 ?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, "");
397 root
398 .querySelector<HTMLElement>(`[data-column-number="${line}"]`)
399 ?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, "");
401​
402const REVEAL_MAX_ATTEMPTS = 30;
403/** Hold the reveal target against late focus/restoration scroll resets. */
404const REVEAL_GUARD_FRAMES = 20;
405const REVEAL_GUARD_TOLERANCE_PX = 2;
406​
407interface FileRevealState {
408 frameId: number | null;
409 cancelGuard: (() => void) | null;
410 handledRequestId: number | null;
411 latestRequestId: number | null;
413​
414function useFileLineReveal(
415 relativePath: string | null,
416 revealLine: number | null,
417 revealRequestId: number,
418): FilePostRender {
419 const [revealStatesByPath] = useState(() => new Map<string, FileRevealState>());
420​
421 return (fileContainer, instance, phase) => {
422 if (relativePath === null) return;
423​
424 const existingState = revealStatesByPath.get(relativePath);
425 const state: FileRevealState = existingState ?? {
426 frameId: null,
427 cancelGuard: null,
428 handledRequestId: null,
429 latestRequestId: null,
430 };
431 if (!existingState) revealStatesByPath.set(relativePath, state);
432​
433 const cancelPendingReveal = () => {
434 if (state.frameId !== null) {
435 cancelAnimationFrame(state.frameId);
436 state.frameId = null;
437 }
438 state.cancelGuard?.();
439 };
440​
441 if (phase === "unmount") {
442 cancelPendingReveal();
443 return;
444 }
445​
446 const contents = instance.file?.contents;
447 const targetLine =
448 revealLine === null || contents === undefined ? null : clampFileLine(contents, revealLine);
449 updateFileLinkReveal(fileContainer, targetLine);
450​
451 if (!(instance instanceof VirtualizedFile)) return;
452​
453 if (state.latestRequestId !== revealRequestId) {
454 cancelPendingReveal();
455 state.latestRequestId = revealRequestId;
456 state.handledRequestId = null;
457 }
458​
459 if (revealLine === null) {
460 fileContainer.style.minHeight = "";
461 return;
462 }
463​
464 const scrollContainer = fileContainer.closest<HTMLElement>(".file-preview-virtualizer");
465 if (!scrollContainer) return;
466 fileContainer.style.minHeight = `${Math.ceil(
467 Math.max(instance.height, scrollContainer.clientHeight),
468 )}px`;
469​
470 if (state.handledRequestId === revealRequestId || state.frameId !== null) {
471 return;
472 }
473​
474 const resolveScrollTarget = (line: number): number | null => {
475 const linePosition = instance.getLinePosition(line);
476 if (!linePosition) return null;
477​
478 const scrollContainerRect = scrollContainer.getBoundingClientRect();
479 const fileTop =
480 scrollContainer.scrollTop +
481 fileContainer.getBoundingClientRect().top -
482 scrollContainerRect.top;
483 const root = fileContainer.shadowRoot ?? fileContainer;
484 const renderedLineElement = root.querySelector<HTMLElement>(`[data-line="${line}"]`);
485 const renderedLineRect = renderedLineElement?.getBoundingClientRect();
486​
487 return resolveCenteredFileLineScrollTop({
488 scrollTop: scrollContainer.scrollTop,
489 scrollHeight: scrollContainer.scrollHeight,
490 viewportTop: scrollContainerRect.top,
491 viewportHeight: scrollContainer.clientHeight,
492 fileTop,
493 estimatedLine: linePosition,
494 ...(renderedLineRect && renderedLineRect.height > 0
495 ? {
496 renderedLine: {
497 top: renderedLineRect.top,
498 height: renderedLineRect.height,
499 },
500 }
501 : {}),
502 });
503 };
504​
505 const guardScrollTarget = (line: number) => {
506 let framesLeft = REVEAL_GUARD_FRAMES;
507 let guardFrameId: number | null = null;
508 const cancelGuard = () => {
509 if (guardFrameId !== null) {
510 cancelAnimationFrame(guardFrameId);
511 guardFrameId = null;
512 }
513 scrollContainer.removeEventListener("wheel", cancelGuard);
514 scrollContainer.removeEventListener("touchstart", cancelGuard);
515 scrollContainer.removeEventListener("pointerdown", cancelGuard, true);
516 window.removeEventListener("keydown", cancelGuard, true);
517 if (state.cancelGuard === cancelGuard) state.cancelGuard = null;
518 };
519 scrollContainer.addEventListener("wheel", cancelGuard, { passive: true });
520 scrollContainer.addEventListener("touchstart", cancelGuard, { passive: true });
521 // Capture gutter pointer events before Pierre stops propagation so comments can cancel the reveal
522 // guard.
523 scrollContainer.addEventListener("pointerdown", cancelGuard, {
524 passive: true,
525 capture: true,
526 });
527 window.addEventListener("keydown", cancelGuard, true);
528 const holdTarget = () => {
529 guardFrameId = null;
530 framesLeft -= 1;
531 if (framesLeft <= 0 || !scrollContainer.isConnected) {
532 cancelGuard();
533 return;
534 }
535 const targetTop = resolveScrollTarget(line);
536 if (
537 targetTop !== null &&
538 Math.abs(scrollContainer.scrollTop - targetTop) > REVEAL_GUARD_TOLERANCE_PX
539 ) {
540 scrollContainer.scrollTop = targetTop;
541 }
542 guardFrameId = requestAnimationFrame(holdTarget);
543 };
544 guardFrameId = requestAnimationFrame(holdTarget);
545 state.cancelGuard = cancelGuard;
546 };
547​
548 const scheduleReveal = (attempt: number) => {
549 state.frameId = requestAnimationFrame(() => {
550 state.frameId = null;
551 if (state.latestRequestId !== revealRequestId || !fileContainer.isConnected) {
552 return;
553 }
554​
555 // Wait for contents and metrics; missing data would clamp fresh-mount reveals to line 1 and mark them
556 // handled.
557 const currentContents = instance.file?.contents;
558 const line =
559 currentContents === undefined ? null : clampFileLine(currentContents, revealLine);
560 const targetTop = line === null ? null : resolveScrollTarget(line);
561 if (line === null || targetTop === null) {
562 if (attempt < REVEAL_MAX_ATTEMPTS) scheduleReveal(attempt + 1);
563 return;
564 }
565 updateFileLinkReveal(fileContainer, line);
566​
567 scrollContainer.scrollTop = targetTop;
568 state.handledRequestId = revealRequestId;
569 guardScrollTarget(line);
570 });
571 };
572​
573 scheduleReveal(0);
574 };
576​
577const createFileEditor: EditorFactory<FileCommentAnnotationGroup, undefined> = (
578 editorType,
579 options,
580 editStateKey,
581) => new Editor(editorType, options, editStateKey);
582​
583function editableFileContents(
584 environmentId: EnvironmentId,
585 cwd: string,
586 relativePath: string,
587 contents: string,
588): FileContents {
589 return {
590 name: relativePath,
591 contents,
592 cacheKey: `editor:${environmentId}:${projectFileCacheKey(cwd, relativePath, contents)}`,
593 };
595​
596function needsWorkerHighlight(workerPool: WorkerPoolManager | undefined, file: FileContents) {
597 if (workerPool?.isWorkingPool() !== true) return false;
598 if ((file.lang ?? getFiletypeFromFileName(file.name)) === "text") return false;
599 let lines = 1;
600 for (
601 let index = file.contents.indexOf("\n");
602 index !== -1;
603 index = file.contents.indexOf("\n", index + 1)
604 ) {
605 lines += 1;
606 }
607 return lines <= DEFAULT_TOKENIZE_MAX_LENGTH;
609​
610/** Enable editing only after worker highlighting renders; active edit sessions highlight on the main
611 * thread. */
612function useEditableAfterHighlight(file: FileContents) {
613 const workerPool = useWorkerPool();
614 const [highlightedFile, setHighlightedFile] = useState<FileContents | null>(null);
615 const needsHighlight = needsWorkerHighlight(workerPool, file);
616 const ready = !needsHighlight || highlightedFile === file;
617​
618 useEffect(() => {
619 if (ready || workerPool === undefined) return;
620 workerPool.primeFileHighlightCache(file).catch(() => setHighlightedFile(file));
621 }, [file, ready, workerPool]);
622​
623 const onPostRender = (renderedFile: FileContents | undefined, phase: PostRenderPhase) => {
624 if (ready || phase === "unmount" || renderedFile?.cacheKey !== file.cacheKey) return;
625 // Cache results arrive just before instance rendering; seeing the cache during render means rows are
626 // highlighted.
627 if (workerPool?.getFileResultCache(file) !== undefined) setHighlightedFile(file);
628 };
629 return { ready, onPostRender };
631​
632interface EditableFileSurfaceProps {
633 environmentId: EnvironmentId;
634 cwd: string;
635 relativePath: string;
636 composerDraftTarget: ScopedThreadRef | DraftId;
637 contents: string;
638 resolvedTheme: "light" | "dark";
639 revealRequestId: number;
640 wordWrap: boolean;
641 onPostRender: FilePostRender;
642 onPendingChange: (relativePath: string, pending: boolean) => void;
644​
645interface FileSelectionOverride {
646 revealRequestId: number;
647 range: SelectedLineRange | null;
649​
650function EditableFileSurface({
651 environmentId,
652 cwd,
653 relativePath,
654 composerDraftTarget,
655 contents,
656 resolvedTheme,
657 revealRequestId,
658 wordWrap,
659 onPostRender,
660 onPendingChange,
661}: EditableFileSurfaceProps) {
662 const addReviewComment = useComposerDraftStore((store) => store.addReviewComment);
663 const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment);
664 const [lineAnnotations, setLineAnnotations] = useState<FileCommentLineAnnotation[]>([]);
665 const [selectionOverride, setSelectionOverride] = useState<FileSelectionOverride | null>(null);
666 const selectedRange =
667 selectionOverride?.revealRequestId === revealRequestId ? selectionOverride.range : null;
668 const setSelectedRange = (range: SelectedLineRange | null) => {
669 setSelectionOverride({ revealRequestId, range });
670 };
671 const surfaceRef = useRef<HTMLDivElement>(null);
672 const selectionFrameRef = useRef<number | null>(null);
673 const saveCoordinator = useFileSaveCoordinator({
674 environmentId,
675 cwd,
676 relativePath,
677 onPendingChange,
678 });
679 // Retain file identity for echoed editor changes; only external changes replace the editor's draft.
680 const [externalFile, setExternalFile] = useState(() =>
681 editableFileContents(environmentId, cwd, relativePath, contents),
682 );
683 const [editedContents, setEditedContents] = useState<string | null>(null);
684 if (contents !== (editedContents ?? externalFile.contents)) {
685 setExternalFile(editableFileContents(environmentId, cwd, relativePath, contents));
686 setEditedContents(null);
687 }
688 const { ready: editable, onPostRender: onEditablePostRender } =
689 useEditableAfterHighlight(externalFile);
690 const editorRef = useRef<Editor<"file", FileCommentAnnotationGroup, undefined> | null>(null);
691 const editorOptions: EditorOptions<"file", FileCommentAnnotationGroup, undefined> = {
692 onAttach: (editor) => {
693 editorRef.current = editor;
694 },
695 onComplete: () => {
696 editorRef.current = null;
697 },
698 };
699​
700 const handleEditChange = ({
701 file,
702 lineAnnotations: nextLineAnnotations,
703 }: EditorChangeEvent<"file", FileCommentAnnotationGroup, undefined>) => {
704 if (file.contents === getProjectFileContents(environmentId, cwd, relativePath)) return;
705 setEditedContents(file.contents);
706 setProjectFileQueryData(environmentId, cwd, relativePath, file.contents);
707 saveCoordinator.change(file.contents);
708 if (!nextLineAnnotations) return;
709 const remapped = remapFileCommentAnnotations(nextLineAnnotations);
710 // The editor hands back the array it was given until an edit moves an annotation.
711 setLineAnnotations((current) => (current === nextLineAnnotations ? current : remapped));
712 for (const annotation of remapped) {
713 for (const entry of annotation.metadata.entries) {
714 if (entry.kind !== "comment") continue;
715 addReviewComment(
716 composerDraftTarget,
717 buildFileReviewComment({
718 id: entry.id,
719 filePath: relativePath,
720 startLine: entry.startLine,
721 endLine: entry.endLine,
722 text: entry.text,
723 contents: file.contents,
724 }),
725 );
726 }
727 }
728 };
729​
730 const removeAnnotationEntry = (entryId: string) => {
731 setSelectedRange(null);
732 removeReviewComment(composerDraftTarget, entryId);
733 setLineAnnotations((current) => {
734 return current.flatMap((annotation) => {
735 const entries = annotation.metadata.entries.filter((entry) => entry.id !== entryId);
736 return entries.length > 0 ? [{ ...annotation, metadata: { entries } }] : [];
737 });
738 });
739 };
740​
741 const submitAnnotationEntry = (entryId: string, text: string) => {
742 setSelectedRange(null);
743 const entry = lineAnnotations
744 .flatMap((annotation) => annotation.metadata.entries)
745 .find((candidate) => candidate.id === entryId);
746 if (entry) {
747 addReviewComment(
748 composerDraftTarget,
749 buildFileReviewComment({
750 id: entry.id,
751 filePath: relativePath,
752 startLine: entry.startLine,
753 endLine: entry.endLine,
754 text,
755 contents,
756 }),
757 );
758 }
759 setLineAnnotations((current) =>
760 current.map((annotation) => ({
761 ...annotation,
762 metadata: {
763 entries: annotation.metadata.entries.map((annotationEntry) =>
764 annotationEntry.id === entryId
765 ? { ...annotationEntry, kind: "comment", text }
766 : annotationEntry,
767 ),
768 },
769 })),
770 );
771 };
772​
773 const beginComment = (range: SelectedLineRange) => {
774 editorRef.current?.setSelections([]);
775 editorRef.current?.blur();
776 const { startLine, endLine } = normalizeFileCommentRange(range);
777 const draftEntry: FileCommentAnnotationEntry = {
778 id: nextFileCommentId(),
779 kind: "draft",
780 startLine,
781 endLine,
782 text: "",
783 };
784 setLineAnnotations((current) => {
785 const withoutDraft = current.flatMap((annotation) => {
786 const entries = annotation.metadata.entries.filter((entry) => entry.kind !== "draft");
787 return entries.length > 0 ? [{ ...annotation, metadata: { entries } }] : [];
788 });
789 const existingIndex = withoutDraft.findIndex(
790 (annotation) => annotation.lineNumber === endLine,
791 );
792 if (existingIndex < 0) {
793 return [
794 ...withoutDraft,
795 {
796 lineNumber: endLine,
797 metadata: { entries: [draftEntry] },
798 },
799 ];
800 }
801 return withoutDraft.map((annotation, index) =>
802 index === existingIndex
803 ? {
804 ...annotation,
805 metadata: { entries: [...annotation.metadata.entries, draftEntry] },
806 }
807 : annotation,
808 );
809 });
810 };
811 const hasOpenCommentForm = lineAnnotations.some((annotation) =>
812 annotation.metadata.entries.some((entry) => entry.kind === "draft"),
813 );
814 useEffect(() => {
815 const root = surfaceRef.current;
816 if (!root) return;
817 return installFileEditorDismissal({
818 root,
819 editor: { setSelections: (selections) => editorRef.current?.setSelections(selections) },
820 isBlocked: () => hasOpenCommentForm,
821 onDismiss: () => setSelectedRange(null),
822 });
823 }, [hasOpenCommentForm, setSelectedRange]);
824 const handleLineSelectionEnd = (range: SelectedLineRange | null) => {
825 setSelectedRange(range);
826 if (range) {
827 beginComment(range);
828 }
829 };
830​
831 const handlePostRender: FilePostRender = (fileContainer, instance, phase) => {
832 onPostRender(fileContainer, instance, phase);
833 onEditablePostRender(instance.file, phase);
834​
835 if (selectionFrameRef.current !== null) {
836 cancelAnimationFrame(selectionFrameRef.current);
837 selectionFrameRef.current = null;
838 }
839 if (phase === "unmount") return;
840​
841 selectionFrameRef.current = requestAnimationFrame(() => {
842 selectionFrameRef.current = null;
843 if (!fileContainer.isConnected) return;
844 instance.setSelectedLines(selectedRange, { notify: false });
845 });
846 };
847​
848 return (
849 <EditProvider createEditor={createFileEditor}>
850 <div ref={surfaceRef} className="flex min-h-0 flex-1">
851 <Virtualizer
852 className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
853 config={{
854 overscrollSize: 600,
855 intersectionObserverMargin: 1200,
856 }}
857 >
858 <File<FileCommentAnnotationGroup>
859 file={externalFile}
860 edit={editable}
861 editorOptions={editorOptions}
862 onEditChange={handleEditChange}
863 options={{
864 disableFileHeader: true,
865 enableGutterUtility: !hasOpenCommentForm,
866 enableLineSelection: !hasOpenCommentForm,
867 onGutterUtilityClick: setSelectedRange,
868 onLineSelectionChange: setSelectedRange,
869 onLineSelectionEnd: handleLineSelectionEnd,
870 overflow: wordWrap ? "wrap" : "scroll",
871 theme: resolveDiffThemeName(resolvedTheme),
872 preferredHighlighter: PREFERRED_HIGHLIGHTER,
873 themeType: resolvedTheme,
874 unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
875 onPostRender: handlePostRender,
876 }}
877 selectedLines={selectedRange}
878 lineAnnotations={lineAnnotations}
879 renderAnnotation={(annotation) => (
880 <div className="py-1">
881 {annotation.metadata.entries.map((entry) => (
882 <DiffCommentAnnotation
883 key={entry.id}
884 kind={entry.kind}
885 rangeLabel={formatFileCommentRange(entry.startLine, entry.endLine)}
886 text={entry.text}
887 onCancel={() => removeAnnotationEntry(entry.id)}
888 onComment={(text) => submitAnnotationEntry(entry.id, text)}
889 onDelete={() => removeAnnotationEntry(entry.id)}
890 />
891 ))}
892 </div>
893 )}
894 className="min-h-full"
895 />
896 </Virtualizer>
897 </div>
898 </EditProvider>
899 );
901​
902function RenderedMarkdownSurface({
903 environmentId,
904 cwd,
905 relativePath,
906 contents,
907 threadRef,
908 workspaceMutationId,
909 readOnly,
910 onPendingChange,
911}: Omit<
912 EditableFileSurfaceProps,
913 | "resolvedTheme"
914 | "composerDraftTarget"
915 | "revealLine"
916 | "revealRequestId"
917 | "wordWrap"
918 | "onPostRender"
919> & {
920 threadRef: ScopedThreadRef;
921 readOnly: boolean;
922 workspaceMutationId: string | null;
923}) {
924 const saveCoordinator = useFileSaveCoordinator({
925 environmentId,
926 cwd,
927 relativePath,
928 onPendingChange,
929 });
930​
931 return (
932 <ScrollArea className="min-h-0 flex-1">
933 <FileMarkdownPreview
934 text={contents}
935 cwd={cwd}
936 relativePath={relativePath}
937 threadRef={threadRef}
938 workspaceMutationId={workspaceMutationId}
939 onTaskListChange={
940 readOnly
941 ? undefined
942 : ({ markerOffset, checked }) => {
943 const currentContents =
944 getOptimisticProjectFileQueryData(environmentId, cwd, relativePath)?.contents ??
945 contents;
946 const nextContents = setMarkdownTaskChecked(currentContents, markerOffset, checked);
947 if (nextContents === currentContents) return;
948 setProjectFileQueryData(environmentId, cwd, relativePath, nextContents);
949 saveCoordinator.change(nextContents);
950 }
951 }
952 />
953 </ScrollArea>
954 );
956​
957function renderedToggleLabel(mode: "markdown" | "html" | "table", rendered: boolean): string {
958 if (mode === "markdown") return rendered ? "Show markdown source" : "Show rendered markdown";
959 if (mode === "table") return rendered ? "Show source" : "Show table";
960 return rendered ? "Show HTML source" : "Show rendered page";
962​
963function initialExplorerOpen(): boolean {
964 try {
965 return getLocalStorageItem(FILE_EXPLORER_STORAGE_KEY, Schema.Boolean) ?? true;
966 } catch (error) {
967 console.error(error);
968 return true;
969 }
971​
972export default function FilePreviewPanel({
973 environmentId,
974 cwd,
975 projectName,
976 relativePath: requestedPath,
977 attachment,
978 threadRef,
979 composerDraftTarget,
980 keybindings,
981 availableEditors,
982 openInShortcutEnabled,
983 revealLine,
984 revealRequestId,
985 onOpenFile,
986 onNavigateFolder,
987 folderTrail,
988 onPendingChange,
989 selectedFilePending,
990 workspaceMutationId,
991}: FilePreviewPanelProps) {
992 const relativePath =
993 attachment === undefined ? resolveFilePreviewPath(requestedPath, cwd) : requestedPath;
994 const draft = typeof composerDraftTarget === "string";
995 const { resolvedTheme } = useTheme();
996 const wordWrap = useClientSettings((settings) => settings.wordWrap);
997 const canOperatePreview = useEnvironmentScope(environmentId, AuthPreviewOperateScope);
998 const primaryEnvironmentId = usePrimaryEnvironmentId();
999 const remoteOpenState = useRemoteOpenState(environmentId);
1000 const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
1001 const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(environmentId);
1002 const previewAvailable = usePreviewAvailable(environmentId);
1003 const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
1004 reportFailure: false,
1005 });
1006 const openPreview = useAtomCommand(previewEnvironment.open, {
1007 reportFailure: false,
1008 });
1009 const isVideo = relativePath !== null && isWorkspaceVideoPreviewPath(relativePath);
1010 const isAudio = relativePath !== null && !isVideo && isWorkspaceAudioPreviewPath(relativePath);
1011 const isImage = relativePath !== null && !isVideo && isWorkspaceImagePreviewPath(relativePath);
1012 const isMedia = isImage || isVideo || isAudio;
1013 const isPdf = relativePath !== null && isPdfPreviewFile(relativePath);
1014 const isHtml = relativePath !== null && !isPdf && isBrowserPreviewFile(relativePath);
1015 const isHostFile =
1016 attachment !== undefined || (relativePath !== null && isHostPath(relativePath));
1017 const fileAccess = useFilesystemReadAccess(environmentId);
1018 const { canReadFiles } = fileAccess;
1019 const canWriteFiles = useEnvironmentScope(environmentId, AuthFilesystemWriteScope);
1020 const file = useProjectFileQuery(
1021 environmentId,
1022 cwd,
1023 relativePath,
1024 attachment === undefined && relativePath !== null,
1025 );
1026 const attemptedPath = file.readError?.resolvedPath ?? file.readError?.operationPath;
1027 // Folder links fail file reads; retain mutation refresh to detect conversion to files. Host folders own
1028 // roots; folderTrail keeps descendants.
1029 const breadcrumbPath =
1030 attachment !== undefined ? null : (relativePath ?? (folderTrail === undefined ? null : ""));
1031 // Reset crumbs when a host trail reaches the workspace root and no longer passes through the current path.
1032 const breadcrumbTrail =
1033 breadcrumbPath === null ? null : retainedBreadcrumbTrail(folderTrail, breadcrumbPath);
1034 // A trail implies a folder before reads settle, preventing file-preview flashes while navigating up.
1035 const isFolder =
1036 attachment === undefined &&
1037 (file.isNotFile || (folderTrail !== undefined && file.data === null && file.error === null));
1038 const hostFolderPath = isFolder && isHostFile ? relativePath : null;
1039 // A chat-linked folder reads as a file until its read settles, and revealing a
1040 // folder selects it in its parent instead of opening it, so reveal waits.
1041 const revealsInFileManager =
1042 !isFolder &&
1043 (file.data !== null || file.error !== null) &&
1044 serverConfig?.shellRevealInFileManager === true;
1045 // Everything preview-related keys off previewPath; a folder has no preview.
1046 const previewPath = isFolder ? null : relativePath;
1047 const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen);
1048 const showExplorer = shouldShowFileExplorer({
1049 relativePath: previewPath,
1050 explorerOpen,
1051 attachmentOpen: attachment !== undefined,
1052 });
1053 const [renderMarkdownPreferred, setRenderMarkdownPreferred] = useLocalStorage(
1054 RENDER_MARKDOWN_STORAGE_KEY,
1055 false,
1056 Schema.Boolean,
1057 );
1058 const [renderBrowserFilePreferred, setRenderBrowserFilePreferred] = useLocalStorage(
1059 RENDER_BROWSER_FILE_STORAGE_KEY,
1060 true,
1061 Schema.Boolean,
1062 );
1063 const [renderTablePreferred, setRenderTablePreferred] = useLocalStorage(
1064 RENDER_TABLE_STORAGE_KEY,
1065 true,
1066 Schema.Boolean,
1067 );
1068 // Reveal ids restart at one per file; pair with the path so dismissal cannot swallow another file's reveal.
1069 const [handledReveal, setHandledReveal] = useState<{ path: string; requestId: number } | null>(
1070 null,
1071 );
1072 const breadcrumbRef = useRef<HTMLDivElement>(null);
1073 const isMarkdown = previewPath ? isMarkdownPreviewFile(previewPath) : false;
1074 const tableDelimiter =
1075 previewPath && attachment === undefined ? filePreviewDelimiter({ name: previewPath }) : null;
1076 const revealHandled =
1077 revealLine === null ||
1078 (handledReveal?.path === relativePath && handledReveal.requestId === revealRequestId);
1079 const renderMarkdown = isMarkdown && renderMarkdownPreferred && revealHandled;
1080 const renderBrowserFile = isPdf || (isHtml && renderBrowserFilePreferred && revealHandled);
1081 const renderTable = tableDelimiter !== null && renderTablePreferred && revealHandled;
1082 const renderedMode = isMarkdown
1083 ? ("markdown" as const)
1084 : tableDelimiter
1085 ? ("table" as const)
1086 : isHtml
1087 ? ("html" as const)
1088 : null;
1089 const canToggleRendered =
1090 previewPath !== null && attachment === undefined && renderedMode !== null;
1091 const showsRawText =
1092 previewPath !== null &&
1093 file.data !== null &&
1094 !(isMarkdown && renderMarkdown) &&
1095 !(tableDelimiter && renderTable) &&
1096 !renderBrowserFile;
1097 const rendered = isMarkdown ? renderMarkdown : tableDelimiter ? renderTable : renderBrowserFile;
1098 const setRenderedPreferred = isMarkdown
1099 ? setRenderMarkdownPreferred
1100 : tableDelimiter
1101 ? setRenderTablePreferred
1102 : setRenderBrowserFilePreferred;
1103 const canOpenInBrowser =
1104 canOperatePreview &&
1105 previewPath !== null &&
1106 attachment === undefined &&
1107 !isVideo &&
1108 previewAvailable &&
1109 isBrowserPreviewFile(previewPath);
1110 // Navigating up preserves the file tab; retain the trail's path spelling to find its folder tab.
1111 const navigateToFolder = (crumbPath: string) => {
1112 const path =
1113 breadcrumbTrail !== null && breadcrumbPathOf(breadcrumbTrail) === crumbPath
1114 ? breadcrumbTrail
1115 : crumbPath;
1116 onNavigateFolder(path, retainedBreadcrumbTrail(breadcrumbTrail ?? undefined, path), !isFolder);
1117 };
1118 const absolutePath =
1119 breadcrumbPath === ""
1120 ? cwd
1121 : relativePath && attachment === undefined
1122 ? resolvePathLinkTarget(relativePath, cwd)
1123 : null;
1124 const onFilePostRender = useFileLineReveal(relativePath, revealLine, revealRequestId);
1125 useWorkspaceMutationRefresh({
1126 enabled:
1127 attachment === undefined &&
1128 relativePath !== null &&
1129 // Skip mutation reads for media/PDF files; re-read similarly named folders to detect conversion to
1130 // files.
1131 (isFolder || (!isMedia && !isPdf)) &&
1132 !selectedFilePending,
1133 mutationId: workspaceMutationId,
1134 refresh: file.refresh,
1135 resourceKey: `file:${environmentId}:${cwd}:${relativePath ?? ""}`,
1136 });
1137​
1138 useEffect(() => {
1139 const crumbs = breadcrumbRef.current?.querySelectorAll<HTMLElement>("[data-file-crumb]");
1140 // Show the deepest crumb when it fits, but never at the cost of the current one.
1141 crumbs?.[crumbs.length - 1]?.scrollIntoView({ block: "nearest", inline: "end" });
1142 breadcrumbRef.current
1143 ?.querySelector<HTMLElement>("[data-current-file-crumb='true']")
1144 ?.scrollIntoView({ block: "nearest", inline: "nearest" });
1145 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A new path or trail re-renders the crumbs, so the current one scrolls back into view.
1146 }, [breadcrumbPath, breadcrumbTrail]);
1147​
1148 const toggleExplorer = () => {
1149 setExplorerOpen((current) => {
1150 const next = !current;
1151 try {
1152 setLocalStorageItem(FILE_EXPLORER_STORAGE_KEY, next, Schema.Boolean);
1153 } catch (error) {
1154 console.error(error);
1156 return next;
1157 });
1158 };
1159​
1160 const handleOpenInBrowser = () => {
1161 if (!canReadFiles || !canOperatePreview || !absolutePath || !environmentHttpBaseUrl) return;
1162 void (async () => {
1163 const result = await openFileInPreview({
1164 threadRef,
1165 filePath: absolutePath,
1166 workspaceRoot: cwd,
1167 httpBaseUrl: environmentHttpBaseUrl,
1168 createAssetUrl,
1169 openPreview,
1170 });
1171 if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
1172 return;
1174 const error = squashAtomCommandFailure(result);
1175 toastManager.add(
1176 stackedThreadToast({
1177 type: "error",
1178 title: "Unable to open file in browser",
1179 description: error instanceof Error ? error.message : "An error occurred.",
1180 }),
1181 );
1182 })();
1183 };
1184​
1185 if (attachment === undefined && !canReadFiles) {
1186 if (fileAccess.isPending) {
1187 return (
1188 <div className="flex min-h-0 flex-1 items-center justify-center gap-2 text-sm text-muted-foreground">
1189 <Spinner className="size-4" />
1190 Checking file access...
1191 </div>
1192 );
1194 return (
1195 <div className="p-4 text-sm text-muted-foreground">
1196 {fileAccess.error ?? "This connection cannot read host files."}
1197 </div>
1198 );
1200​
1201 return (
1202 <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-background">
1203 {breadcrumbPath !== null && breadcrumbTrail !== null ? (
1204 <div className={FILE_SURFACE_SUBHEADER_CLASS} data-surface-subheader>
1205 <ScrollArea
1206 radius="none"
1207 ref={breadcrumbRef}
1208 hideScrollbars
1209 scrollFade
1210 className="min-w-0 flex-1"
1211 data-file-breadcrumbs
1213 <div className="flex h-full w-max min-w-full items-center text-xs">
1214 <FileBreadcrumbs
1215 cwd={cwd}
1216 environmentId={environmentId}
1217 onNavigateFolder={navigateToFolder}
1218 onOpenFile={onOpenFile}
1219 projectName={projectName}
1220 relativePath={breadcrumbPath}
1221 trail={breadcrumbTrail}
1222 workspaceMutationId={workspaceMutationId}
1223 />
1224 </div>
1225 </ScrollArea>
1226 {absolutePath &&
1227 (environmentId === primaryEnvironmentId || remoteOpenState.mode !== "local-exec") ? (
1228 <OpenInPicker
1229 environmentId={environmentId}
1230 keybindings={keybindings}
1231 availableEditors={availableEditors}
1232 enableShortcut={openInShortcutEnabled}
1233 openInCwd={absolutePath}
1234 openInCwdIsFile={file.isFile}
1235 compact
1236 revealFileManager={revealsInFileManager}
1237 />
1238 ) : null}
1239 {canToggleRendered && renderedMode ? (
1240 <FileSurfaceAction
1241 label={renderedToggleLabel(renderedMode, rendered)}
1242 pressed={rendered}
1243 onPress={() => {
1244 const pressed = !rendered;
1245 setRenderedPreferred(pressed);
1246 setHandledReveal(
1247 pressed && relativePath !== null
1248 ? { path: relativePath, requestId: revealRequestId }
1249 : null,
1250 );
1251 }}
1253 <MorphIcon
1254 className="size-3.5"
1255 icon={rendered ? Code2 : renderedMode === "table" ? Table2 : Eye}
1256 />
1257 </FileSurfaceAction>
1258 ) : null}
1259 {showsRawText ? (
1260 <FileSurfaceAction
1261 label={wordWrap ? "Disable word wrap" : "Enable word wrap"}
1262 pressed={wordWrap}
1263 onPress={() => updateClientSettings({ wordWrap: !wordWrap })}
1265 <WrapTextIcon className="size-3.5" />
1266 </FileSurfaceAction>
1267 ) : null}
1268 {canOpenInBrowser ? (
1269 <FileSurfaceAction label="Open file in preview browser" onPress={handleOpenInBrowser}>
1270 <Globe2 className="size-3.5" />
1271 </FileSurfaceAction>
1272 ) : null}
1273 {!isHostFile && previewPath !== null ? (
1274 <FileSurfaceAction
1275 label={explorerOpen ? "Hide file explorer" : "Show file explorer"}
1276 pressed={explorerOpen}
1277 onPress={toggleExplorer}
1279 <FolderTree className="size-3.5" />
1280 </FileSurfaceAction>
1281 ) : null}
1282 </div>
1283 ) : null}
1284 {relativePath && !attachment && !isHostFile && !canWriteFiles && !fileAccess.isPending ? (
1285 <div className="shrink-0 border-b px-3 py-1.5 text-2xs text-muted-foreground">
1286 Read-only connection. Unsaved edits are kept until write access returns.
1287 </div>
1288 ) : null}
1289 {previewPath &&
1290 attachment === undefined &&
1291 !isMedia &&
1292 !renderBrowserFile &&
1293 file.data?.truncated ? (
1294 <div className="shrink-0 border-b border-warning/20 bg-warning-surface px-3 py-1.5 text-2xs text-warning-foreground">
1295 Preview limited to the first 1 MB of a {file.data.byteLength.toLocaleString()} byte file.
1296 </div>
1297 ) : null}
1298 <div className="flex min-h-0 flex-1 overflow-hidden">
1299 <div
1300 className={cn("min-w-0 flex-1 flex-col overflow-hidden", previewPath ? "flex" : "hidden")}
1302 {isFolder ? null : relativePath && attachment ? (
1303 <AttachmentFilePreview
1304 key={`${environmentId}:${attachment.id}`}
1305 name={attachment.name}
1306 mimeType={attachment.mimeType}
1307 sizeBytes={attachment.sizeBytes}
1308 asset={{ environmentId, attachmentId: attachment.id }}
1309 htmlRender={attachment.htmlRender === true}
1310 threadRef={threadRef}
1311 />
1312 ) : relativePath && isVideo && absolutePath ? (
1313 <WorkspaceVideoPreview
1314 key={`${environmentId}:${threadRef.threadId}:${absolutePath}`}
1315 environmentId={environmentId}
1316 threadRef={threadRef}
1317 draft={draft}
1318 absolutePath={absolutePath}
1319 workspaceRoot={cwd}
1320 name={relativePath}
1321 workspaceMutationId={workspaceMutationId}
1322 />
1323 ) : relativePath && isAudio && absolutePath ? (
1324 <WorkspaceAudioPreview
1325 key={`${environmentId}:${threadRef.threadId}:${absolutePath}`}
1326 environmentId={environmentId}
1327 threadRef={threadRef}
1328 draft={draft}
1329 absolutePath={absolutePath}
1330 workspaceRoot={cwd}
1331 name={relativePath}
1332 workspaceMutationId={workspaceMutationId}
1333 />
1334 ) : relativePath && isImage && absolutePath ? (
1335 <WorkspaceImagePreview
1336 key={absolutePath}
1337 environmentId={environmentId}
1338 threadRef={threadRef}
1339 draft={draft}
1340 absolutePath={absolutePath}
1341 workspaceRoot={cwd}
1342 alt={relativePath}
1343 workspaceMutationId={workspaceMutationId}
1344 />
1345 ) : relativePath && renderBrowserFile && absolutePath ? (
1346 <WorkspaceBrowserPreview
1347 key={absolutePath}
1348 environmentId={environmentId}
1349 threadRef={threadRef}
1350 draft={draft}
1351 absolutePath={absolutePath}
1352 workspaceRoot={cwd}
1353 title={relativePath}
1354 workspaceMutationId={workspaceMutationId}
1355 />
1356 ) : relativePath && absolutePath && file.readError?.failure === "binary_file" ? (
1357 <AttachmentFilePreview
1358 key={`${environmentId}:${absolutePath}`}
1359 name={relativePath.split(/[\\/]/).at(-1) || relativePath}
1360 mimeType="application/octet-stream"
1361 sizeBytes={0}
1362 asset={{
1363 environmentId,
1364 resource: {
1365 _tag: "media-file",
1366 threadId: threadRef.threadId,
1367 path: absolutePath,
1368 disposition: "attachment",
1369 },
1370 }}
1371 origin="File"
1372 />
1373 ) : relativePath && file.error && file.data === null ? (
1374 <div
1375 role="alert"
1376 className="scrollbar-gutter-both flex min-h-0 flex-1 flex-col overflow-auto"
1378 <div className="my-auto flex shrink-0 flex-col gap-3 px-6 py-6 text-center text-xs leading-relaxed">
1379 <p className="text-destructive">
1380 {file.readError ? filePreviewReadErrorMessage(file.readError) : file.error}
1381 </p>
1382 {attemptedPath ? (
1383 <p className="text-muted-foreground">
1384 Attempted path
1385 <code className="block break-all font-mono text-foreground select-all">
1386 {attemptedPath}
1387 </code>
1388 </p>
1389 ) : null}
1390 {!isHostFile ? (
1391 <p className="text-muted-foreground">
1392 Workspace folder:{" "}
1393 <code className="break-all font-mono select-all">
1394 {file.readError?.cwd ?? cwd}
1395 </code>
1396 . Check the link's path or locate the file in Files.
1397 </p>
1398 ) : null}
1399 </div>
1400 </div>
1401 ) : relativePath && file.data === null ? (
1402 <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
1403 <Spinner size="lg" />
1404 </div>
1405 ) : relativePath && file.data ? (
1406 isMarkdown && renderMarkdown ? (
1407 <RenderedMarkdownSurface
1408 key={relativePath}
1409 environmentId={environmentId}
1410 cwd={cwd}
1411 relativePath={relativePath}
1412 threadRef={threadRef}
1413 contents={file.data.contents}
1414 workspaceMutationId={workspaceMutationId}
1415 readOnly={isHostFile || !canWriteFiles}
1416 onPendingChange={onPendingChange}
1417 />
1418 ) : tableDelimiter && renderTable ? (
1419 <DelimitedTablePreview
1420 key={relativePath}
1421 name={relativePath}
1422 text={file.data.contents}
1423 delimiter={tableDelimiter}
1424 />
1425 ) : file.data.truncated || isHostFile || !canWriteFiles ? (
1426 <SourceFilePreview
1427 name={relativePath}
1428 text={file.data.contents}
1429 cacheKey={projectFileCacheKey(cwd, relativePath, file.data.contents)}
1430 onPostRender={onFilePostRender}
1431 />
1432 ) : (
1433 <DiffWorkerPoolProvider>
1434 <EditableFileSurface
1435 key={`${relativePath}:${resolvedTheme}`}
1436 environmentId={environmentId}
1437 cwd={cwd}
1438 relativePath={relativePath}
1439 composerDraftTarget={composerDraftTarget}
1440 contents={file.data.contents}
1441 resolvedTheme={resolvedTheme}
1442 revealRequestId={revealRequestId}
1443 wordWrap={wordWrap}
1444 onPostRender={onFilePostRender}
1445 onPendingChange={onPendingChange}
1446 />
1447 </DiffWorkerPoolProvider>
1449 ) : null}
1450 </div>
1451 {showExplorer ? (
1452 <aside
1453 className={cn(
1454 "flex min-h-0 shrink-0 bg-background",
1455 previewPath
1456 ? "w-[min(22rem,46%)] min-w-64 border-l border-border/60"
1457 : "min-w-0 flex-1",
1458 )}
1460 <FileBrowserPanel
1461 key={`${environmentId}:${hostFolderPath ?? cwd}`}
1462 environmentId={environmentId}
1463 cwd={hostFolderPath ?? cwd}
1464 projectName={hostFolderPath ?? projectName}
1465 hostFolder={hostFolderPath !== null}
1466 selectedPath={
1467 hostFolderPath === null
1468 ? relativePath
1469 : trailChildOf(hostFolderPath, breadcrumbTrail ?? hostFolderPath)
1471 selectedPathRevealId={revealRequestId}
1472 onOpenFile={onOpenFile}
1473 workspaceMutationId={workspaceMutationId}
1474 {...(previewPath && !isMedia && !isPdf
1475 ? { onRefreshSelectedFile: file.refresh }
1476 : {})}
1477 />
1478 </aside>
1479 ) : null}
1480 </div>
1481 </div>
1482 );