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

FilePreviewPanel.tsx

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