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

FilePreviewPanel.tsx

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