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