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