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