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