Open History to see the last commit
1import { Spinner } from "~/components/ui/spinner";
2import type {
3 ChatFileAttachment,
4 EditorId,
5 EnvironmentId,
6 ResolvedKeybindingsConfig,
7 ScopedThreadRef,
8} from "@t3tools/contracts";
9import { filePreviewDelimiter } from "@t3tools/shared/delimitedPreview";
10import {
11 isWorkspaceAudioPreviewPath,
12 isWorkspaceImagePreviewPath,
13 isWorkspaceVideoPreviewPath,
14} from "@t3tools/shared/filePreview";
15import { VirtualizedFile, type SelectedLineRange } from "@pierre/diffs";
16import { Editor } from "@pierre/diffs/editor";
17import { EditProvider, File, type FileOptions, Virtualizer } from "@pierre/diffs/react";
18import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";
19import {
20 isAtomCommandInterrupted,
21 squashAtomCommandFailure,
22} from "@t3tools/client-runtime/state/runtime";
23import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
24import { Code2, Eye, FolderTree, Globe2, Table2 } from "lucide-react";
25import * as Schema from "effect/Schema";
26import { useCallback, useEffect, useMemo, useRef, useState } from "react";
27
28import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview";
29import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
30import { OpenInPicker } from "~/components/chat/OpenInPicker";
31import { MediaVideoPlayer } from "~/components/media/MediaVideoPlayer";
32import { MediaActions, type MediaActionSource } from "~/components/media/MediaActions";
33import { useRemoteOpenState } from "~/remoteOpen";
34import { useClientSettings } from "~/hooks/useSettings";
35import { useTheme } from "~/hooks/useTheme";
36import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "~/hooks/useLocalStorage";
37import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";
38import { resolveDiffThemeName } from "~/lib/diffRendering";
39import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";
40import { cn } from "~/lib/utils";
41import { isPreviewSupportedInRuntime } from "~/previewStateStore";
42import { isAbsolutePath, resolvePathLinkTarget } from "~/terminal-links";
43import { ScrollArea } from "~/components/ui/scroll-area";
44import { stackedThreadToast, toastManager } from "~/components/ui/toast";
45import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
46import { buildFileReviewComment } from "~/reviewCommentContext";
47import { assetEnvironment } from "~/state/assets";
48import { useEnvironmentHttpBaseUrl, usePrimaryEnvironmentId } from "~/state/environments";
49import { previewEnvironment } from "~/state/preview";
50import { useAtomCommand } from "~/state/use-atom-command";
51import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
52
53import { AttachmentFilePreview } from "./AttachmentFilePreview";
54import { AudioPreview } from "./AudioPreview";
55import { BrowserDocumentFrame, isPdfPreviewFile } from "./BrowserDocumentFrame";
56import { DelimitedTablePreview } from "./DelimitedTablePreview";
57import FileBrowserPanel from "./FileBrowserPanel";
58import { FileBreadcrumbs } from "./FileBreadcrumbs";
59import { FileMarkdownPreview } from "./FileMarkdownPreview";
60import {
61 type FileCommentAnnotationEntry,
62 type FileCommentAnnotationGroup,
63 type FileCommentLineAnnotation,
64 formatFileCommentRange,
65 nextFileCommentId,
66 normalizeFileCommentRange,
67 remapFileCommentAnnotations,
68} from "./fileCommentAnnotations";
69import { installFileEditorDismissal } from "./fileEditorDismissal";
70import {
71 FILE_LINK_REVEAL_ATTRIBUTE,
72 FILE_LINK_REVEAL_UNSAFE_CSS,
73 FILE_SURFACE_SUBHEADER_CLASS,
74 FileSurfaceAction,
75 FileSurfaceFailure,
76 FileSurfaceLoading,
77} from "./fileSurfaceChrome";
78import SourceFilePreview from "./ReadOnlySourcePreview";
79import { resolveCenteredFileLineScrollTop } from "./fileLineReveal";
80import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation";
81import { projectFileCacheKey, projectFileEditorCacheKey } from "./fileContentRevision";
82import {
83 isMarkdownPreviewFile,
84 setMarkdownTaskChecked,
85 shouldShowFileExplorer,
86} from "./filePreviewMode";
87import { useFileSaveCoordinator } from "./useFileSaveCoordinator";
88import {
89 getOptimisticProjectFileQueryData,
90 setProjectFileQueryData,
91 useProjectFileQuery,
92} from "./projectFilesQueryState";
93
94interface FilePreviewPanelProps {
95 environmentId: EnvironmentId;
96 cwd: string;
97 projectName: string;
98 relativePath: string | null;
99 attachment?: ChatFileAttachment;
100 threadRef: ScopedThreadRef;
101 composerDraftTarget: ScopedThreadRef | DraftId;
102 keybindings: ResolvedKeybindingsConfig;
103 availableEditors: ReadonlyArray<EditorId>;
104 revealLine: number | null;
105 revealRequestId: number;
106 onOpenFile: (relativePath: string) => void;
107 onPendingChange: (relativePath: string, pending: boolean) => void;
108 selectedFilePending: boolean;
109 workspaceMutationId: string | null;
110}
111
112const FILE_EXPLORER_STORAGE_KEY = "t3code.fileExplorerOpen";
113const RENDER_MARKDOWN_STORAGE_KEY = "t3code.renderMarkdown";
114const RENDER_BROWSER_FILE_STORAGE_KEY = "t3code.renderBrowserFile";
115const RENDER_TABLE_STORAGE_KEY = "t3code.renderTable";
116type FilePostRender = NonNullable<FileOptions<unknown>["onPostRender"]>;
117
118function WorkspaceImagePreview(props: {
119 readonly environmentId: EnvironmentId;
120 readonly threadRef: ScopedThreadRef;
121 readonly absolutePath: string;
122 readonly workspaceRoot: string;
123 readonly alt: string;
124 readonly workspaceMutationId: string | null;
125}) {
126 const resource = useMemo(
127 () => ({
128 _tag: "workspace-file" as const,
129 threadId: props.threadRef.threadId,
130 path: props.absolutePath,
131 }),
132 [props.threadRef.threadId, props.absolutePath],
133 );
134 const assetUrl = useAssetUrlState(props.environmentId, resource);
135 const [failedUrl, setFailedUrl] = useState<string | null>(null);
136 const revisionSuffix =
137 props.workspaceMutationId === null
138 ? ""
139 : `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}workspace-revision=${encodeURIComponent(props.workspaceMutationId)}`;
140 const imageUrl = assetUrl._tag === "Success" ? `${assetUrl.url}${revisionSuffix}` : null;
141 const actionsSource: MediaActionSource = {
142 kind: "image",
143 name: props.alt,
144 src: imageUrl,
145 reference: mediaFileReference(props.absolutePath, props.workspaceRoot),
146 asset: { environmentId: props.environmentId, resource },
147 };
148
149 if (assetUrl._tag === "Failure" || (imageUrl !== null && failedUrl === imageUrl)) {
150 return (
151 <MediaActions source={actionsSource}>
152 <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
153 Unable to load workspace image.
154 </div>
155 </MediaActions>
156 );
157 }
158
159 return assetUrl._tag === "Success" && imageUrl !== null ? (
160 <div className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-4">
161 <MediaActions source={actionsSource}>
162 <img
163 className="max-h-full max-w-full object-contain"
164 src={imageUrl}
165 alt={props.alt}
166 onError={() => setFailedUrl(imageUrl)}
167 />
168 </MediaActions>
169 </div>
170 ) : (
171 <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
172 <Spinner className="size-5" />
173 </div>
174 );
175}
176
177/**
178 * Renders an HTML or PDF file in place from its signed asset URL. HTML runs in
179 * a sandboxed frame with an opaque origin, so a page cannot reach the app's
180 * session or storage. A file inside the workspace may load sibling assets; a
181 * host file outside it is served on its own.
182 */
183function WorkspaceBrowserPreview(props: {
184 readonly environmentId: EnvironmentId;
185 readonly threadRef: ScopedThreadRef;
186 readonly absolutePath: string;
187 readonly workspaceRoot: string;
188 readonly title: string;
189 readonly workspaceMutationId: string | null;
190}) {
191 const insideWorkspace =
192 mediaFileReference(props.absolutePath, props.workspaceRoot).relativePath !== undefined;
193 const resource = useMemo(
194 () => ({
195 _tag: insideWorkspace ? ("workspace-file" as const) : ("media-file" as const),
196 threadId: props.threadRef.threadId,
197 path: props.absolutePath,
198 }),
199 [insideWorkspace, props.threadRef.threadId, props.absolutePath],
200 );
201 const assetUrl = useAssetUrlState(props.environmentId, resource);
202 const revisionSuffix =
203 props.workspaceMutationId === null
204 ? ""
205 : `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}workspace-revision=${encodeURIComponent(props.workspaceMutationId)}`;
206
207 if (assetUrl._tag === "Failure") {
208 return (
209 <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
210 Unable to load file preview.
211 </div>
212 );
213 }
214 if (assetUrl._tag !== "Success") {
215 return (
216 <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
217 <Spinner className="size-5" />
218 </div>
219 );
220 }
221 return (
222 <BrowserDocumentFrame
223 src={`${assetUrl.url}${revisionSuffix}`}
224 title={props.title}
225 pdf={isPdfPreviewFile(props.absolutePath)}
226 />
227 );
228}
229
230function WorkspaceVideoPreview(props: {
231 readonly environmentId: EnvironmentId;
232 readonly threadRef: ScopedThreadRef;
233 readonly absolutePath: string;
234 readonly workspaceRoot: string;
235 readonly name: string;
236 readonly workspaceMutationId: string | null;
237}) {
238 const resource = useMemo(
239 () => ({
240 _tag: "media-file" as const,
241 threadId: props.threadRef.threadId,
242 path: props.absolutePath,
243 }),
244 [props.threadRef.threadId, props.absolutePath],
245 );
246 const assetUrl = useAssetUrlState(props.environmentId, resource);
247 const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
248 useWorkspaceMutationRefresh({
249 mutationId: props.workspaceMutationId,
250 resourceKey: JSON.stringify([props.environmentId, resource]),
251 refresh: () => {
252 // Failed refreshes flow through assetUrl and can be retried from the player.
253 void refreshAssetUrl().catch(() => undefined);
254 },
255 });
256 const revisionSuffix =
257 props.workspaceMutationId === null
258 ? ""
259 : `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}workspace-revision=${encodeURIComponent(props.workspaceMutationId)}`;
260 const latestUrl = assetUrl._tag === "Success" ? `${assetUrl.url}${revisionSuffix}` : null;
261
262 return (
263 <div className="flex min-h-0 flex-1 items-center justify-center overflow-hidden p-4">
264 <MediaVideoPlayer
265 src={latestUrl}
266 sourceFailed={assetUrl._tag === "Failure"}
267 label={props.name}
268 revision={props.workspaceMutationId}
269 preload="metadata"
270 className="flex h-full min-h-0 w-full max-w-5xl items-center justify-center"
271 onRetry={refreshAssetUrl}
272 actionsSource={{
273 kind: "video",
274 name: props.name,
275 src: latestUrl,
276 reference: mediaFileReference(props.absolutePath, props.workspaceRoot),
277 asset: { environmentId: props.environmentId, resource },
278 }}
279 />
280 </div>
281 );
282}
283
284function WorkspaceAudioPreview(props: {
285 readonly environmentId: EnvironmentId;
286 readonly threadRef: ScopedThreadRef;
287 readonly absolutePath: string;
288 readonly name: string;
289 readonly workspaceMutationId: string | null;
290}) {
291 const resource = useMemo(
292 () => ({
293 _tag: "media-file" as const,
294 threadId: props.threadRef.threadId,
295 path: props.absolutePath,
296 }),
297 [props.threadRef.threadId, props.absolutePath],
298 );
299 const assetUrl = useAssetUrlState(props.environmentId, resource);
300 const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
301 const [failedUrl, setFailedUrl] = useState<string | null>(null);
302 useWorkspaceMutationRefresh({
303 mutationId: props.workspaceMutationId,
304 resourceKey: JSON.stringify([props.environmentId, resource]),
305 refresh: () => {
306 void refreshAssetUrl().catch(() => undefined);
307 },
308 });
309 const revisionSuffix =
310 props.workspaceMutationId === null
311 ? ""
312 : `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}workspace-revision=${encodeURIComponent(props.workspaceMutationId)}`;
313 const url = assetUrl._tag === "Success" ? `${assetUrl.url}${revisionSuffix}` : null;
314 if (assetUrl._tag === "Failure" || (url !== null && failedUrl === url)) {
315 return (
316 <FileSurfaceFailure
317 message="Unable to load audio."
318 onRetry={() => {
319 setFailedUrl(null);
320 void refreshAssetUrl().catch(() => undefined);
321 }}
322 />
323 );
324 }
325 if (url === null) return <FileSurfaceLoading />;
326 return <AudioPreview src={url} name={props.name} onError={() => setFailedUrl(url)} />;
327}
328
329function clampFileLine(contents: string, requestedLine: number): number {
330 let lineCount = 1;
331 for (let index = 0; index < contents.length; index += 1) {
332 const character = contents.charCodeAt(index);
333 if (character === 10) {
334 lineCount += 1;
335 } else if (character === 13) {
336 lineCount += 1;
337 if (contents.charCodeAt(index + 1) === 10) index += 1;
338 }
339 }
340 return Math.min(Math.max(1, requestedLine), lineCount);
341}
342
343function updateFileLinkReveal(fileContainer: HTMLElement, line: number | null): void {
344 const root = fileContainer.shadowRoot ?? fileContainer;
345 for (const element of root.querySelectorAll<HTMLElement>(`[${FILE_LINK_REVEAL_ATTRIBUTE}]`)) {
346 element.removeAttribute(FILE_LINK_REVEAL_ATTRIBUTE);
347 }
348 if (line === null) return;
349
350 root
351 .querySelector<HTMLElement>(`[data-line="${line}"]`)
352 ?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, "");
353 root
354 .querySelector<HTMLElement>(`[data-column-number="${line}"]`)
355 ?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, "");
356}
357
358/**
359 * Frames to keep retrying while the file contents or line metrics are not
360 * available yet (fresh mounts hydrate asynchronously).
361 */
362const REVEAL_MAX_ATTEMPTS = 30;
363/**
364 * After scrolling to the target, hold it for a short window so late
365 * programmatic scroll resets (editable-editor focus and state restoration)
366 * cannot silently snap the file back to the top. Real user input cancels the
367 * guard immediately.
368 */
369const REVEAL_GUARD_FRAMES = 20;
370const REVEAL_GUARD_TOLERANCE_PX = 2;
371
372interface FileRevealState {
373 frameId: number | null;
374 cancelGuard: (() => void) | null;
375 handledRequestId: number | null;
376 latestRequestId: number | null;
377}
378
379function useFileLineReveal(
380 relativePath: string | null,
381 revealLine: number | null,
382 revealRequestId: number,
383): FilePostRender {
384 const [revealStatesByPath] = useState(() => new Map<string, FileRevealState>());
385
386 return useCallback<FilePostRender>(
387 (fileContainer, instance, phase) => {
388 if (relativePath === null) return;
389
390 const existingState = revealStatesByPath.get(relativePath);
391 const state: FileRevealState = existingState ?? {
392 frameId: null,
393 cancelGuard: null,
394 handledRequestId: null,
395 latestRequestId: null,
396 };
397 if (!existingState) revealStatesByPath.set(relativePath, state);
398
399 const cancelPendingReveal = () => {
400 if (state.frameId !== null) {
401 cancelAnimationFrame(state.frameId);
402 state.frameId = null;
403 }
404 state.cancelGuard?.();
405 };
406
407 if (phase === "unmount") {
408 cancelPendingReveal();
409 return;
410 }
411
412 const contents = instance.file?.contents;
413 const targetLine =
414 revealLine === null || contents === undefined ? null : clampFileLine(contents, revealLine);
415 updateFileLinkReveal(fileContainer, targetLine);
416
417 if (!(instance instanceof VirtualizedFile)) return;
418
419 if (state.latestRequestId !== revealRequestId) {
420 cancelPendingReveal();
421 state.latestRequestId = revealRequestId;
422 state.handledRequestId = null;
423 }
424
425 if (revealLine === null) {
426 fileContainer.style.minHeight = "";
427 return;
428 }
429
430 const scrollContainer = fileContainer.closest<HTMLElement>(".file-preview-virtualizer");
431 if (!scrollContainer) return;
432 fileContainer.style.minHeight = `${Math.ceil(
433 Math.max(instance.height, scrollContainer.clientHeight),
434 )}px`;
435
436 if (state.handledRequestId === revealRequestId || state.frameId !== null) {
437 return;
438 }
439
440 const resolveScrollTarget = (line: number): number | null => {
441 const linePosition = instance.getLinePosition(line);
442 if (!linePosition) return null;
443
444 const scrollContainerRect = scrollContainer.getBoundingClientRect();
445 const fileTop =
446 scrollContainer.scrollTop +
447 fileContainer.getBoundingClientRect().top -
448 scrollContainerRect.top;
449 const root = fileContainer.shadowRoot ?? fileContainer;
450 const renderedLineElement = root.querySelector<HTMLElement>(`[data-line="${line}"]`);
451 const renderedLineRect = renderedLineElement?.getBoundingClientRect();
452
453 return resolveCenteredFileLineScrollTop({
454 scrollTop: scrollContainer.scrollTop,
455 scrollHeight: scrollContainer.scrollHeight,
456 viewportTop: scrollContainerRect.top,
457 viewportHeight: scrollContainer.clientHeight,
458 fileTop,
459 estimatedLine: linePosition,
460 ...(renderedLineRect && renderedLineRect.height > 0
461 ? {
462 renderedLine: {
463 top: renderedLineRect.top,
464 height: renderedLineRect.height,
465 },
466 }
467 : {}),
468 });
469 };
470
471 const guardScrollTarget = (line: number) => {
472 let framesLeft = REVEAL_GUARD_FRAMES;
473 let guardFrameId: number | null = null;
474 const cancelGuard = () => {
475 if (guardFrameId !== null) {
476 cancelAnimationFrame(guardFrameId);
477 guardFrameId = null;
478 }
479 scrollContainer.removeEventListener("wheel", cancelGuard);
480 scrollContainer.removeEventListener("touchstart", cancelGuard);
481 scrollContainer.removeEventListener("pointerdown", cancelGuard, true);
482 window.removeEventListener("keydown", cancelGuard, true);
483 if (state.cancelGuard === cancelGuard) state.cancelGuard = null;
484 };
485 scrollContainer.addEventListener("wheel", cancelGuard, { passive: true });
486 scrollContainer.addEventListener("touchstart", cancelGuard, { passive: true });
487 // Pierre stops gutter pointer events from bubbling. Listen in capture
488 // so starting a comment cancels the reveal guard before the row expands.
489 scrollContainer.addEventListener("pointerdown", cancelGuard, {
490 passive: true,
491 capture: true,
492 });
493 window.addEventListener("keydown", cancelGuard, true);
494 const holdTarget = () => {
495 guardFrameId = null;
496 framesLeft -= 1;
497 if (framesLeft <= 0 || !scrollContainer.isConnected) {
498 cancelGuard();
499 return;
500 }
501 const targetTop = resolveScrollTarget(line);
502 if (
503 targetTop !== null &&
504 Math.abs(scrollContainer.scrollTop - targetTop) > REVEAL_GUARD_TOLERANCE_PX
505 ) {
506 scrollContainer.scrollTop = targetTop;
507 }
508 guardFrameId = requestAnimationFrame(holdTarget);
509 };
510 guardFrameId = requestAnimationFrame(holdTarget);
511 state.cancelGuard = cancelGuard;
512 };
513
514 const scheduleReveal = (attempt: number) => {
515 state.frameId = requestAnimationFrame(() => {
516 state.frameId = null;
517 if (state.latestRequestId !== revealRequestId || !fileContainer.isConnected) {
518 return;
519 }
520
521 // Contents and line metrics can lag the first post-render on fresh
522 // mounts; clamping against missing contents would scroll to line 1
523 // and wrongly mark the request handled.
524 const currentContents = instance.file?.contents;
525 const line =
526 currentContents === undefined ? null : clampFileLine(currentContents, revealLine);
527 const targetTop = line === null ? null : resolveScrollTarget(line);
528 if (line === null || targetTop === null) {
529 if (attempt < REVEAL_MAX_ATTEMPTS) scheduleReveal(attempt + 1);
530 return;
531 }
532 updateFileLinkReveal(fileContainer, line);
533
534 scrollContainer.scrollTop = targetTop;
535 state.handledRequestId = revealRequestId;
536 guardScrollTarget(line);
537 });
538 };
539
540 scheduleReveal(0);
541 },
542 [revealStatesByPath, relativePath, revealLine, revealRequestId],
543 );
544}
545
546interface EditableFileSurfaceProps {
547 environmentId: EnvironmentId;
548 cwd: string;
549 relativePath: string;
550 composerDraftTarget: ScopedThreadRef | DraftId;
551 contents: string;
552 resolvedTheme: "light" | "dark";
553 revealRequestId: number;
554 wordWrap: boolean;
555 onPostRender: FilePostRender;
556 onPendingChange: (relativePath: string, pending: boolean) => void;
557}
558
559interface FileSelectionOverride {
560 revealRequestId: number;
561 range: SelectedLineRange | null;
562}
563
564function EditableFileSurface({
565 environmentId,
566 cwd,
567 relativePath,
568 composerDraftTarget,
569 contents,
570 resolvedTheme,
571 revealRequestId,
572 wordWrap,
573 onPostRender,
574 onPendingChange,
575}: EditableFileSurfaceProps) {
576 const addReviewComment = useComposerDraftStore((store) => store.addReviewComment);
577 const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment);
578 const [lineAnnotations, setLineAnnotations] = useState<FileCommentLineAnnotation[]>([]);
579 const [selectionOverride, setSelectionOverride] = useState<FileSelectionOverride | null>(null);
580 const selectedRange =
581 selectionOverride?.revealRequestId === revealRequestId ? selectionOverride.range : null;
582 const setSelectedRange = useCallback(
583 (range: SelectedLineRange | null) => {
584 setSelectionOverride({ revealRequestId, range });
585 },
586 [revealRequestId],
587 );
588 const surfaceRef = useRef<HTMLDivElement>(null);
589 const selectionFrameRef = useRef<number | null>(null);
590 const saveCoordinator = useFileSaveCoordinator({
591 environmentId,
592 cwd,
593 relativePath,
594 onPendingChange,
595 });
596 const editor = useMemo(
597 () =>
598 new Editor<FileCommentAnnotationGroup>({
599 persistState: true,
600 persistStateStorage: "inMemory",
601 onChange: (file, nextLineAnnotations) => {
602 setProjectFileQueryData(environmentId, cwd, relativePath, file.contents);
603 saveCoordinator.change(file.contents);
604 if (nextLineAnnotations) {
605 const remapped = remapFileCommentAnnotations(
606 nextLineAnnotations as FileCommentLineAnnotation[],
607 );
608 setLineAnnotations(remapped);
609 for (const annotation of remapped) {
610 for (const entry of annotation.metadata.entries) {
611 if (entry.kind !== "comment") continue;
612 addReviewComment(
613 composerDraftTarget,
614 buildFileReviewComment({
615 id: entry.id,
616 filePath: relativePath,
617 startLine: entry.startLine,
618 endLine: entry.endLine,
619 text: entry.text,
620 contents: file.contents,
621 }),
622 );
623 }
624 }
625 }
626 },
627 }),
628 [addReviewComment, composerDraftTarget, cwd, environmentId, relativePath, saveCoordinator],
629 );
630
631 useEffect(
632 () => () => {
633 editor.cleanUp();
634 },
635 [editor],
636 );
637
638 const removeAnnotationEntry = useCallback(
639 (entryId: string) => {
640 setSelectedRange(null);
641 removeReviewComment(composerDraftTarget, entryId);
642 setLineAnnotations((current) => {
643 return current.flatMap((annotation) => {
644 const entries = annotation.metadata.entries.filter((entry) => entry.id !== entryId);
645 return entries.length > 0 ? [{ ...annotation, metadata: { entries } }] : [];
646 });
647 });
648 },
649 [composerDraftTarget, removeReviewComment, setSelectedRange],
650 );
651
652 const submitAnnotationEntry = useCallback(
653 (entryId: string, text: string) => {
654 setSelectedRange(null);
655 const entry = lineAnnotations
656 .flatMap((annotation) => annotation.metadata.entries)
657 .find((candidate) => candidate.id === entryId);
658 if (entry) {
659 addReviewComment(
660 composerDraftTarget,
661 buildFileReviewComment({
662 id: entry.id,
663 filePath: relativePath,
664 startLine: entry.startLine,
665 endLine: entry.endLine,
666 text,
667 contents,
668 }),
669 );
670 }
671 setLineAnnotations((current) =>
672 current.map((annotation) => ({
673 ...annotation,
674 metadata: {
675 entries: annotation.metadata.entries.map((annotationEntry) =>
676 annotationEntry.id === entryId
677 ? { ...annotationEntry, kind: "comment", text }
678 : annotationEntry,
679 ),
680 },
681 })),
682 );
683 },
684 [
685 addReviewComment,
686 composerDraftTarget,
687 contents,
688 lineAnnotations,
689 relativePath,
690 setSelectedRange,
691 ],
692 );
693
694 const beginComment = useCallback(
695 (range: SelectedLineRange) => {
696 editor.setSelections([]);
697 editor.blur();
698 const { startLine, endLine } = normalizeFileCommentRange(range);
699 const draftEntry: FileCommentAnnotationEntry = {
700 id: nextFileCommentId(),
701 kind: "draft",
702 startLine,
703 endLine,
704 text: "",
705 };
706 setLineAnnotations((current) => {
707 const withoutDraft = current.flatMap((annotation) => {
708 const entries = annotation.metadata.entries.filter((entry) => entry.kind !== "draft");
709 return entries.length > 0 ? [{ ...annotation, metadata: { entries } }] : [];
710 });
711 const existingIndex = withoutDraft.findIndex(
712 (annotation) => annotation.lineNumber === endLine,
713 );
714 if (existingIndex < 0) {
715 return [
716 ...withoutDraft,
717 {
718 lineNumber: endLine,
719 metadata: { entries: [draftEntry] },
720 },
721 ];
722 }
723 return withoutDraft.map((annotation, index) =>
724 index === existingIndex
725 ? {
726 ...annotation,
727 metadata: { entries: [...annotation.metadata.entries, draftEntry] },
728 }
729 : annotation,
730 );
731 });
732 },
733 [editor],
734 );
735 const hasOpenCommentForm = lineAnnotations.some((annotation) =>
736 annotation.metadata.entries.some((entry) => entry.kind === "draft"),
737 );
738 useEffect(() => {
739 const root = surfaceRef.current;
740 if (!root) return;
741 return installFileEditorDismissal({
742 root,
743 editor,
744 isBlocked: () => hasOpenCommentForm,
745 onDismiss: () => setSelectedRange(null),
746 });
747 }, [editor, hasOpenCommentForm, setSelectedRange]);
748 const handleLineSelectionEnd = useCallback(
749 (range: SelectedLineRange | null) => {
750 setSelectedRange(range);
751 if (range) {
752 beginComment(range);
753 }
754 },
755 [beginComment, setSelectedRange],
756 );
757
758 const handlePostRender = useCallback<FilePostRender>(
759 (fileContainer, instance, phase) => {
760 onPostRender(fileContainer, instance, phase);
761
762 if (selectionFrameRef.current !== null) {
763 cancelAnimationFrame(selectionFrameRef.current);
764 selectionFrameRef.current = null;
765 }
766 if (phase === "unmount") return;
767
768 selectionFrameRef.current = requestAnimationFrame(() => {
769 selectionFrameRef.current = null;
770 if (!fileContainer.isConnected) return;
771 instance.setSelectedLines(selectedRange, { notify: false });
772 });
773 },
774 [onPostRender, selectedRange],
775 );
776
777 return (
778 <EditProvider editor={editor}>
779 <div ref={surfaceRef} className="flex min-h-0 flex-1">
780 <Virtualizer
781 className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
782 config={{
783 overscrollSize: 600,
784 intersectionObserverMargin: 1200,
785 }}
786 >
787 <File<FileCommentAnnotationGroup>
788 file={{
789 name: relativePath,
790 contents,
791 cacheKey: projectFileEditorCacheKey(
792 environmentId,
793 cwd,
794 relativePath,
795 contents,
796 editor.getFile(),
797 ),
798 }}
799 options={{
800 disableFileHeader: true,
801 enableGutterUtility: !hasOpenCommentForm,
802 enableLineSelection: !hasOpenCommentForm,
803 onGutterUtilityClick: setSelectedRange,
804 onLineSelectionChange: setSelectedRange,
805 onLineSelectionEnd: handleLineSelectionEnd,
806 overflow: wordWrap ? "wrap" : "scroll",
807 theme: resolveDiffThemeName(resolvedTheme),
808 preferredHighlighter: PREFERRED_HIGHLIGHTER,
809 themeType: resolvedTheme,
810 unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
811 onPostRender: handlePostRender,
812 }}
813 selectedLines={selectedRange}
814 lineAnnotations={lineAnnotations}
815 renderAnnotation={(annotation) => (
816 <div className="py-1">
817 {annotation.metadata.entries.map((entry) => (
818 <DiffCommentAnnotation
819 key={entry.id}
820 kind={entry.kind}
821 rangeLabel={formatFileCommentRange(entry.startLine, entry.endLine)}
822 text={entry.text}
823 onCancel={() => removeAnnotationEntry(entry.id)}
824 onComment={(text) => submitAnnotationEntry(entry.id, text)}
825 onDelete={() => removeAnnotationEntry(entry.id)}
826 />
827 ))}
828 </div>
829 )}
830 className="min-h-full"
831 contentEditable
832 />
833 </Virtualizer>
834 </div>
835 </EditProvider>
836 );
837}
838
839function RenderedMarkdownSurface({
840 environmentId,
841 cwd,
842 relativePath,
843 contents,
844 threadRef,
845 readOnly,
846 onPendingChange,
847}: Omit<
848 EditableFileSurfaceProps,
849 | "resolvedTheme"
850 | "composerDraftTarget"
851 | "revealLine"
852 | "revealRequestId"
853 | "wordWrap"
854 | "onPostRender"
855> & {
856 threadRef: ScopedThreadRef;
857 readOnly: boolean;
858}) {
859 const saveCoordinator = useFileSaveCoordinator({
860 environmentId,
861 cwd,
862 relativePath,
863 onPendingChange,
864 });
865
866 return (
867 <ScrollArea className="min-h-0 flex-1">
868 <FileMarkdownPreview
869 text={contents}
870 cwd={cwd}
871 relativePath={relativePath}
872 threadRef={threadRef}
873 onTaskListChange={
874 readOnly
875 ? undefined
876 : ({ markerOffset, checked }) => {
877 const currentContents =
878 getOptimisticProjectFileQueryData(environmentId, cwd, relativePath)?.contents ??
879 contents;
880 const nextContents = setMarkdownTaskChecked(currentContents, markerOffset, checked);
881 if (nextContents === currentContents) return;
882 setProjectFileQueryData(environmentId, cwd, relativePath, nextContents);
883 saveCoordinator.change(nextContents);
884 }
885 }
886 />
887 </ScrollArea>
888 );
889}
890
891function renderedToggleLabel(mode: "markdown" | "html" | "table", rendered: boolean): string {
892 if (mode === "markdown") return rendered ? "Show markdown source" : "Show rendered markdown";
893 if (mode === "table") return rendered ? "Show source" : "Show table";
894 return rendered ? "Show HTML source" : "Show rendered page";
895}
896
897function initialExplorerOpen(): boolean {
898 try {
899 return getLocalStorageItem(FILE_EXPLORER_STORAGE_KEY, Schema.Boolean) ?? true;
900 } catch (error) {
901 console.error(error);
902 return true;
903 }
904}
905
906export default function FilePreviewPanel({
907 environmentId,
908 cwd,
909 projectName,
910 relativePath,
911 attachment,
912 threadRef,
913 composerDraftTarget,
914 keybindings,
915 availableEditors,
916 revealLine,
917 revealRequestId,
918 onOpenFile,
919 onPendingChange,
920 selectedFilePending,
921 workspaceMutationId,
922}: FilePreviewPanelProps) {
923 const { resolvedTheme } = useTheme();
924 const wordWrap = useClientSettings((settings) => settings.wordWrap);
925 const primaryEnvironmentId = usePrimaryEnvironmentId();
926 const remoteOpenState = useRemoteOpenState(environmentId);
927 const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(environmentId);
928 const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
929 reportFailure: false,
930 });
931 const openPreview = useAtomCommand(previewEnvironment.open, {
932 reportFailure: false,
933 });
934 const isVideo = relativePath !== null && isWorkspaceVideoPreviewPath(relativePath);
935 const isAudio = relativePath !== null && !isVideo && isWorkspaceAudioPreviewPath(relativePath);
936 const isImage = relativePath !== null && !isVideo && isWorkspaceImagePreviewPath(relativePath);
937 const isMedia = isImage || isVideo || isAudio;
938 // PDFs have no text to show; HTML has, and can toggle between page and source.
939 const isPdf = relativePath !== null && isPdfPreviewFile(relativePath);
940 const isHtml = relativePath !== null && !isPdf && isBrowserPreviewFile(relativePath);
941 // A file outside the workspace (an absolute path) is shown, never edited.
942 const isHostFile =
943 attachment !== undefined || (relativePath !== null && isAbsolutePath(relativePath));
944 const file = useProjectFileQuery(
945 environmentId,
946 cwd,
947 relativePath,
948 attachment === undefined && !isMedia && !isPdf,
949 );
950 const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen);
951 const showExplorer = shouldShowFileExplorer({
952 relativePath,
953 explorerOpen,
954 attachmentOpen: attachment !== undefined,
955 });
956 // Reading markdown rendered is a preference, not a property of one file. Keeping
957 // it on the panel meant a thread switch dropped it and forced source back.
958 const [renderMarkdownPreferred, setRenderMarkdownPreferred] = useLocalStorage(
959 RENDER_MARKDOWN_STORAGE_KEY,
960 false,
961 Schema.Boolean,
962 );
963 const [renderBrowserFilePreferred, setRenderBrowserFilePreferred] = useLocalStorage(
964 RENDER_BROWSER_FILE_STORAGE_KEY,
965 true,
966 Schema.Boolean,
967 );
968 const [renderTablePreferred, setRenderTablePreferred] = useLocalStorage(
969 RENDER_TABLE_STORAGE_KEY,
970 true,
971 Schema.Boolean,
972 );
973 // Paired with the path on purpose: each file surface counts its reveals from
974 // one, so a bare id would let a dismissed reveal on one file swallow the first
975 // reveal on the next.
976 const [handledReveal, setHandledReveal] = useState<{ path: string; requestId: number } | null>(
977 null,
978 );
979 const breadcrumbRef = useRef<HTMLDivElement>(null);
980 const isMarkdown = relativePath ? isMarkdownPreviewFile(relativePath) : false;
981 const tableDelimiter =
982 relativePath && attachment === undefined ? filePreviewDelimiter({ name: relativePath }) : null;
983 // A reveal still wins over the preference: the line only exists in the source.
984 const revealHandled =
985 revealLine === null ||
986 (handledReveal?.path === relativePath && handledReveal.requestId === revealRequestId);
987 const renderMarkdown = isMarkdown && renderMarkdownPreferred && revealHandled;
988 const renderBrowserFile = isPdf || (isHtml && renderBrowserFilePreferred && revealHandled);
989 const renderTable = tableDelimiter !== null && renderTablePreferred && revealHandled;
990 const renderedMode = isMarkdown
991 ? ("markdown" as const)
992 : tableDelimiter
993 ? ("table" as const)
994 : isHtml
995 ? ("html" as const)
996 : null;
997 const canToggleRendered = attachment === undefined && renderedMode !== null;
998 const rendered = isMarkdown ? renderMarkdown : tableDelimiter ? renderTable : renderBrowserFile;
999 const setRenderedPreferred = isMarkdown
1000 ? setRenderMarkdownPreferred
1001 : tableDelimiter
1002 ? setRenderTablePreferred
1003 : setRenderBrowserFilePreferred;
1004 const canOpenInBrowser =
1005 relativePath !== null &&
1006 attachment === undefined &&
1007 !isVideo &&
1008 isPreviewSupportedInRuntime() &&
1009 isBrowserPreviewFile(relativePath);
1010 const absolutePath =
1011 relativePath && attachment === undefined ? resolvePathLinkTarget(relativePath, cwd) : null;
1012 const onFilePostRender = useFileLineReveal(relativePath, revealLine, revealRequestId);
1013 useWorkspaceMutationRefresh({
1014 enabled:
1015 attachment === undefined &&
1016 relativePath !== null &&
1017 !isMedia &&
1018 !isPdf &&
1019 !selectedFilePending,
1020 mutationId: workspaceMutationId,
1021 refresh: file.refresh,
1022 resourceKey: `file:${environmentId}:${cwd}:${relativePath ?? ""}`,
1023 });
1024
1025 useEffect(() => {
1026 const currentCrumb = breadcrumbRef.current?.querySelector<HTMLElement>(
1027 "[data-current-file-crumb='true']",
1028 );
1029 currentCrumb?.scrollIntoView({ block: "nearest", inline: "end" });
1030 }, [relativePath]);
1031
1032 const toggleExplorer = () => {
1033 setExplorerOpen((current) => {
1034 const next = !current;
1035 try {
1036 setLocalStorageItem(FILE_EXPLORER_STORAGE_KEY, next, Schema.Boolean);
1037 } catch (error) {
1038 console.error(error);
1039 }
1040 return next;
1041 });
1042 };
1043
1044 const handleOpenInBrowser = useCallback(() => {
1045 if (!absolutePath || !environmentHttpBaseUrl) return;
1046 void (async () => {
1047 const result = await openFileInPreview({
1048 threadRef,
1049 filePath: absolutePath,
1050 workspaceRoot: cwd,
1051 httpBaseUrl: environmentHttpBaseUrl,
1052 createAssetUrl,
1053 openPreview,
1054 });
1055 if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
1056 return;
1057 }
1058 const error = squashAtomCommandFailure(result);
1059 toastManager.add(
1060 stackedThreadToast({
1061 type: "error",
1062 title: "Unable to open file in browser",
1063 description: error instanceof Error ? error.message : "An error occurred.",
1064 }),
1065 );
1066 })();
1067 }, [absolutePath, createAssetUrl, cwd, environmentHttpBaseUrl, openPreview, threadRef]);
1068
1069 return (
1070 <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-background">
1071 {relativePath && attachment === undefined ? (
1072 <div className={FILE_SURFACE_SUBHEADER_CLASS} data-surface-subheader>
1073 <ScrollArea
1074 ref={breadcrumbRef}
1075 hideScrollbars
1076 scrollFade
1077 className="min-w-0 flex-1 rounded-none"
1078 data-file-breadcrumbs
1079 >
1080 <div className="flex h-full w-max min-w-full items-center text-xs">
1081 <FileBreadcrumbs
1082 cwd={cwd}
1083 environmentId={environmentId}
1084 onOpenFile={onOpenFile}
1085 projectName={projectName}
1086 relativePath={relativePath}
1087 workspaceMutationId={workspaceMutationId}
1088 />
1089 </div>
1090 </ScrollArea>
1091 {absolutePath &&
1092 (environmentId === primaryEnvironmentId || remoteOpenState.mode !== "local-exec") ? (
1093 <OpenInPicker
1094 environmentId={environmentId}
1095 keybindings={keybindings}
1096 availableEditors={availableEditors}
1097 openInCwd={absolutePath}
1098 compact
1099 enableShortcut={false}
1100 />
1101 ) : null}
1102 {canToggleRendered && renderedMode ? (
1103 <FileSurfaceAction
1104 label={renderedToggleLabel(renderedMode, rendered)}
1105 pressed={rendered}
1106 onPress={() => {
1107 const pressed = !rendered;
1108 setRenderedPreferred(pressed);
1109 setHandledReveal(
1110 pressed && relativePath !== null
1111 ? { path: relativePath, requestId: revealRequestId }
1112 : null,
1113 );
1114 }}
1115 >
1116 {rendered ? (
1117 <Code2 className="size-3.5" />
1118 ) : renderedMode === "table" ? (
1119 <Table2 className="size-3.5" />
1120 ) : (
1121 <Eye className="size-3.5" />
1122 )}
1123 </FileSurfaceAction>
1124 ) : null}
1125 {canOpenInBrowser ? (
1126 <FileSurfaceAction label="Open file in preview browser" onPress={handleOpenInBrowser}>
1127 <Globe2 className="size-3.5" />
1128 </FileSurfaceAction>
1129 ) : null}
1130 {!isHostFile ? (
1131 <FileSurfaceAction
1132 label={explorerOpen ? "Hide file explorer" : "Show file explorer"}
1133 pressed={explorerOpen}
1134 onPress={toggleExplorer}
1135 >
1136 <FolderTree className="size-3.5" />
1137 </FileSurfaceAction>
1138 ) : null}
1139 </div>
1140 ) : null}
1141 {relativePath &&
1142 attachment === undefined &&
1143 !isMedia &&
1144 !renderBrowserFile &&
1145 file.data?.truncated ? (
1146 <div className="shrink-0 border-b border-warning/20 bg-warning-surface px-3 py-1.5 text-[11px] text-warning-foreground">
1147 Preview limited to the first 1 MB of a {file.data.byteLength.toLocaleString()} byte file.
1148 </div>
1149 ) : null}
1150 <div className="flex min-h-0 flex-1 overflow-hidden">
1151 <div
1152 className={cn(
1153 "min-w-0 flex-1 flex-col overflow-hidden",
1154 relativePath ? "flex" : "hidden",
1155 )}
1156 >
1157 {relativePath && attachment ? (
1158 <AttachmentFilePreview
1159 key={`${environmentId}:${attachment.id}`}
1160 name={attachment.name}
1161 mimeType={attachment.mimeType}
1162 sizeBytes={attachment.sizeBytes}
1163 asset={{ environmentId, attachmentId: attachment.id }}
1164 />
1165 ) : relativePath && isVideo && absolutePath ? (
1166 <WorkspaceVideoPreview
1167 key={`${environmentId}:${threadRef.threadId}:${absolutePath}`}
1168 environmentId={environmentId}
1169 threadRef={threadRef}
1170 absolutePath={absolutePath}
1171 workspaceRoot={cwd}
1172 name={relativePath}
1173 workspaceMutationId={workspaceMutationId}
1174 />
1175 ) : relativePath && isAudio && absolutePath ? (
1176 <WorkspaceAudioPreview
1177 key={`${environmentId}:${threadRef.threadId}:${absolutePath}`}
1178 environmentId={environmentId}
1179 threadRef={threadRef}
1180 absolutePath={absolutePath}
1181 name={relativePath}
1182 workspaceMutationId={workspaceMutationId}
1183 />
1184 ) : relativePath && isImage && absolutePath ? (
1185 <WorkspaceImagePreview
1186 key={absolutePath}
1187 environmentId={environmentId}
1188 threadRef={threadRef}
1189 absolutePath={absolutePath}
1190 workspaceRoot={cwd}
1191 alt={relativePath}
1192 workspaceMutationId={workspaceMutationId}
1193 />
1194 ) : relativePath && renderBrowserFile && absolutePath ? (
1195 <WorkspaceBrowserPreview
1196 key={absolutePath}
1197 environmentId={environmentId}
1198 threadRef={threadRef}
1199 absolutePath={absolutePath}
1200 workspaceRoot={cwd}
1201 title={relativePath}
1202 workspaceMutationId={workspaceMutationId}
1203 />
1204 ) : relativePath && file.error && file.data === null ? (
1205 <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
1206 {file.error}
1207 </div>
1208 ) : relativePath && file.data === null ? (
1209 <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
1210 <Spinner className="size-5" />
1211 </div>
1212 ) : relativePath && file.data ? (
1213 isMarkdown && renderMarkdown ? (
1214 // Markdown reconciles in place across text updates, so a file
1215 // switch needs a new key or the previous file's disclosure and
1216 // wrap state carries into the next document.
1217 <RenderedMarkdownSurface
1218 key={relativePath}
1219 environmentId={environmentId}
1220 cwd={cwd}
1221 relativePath={relativePath}
1222 threadRef={threadRef}
1223 contents={file.data.contents}
1224 readOnly={isHostFile}
1225 onPendingChange={onPendingChange}
1226 />
1227 ) : tableDelimiter && renderTable ? (
1228 <DelimitedTablePreview
1229 key={relativePath}
1230 name={relativePath}
1231 text={file.data.contents}
1232 delimiter={tableDelimiter}
1233 />
1234 ) : file.data.truncated || isHostFile ? (
1235 <SourceFilePreview
1236 name={relativePath}
1237 text={file.data.contents}
1238 cacheKey={projectFileCacheKey(cwd, relativePath, file.data.contents)}
1239 onPostRender={onFilePostRender}
1240 />
1241 ) : (
1242 <DiffWorkerPoolProvider>
1243 <EditableFileSurface
1244 key={`${relativePath}:${resolvedTheme}`}
1245 environmentId={environmentId}
1246 cwd={cwd}
1247 relativePath={relativePath}
1248 composerDraftTarget={composerDraftTarget}
1249 contents={file.data.contents}
1250 resolvedTheme={resolvedTheme}
1251 revealRequestId={revealRequestId}
1252 wordWrap={wordWrap}
1253 onPostRender={onFilePostRender}
1254 onPendingChange={onPendingChange}
1255 />
1256 </DiffWorkerPoolProvider>
1257 )
1258 ) : null}
1259 </div>
1260 {showExplorer ? (
1261 <aside
1262 className={cn(
1263 "flex min-h-0 shrink-0 bg-background",
1264 relativePath
1265 ? "w-[min(22rem,46%)] min-w-64 border-l border-border/60"
1266 : "min-w-0 flex-1",
1267 )}
1268 >
1269 <FileBrowserPanel
1270 key={`${environmentId}:${cwd}`}
1271 environmentId={environmentId}
1272 cwd={cwd}
1273 projectName={projectName}
1274 selectedPath={relativePath}
1275 selectedPathRevealId={revealRequestId}
1276 onOpenFile={onOpenFile}
1277 workspaceMutationId={workspaceMutationId}
1278 {...(relativePath && !isMedia && !isPdf
1279 ? { onRefreshSelectedFile: file.refresh }
1280 : {})}
1281 />
1282 </aside>
1283 ) : null}
1284 </div>
1285 </div>
1286 );
1287}