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

FilePreviewPanel.tsx

1,493 lines55.3 KB

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