TypeScript
feat(web): preview document attachments in the file viewer (#9292)
Julius Marminge775129984857
diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.tsindex 8d7c696cd62..539827a0a5c 100644--- a/apps/server/src/assets/AssetAccess.test.ts+++ b/apps/server/src/assets/AssetAccess.test.ts@@ -576,6 +576,67 @@ describe("AssetAccess", () => {});}).pipe(Effect.provide(testLayer)),);++ it.effect("serves document attachments inline when a viewer requests it", () =>+ Effect.gen(function* () {+ const config = yield* ServerConfig.ServerConfig;+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001-pdf";+ const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.pdf`);+ yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });+ yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));++ const result = yield* issueAssetUrl({+ resource: {+ _tag: "attachment",+ attachmentId,+ fileName: "report.pdf",+ mimeType: "application/pdf",+ disposition: "inline",+ },+ });+ const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);+ const separatorIndex = suffix.indexOf("/");++ expect(+ yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),+ ).toEqual({+ kind: "file",+ path: attachmentPath,+ fileName: "report.pdf",+ mimeType: "application/pdf",+ });+ }).pipe(Effect.provide(testLayer)),+ );++ it.effect("keeps inline requests for other attachment types as downloads", () =>+ Effect.gen(function* () {+ const config = yield* ServerConfig.ServerConfig;+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const attachmentId = "thread-1-00000000-0000-4000-8000-000000000002-zip";+ const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.zip`);+ yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });+ yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));++ const result = yield* issueAssetUrl({+ resource: {+ _tag: "attachment",+ attachmentId,+ fileName: "archive.zip",+ mimeType: "text/html",+ disposition: "inline",+ },+ });+ const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);+ const separatorIndex = suffix.indexOf("/");++ expect(+ yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),+ ).toMatchObject({ kind: "file", path: attachmentPath, download: true });+ }).pipe(Effect.provide(testLayer)),+ );it.effect("issues project favicon capabilities with a signed fallback", () =>Effect.gen(function* () {const fileSystem = yield* FileSystem.FileSystem;diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.tsindex ad7cb273cf0..36fa9130b68 100644--- a/apps/server/src/assets/AssetAccess.ts+++ b/apps/server/src/assets/AssetAccess.ts@@ -51,6 +51,14 @@ const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;const PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000;const PROJECT_FAVICON_VERSION_PREFIX = "v";const INLINE_VIDEO_MIME_TYPE_PATTERN = /^video\/[\w!#$&^.+-]+$/i;+// Extensions a document viewer may request inline. The extension comes from+// the attachment id the server assigned, never from the client's mime type.+const INLINE_DOCUMENT_EXTENSIONS = new Set(["pdf", "html", "htm"]);+const INLINE_DOCUMENT_MIME_TYPES: Record<string, string> = {+ pdf: "application/pdf",+ html: "text/html",+ htm: "text/html",+};const PREVIEW_ASSET_EXTENSIONS = new Set([...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,@@ -362,19 +370,31 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i}// Generic files carry their extension inside the attachment id (that// shape resolves the on-disk path); images do not. Videos and images- // render inline; other generic files download.- const isGenericFile = parseAttachmentFileExtension(input.resource.attachmentId) !== null;+ // render inline. Other generic files download, unless a document viewer+ // asked for inline and the stored extension is one a browser can show.+ const extension = parseAttachmentFileExtension(input.resource.attachmentId);+ const isGenericFile = extension !== null;const videoMimeType = input.resource.mimeType?.split(";", 1)[0]?.trim() ?? "";const isVideo = INLINE_VIDEO_MIME_TYPE_PATTERN.test(videoMimeType);+ const inlineDocumentMimeType =+ input.resource.disposition === "inline" &&+ extension !== null &&+ INLINE_DOCUMENT_EXTENSIONS.has(extension)+ ? INLINE_DOCUMENT_MIME_TYPES[extension]+ : undefined;claims = {version: 1,kind: "attachment",attachmentId: input.resource.attachmentId,- ...(isGenericFile && !isVideo ? { download: true } : {}),- ...(input.resource.fileName !== undefined ? { fileName: input.resource.fileName } : {}),- ...(input.resource.mimeType !== undefined- ? { mimeType: isVideo ? videoMimeType : input.resource.mimeType }+ ...(isGenericFile && !isVideo && inlineDocumentMimeType === undefined+ ? { download: true }: {}),+ ...(input.resource.fileName !== undefined ? { fileName: input.resource.fileName } : {}),+ ...(inlineDocumentMimeType !== undefined+ ? { mimeType: inlineDocumentMimeType }+ : input.resource.mimeType !== undefined+ ? { mimeType: isVideo ? videoMimeType : input.resource.mimeType }+ : {}),expiresAt,};fileName = input.resource.fileName ?? path.basename(attachmentPath);diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.tsindex 6b094085665..0c253033ac5 100644--- a/apps/server/src/http.test.ts+++ b/apps/server/src/http.test.ts@@ -324,6 +324,19 @@ describe("assetResponseHeaders", () => {"X-Content-Type-Options": "nosniff",});});+ it("serves inline attachment documents with their declared mime type", () => {+ expect(+ assetResponseHeaders("/attachments/upload.bin", { mimeType: "application/pdf" }),+ ).toMatchObject({+ "Content-Type": "application/pdf",+ });+ expect(+ assetResponseHeaders("/attachments/upload.bin", { mimeType: "text/html" }),+ ).toMatchObject({+ "Content-Type": "text/html; charset=utf-8",+ "Content-Security-Policy": "sandbox allow-scripts allow-forms allow-popups allow-modals",+ });+ });it("serves HTML assets as utf-8 inside a sandboxed origin", () => {for (const path of ["/workspace/page.html", "/workspace/PAGE.HTM", "/tmp/report.html"]) {expect(assetResponseHeaders(path)).toMatchObject({diff --git a/apps/server/src/http.ts b/apps/server/src/http.tsindex 4d5865335a3..3bcca884107 100644--- a/apps/server/src/http.ts+++ b/apps/server/src/http.ts@@ -64,6 +64,8 @@ const isSafeDownloadMimeType = (mimeType: string): boolean =>!/(?:^text\/html$|\/xml(?:$|-)|\+xml$)/i.test(mimeType.trim().toLowerCase());const isSafeInlineVideoMimeType = (mimeType: string): boolean =>DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) && mimeType.toLowerCase().startsWith("video/");+const isSafeInlineDocumentMimeType = (mimeType: string): boolean =>+ mimeType.toLowerCase() === "application/pdf" || mimeType.toLowerCase() === "text/html";/** RFC 6266 disposition with an ASCII fallback name plus a UTF-8 `filename*`. */export function downloadContentDisposition(fileName?: string): string {@@ -93,7 +95,7 @@ export function assetResponseHeaders(},): Record<string, string> {const lowerPath = filePath.toLowerCase();- const inlineVideoMimeType = options?.mimeType?.split(";", 1)[0]?.trim();+ const inlineMimeType = options?.mimeType?.split(";", 1)[0]?.trim();return {"Cache-Control": "private, max-age=3600","X-Content-Type-Options": "nosniff",@@ -106,14 +108,24 @@ export function assetResponseHeaders(? options.mimeType: "application/octet-stream",}- : inlineVideoMimeType !== undefined && isSafeInlineVideoMimeType(inlineVideoMimeType)- ? { "Content-Type": inlineVideoMimeType }- : lowerPath.endsWith(".html") || lowerPath.endsWith(".htm")+ : inlineMimeType !== undefined && isSafeInlineVideoMimeType(inlineMimeType)+ ? { "Content-Type": inlineMimeType }+ : inlineMimeType !== undefined && isSafeInlineDocumentMimeType(inlineMimeType)? {- "Content-Type": "text/html; charset=utf-8",- "Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY,+ "Content-Type":+ inlineMimeType.toLowerCase() === "text/html"+ ? "text/html; charset=utf-8"+ : "application/pdf",+ ...(inlineMimeType.toLowerCase() === "text/html"+ ? { "Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY }+ : {}),}- : {}),+ : lowerPath.endsWith(".html") || lowerPath.endsWith(".htm")+ ? {+ "Content-Type": "text/html; charset=utf-8",+ "Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY,+ }+ : {}),...(!options?.download && lowerPath.endsWith(".svg")? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY }: {}),diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex cadb8b3028b..a5335856be9 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -132,6 +132,7 @@ import {DEFAULT_THREAD_TERMINAL_ID,MAX_TERMINALS_PER_GROUP,type ChatMessage,+ isBrowserPreviewAttachment,isImageAttachment,videoMimeType,type SessionPhase,@@ -2602,7 +2603,7 @@ function ChatViewContent(props: ChatViewProps) {});}, []);const serverMessages = activeThread?.messages;- const openFileAttachment = useCallback(+ const downloadFileAttachment = useCallback(async (attachment: ChatFileAttachment) => {const connection = readPreparedConnection(environmentId);if (!connection) {@@ -2654,6 +2655,16 @@ function ChatViewContent(props: ChatViewProps) {},[createAttachmentAssetUrl, environmentId, routeThreadKey],);+ const openFileAttachment = useCallback(+ (attachment: ChatFileAttachment) => {+ if (isBrowserPreviewAttachment(attachment) && activeThreadRef) {+ useRightPanelStore.getState().openAttachment(activeThreadRef, attachment);+ return;+ }+ void downloadFileAttachment(attachment);+ },+ [activeThreadRef, downloadFileAttachment],+ );const serverAttachmentIds = useMemo(() => {const attachmentIds = new Set<string>();for (const message of serverMessages ?? []) {@@ -7351,14 +7362,18 @@ function ChatViewContent(props: ChatViewProps) {/>) : (renderedRightPanelSurface?.kind === "files" ||renderedRightPanelSurface?.kind === "file") &&- activeProject &&- activeWorkspaceRoot ? (+ ((activeProject && activeWorkspaceRoot) ||+ (renderedRightPanelSurface.kind === "file" && renderedRightPanelSurface.attachment)) ? (<Suspense fallback={null}><FilePreviewPanel- key={`${activeProject.environmentId}:${activeWorkspaceRoot}`}- environmentId={activeProject.environmentId}- cwd={activeWorkspaceRoot}- projectName={activeProject.title}+ key={`${activeThread.environmentId}:${+ renderedRightPanelSurface.kind === "file" && renderedRightPanelSurface.attachment+ ? `attachment:${renderedRightPanelSurface.attachment.id}`+ : activeWorkspaceRoot+ }`}+ environmentId={activeThread.environmentId}+ cwd={activeWorkspaceRoot ?? ""}+ projectName={activeProject?.title ?? ""}threadRef={activeThreadRef}composerDraftTarget={composerDraftTarget}keybindings={keybindings}@@ -7368,6 +7383,9 @@ function ChatViewContent(props: ChatViewProps) {? renderedRightPanelSurface.relativePath: null}+ {...(renderedRightPanelSurface.kind === "file" && renderedRightPanelSurface.attachment+ ? { attachment: renderedRightPanelSurface.attachment }+ : {})}revealLine={renderedRightPanelSurface.kind === "file"? (renderedRightPanelSurface.revealLine ?? null)@@ -7508,6 +7526,7 @@ function ChatViewContent(props: ChatViewProps) {isRevertingCheckpoint={isRevertingCheckpoint}onImageExpand={onExpandTimelineImage}onFileOpen={openFileAttachment}+ onFileDownload={downloadFileAttachment}openingVideoAttachmentId={openingVideoAttachmentId}markdownCwd={gitCwd ?? undefined}resolvedTheme={resolvedTheme}diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsxindex 667390ebd47..5a9356a0fff 100644--- a/apps/web/src/components/RightPanelTabs.tsx+++ b/apps/web/src/components/RightPanelTabs.tsx@@ -793,7 +793,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {if (surfaceIndex < 0) return;const items: ContextMenuItem<TabContextMenuAction>[] = [];- if (surface.kind === "file") {+ if (surface.kind === "file" && surface.attachment === undefined) {items.push({ id: "copy-path", label: "Copy path" });}const menuPreviewTabId = previewTabIdOf(surface, props.previewSessions);@@ -837,7 +837,9 @@ export function RightPanelTabs(props: RightPanelTabsProps) {const action = await api.contextMenu.show(items, { x: event.clientX, y: event.clientY });switch (action) {case "copy-path":- if (surface.kind === "file") props.onCopyFilePath(surface.relativePath);+ if (surface.kind === "file" && surface.attachment === undefined) {+ props.onCopyFilePath(surface.relativePath);+ }break;case "toggle-mute": {// menuOverlay repeats the disabled gate above: the desktop tab mustdiff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsxindex 1044a956bb6..3cd601ce09a 100644--- a/apps/web/src/components/chat/MessagesTimeline.test.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx@@ -437,7 +437,7 @@ describe("MessagesTimeline", () => {expect(resolveTimelineMinimapInteractiveWidth(40, true)).toBe("22rem");});- it("renders generic attachments as download links instead of image previews", () => {+ it("gives browser documents separate preview and download controls", () => {const entry = {...buildUserTimelineEntry("Read the report."),message: {@@ -459,9 +459,9 @@ describe("MessagesTimeline", () => {<MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,);- expect(markup).toContain(- '<a href="https://environment.test/api/assets/report.pdf" download="report.pdf" class="flex min-w-0 items-center gap-2 rounded-md py-1 text-sm hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70">',- );+ expect(markup).toContain('aria-label="Preview report.pdf"');+ expect(markup).toContain('aria-label="Download report.pdf"');+ expect(markup).not.toContain('download="report.pdf"');expect(markup).not.toContain('alt="report.pdf"');});@@ -502,7 +502,7 @@ describe("MessagesTimeline", () => {expect(busyMarkup).not.toContain('disabled=""');expect(busyMarkup).toContain(">Loading…</span>");});- it("renders a file download button without creating its URL in advance", () => {+ it("renders an ordinary file download button without creating its URL in advance", () => {const entry = {...buildUserTimelineEntry("Read the report."),message: {@@ -511,8 +511,8 @@ describe("MessagesTimeline", () => {{type: "file" as const,id: "attachment-report-pdf",- name: "report.pdf",- mimeType: "application/pdf",+ name: "archive.zip",+ mimeType: "application/zip",sizeBytes: 42,},],@@ -524,9 +524,9 @@ describe("MessagesTimeline", () => {);expect(markup).toContain(- '<button type="button" aria-label="Download report.pdf" class="flex min-w-0 cursor-pointer items-center gap-2 rounded-md py-1 text-left text-sm hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70">',+ '<button type="button" aria-label="Download archive.zip" class="flex min-w-0 cursor-pointer items-center gap-2 rounded-md py-1 text-left text-sm hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70">',);- expect(markup).not.toContain("href=");+ expect(markup).not.toContain("<a href=");});it("does not download an optimistic file before the server supplies its attachment ID", () => {@@ -581,7 +581,7 @@ describe("MessagesTimeline", () => {expect(markup).toContain("voice-memo.ogg");expect(markup).not.toContain('aria-label="Download voice-memo.ogg"');expect(markup).not.toContain('alt="voice-memo.ogg"');- expect(markup).not.toContain("href=");+ expect(markup).not.toContain("<a href=");});it("keeps reserved end space when tool work starts while reading history", () => {diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex 95f4b35f665..64ca547ee1a 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -51,6 +51,7 @@ import {} from "../../session-logic";import {type ChatImageAttachment,+ isBrowserPreviewAttachment,isFileAttachment,isImageAttachment,isVideoAttachment,@@ -73,7 +74,6 @@ import {CircleAlertIcon,DownloadIcon,EyeIcon,- FileIcon,GlobeIcon,HammerIcon,MessageCircleIcon,@@ -99,6 +99,7 @@ import {keepTimelineEndVisibleAfterOverlayGrowth,} from "./timelineScrollAnchoring";import { MessageCopyButton } from "./MessageCopyButton";+import { PierreEntryIcon } from "./PierreEntryIcon";import { AssistantSelectionToolbar } from "./AssistantSelectionToolbar";import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";import {@@ -186,6 +187,7 @@ interface TimelineRowSharedState {onUseArtifactTemplate: (template: CodexArtifactTemplate) => void;onImageExpand: (preview: ExpandedImagePreview) => void;onFileOpen: (attachment: ChatFileAttachment) => void;+ onFileDownload: (attachment: ChatFileAttachment) => void;openingVideoAttachmentId: string | null;onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;onToggleTurnFold: (turnId: TurnId) => void;@@ -286,6 +288,7 @@ interface MessagesTimelineProps {isRevertingCheckpoint: boolean;onImageExpand: (preview: ExpandedImagePreview) => void;onFileOpen?: (attachment: ChatFileAttachment) => void;+ onFileDownload?: (attachment: ChatFileAttachment) => void;openingVideoAttachmentId: string | null;activeThreadEnvironmentId: EnvironmentId;markdownCwd: string | undefined;@@ -337,6 +340,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({isRevertingCheckpoint,onImageExpand,onFileOpen = NOOP_OPEN_ATTACHMENT,+ onFileDownload = NOOP_OPEN_ATTACHMENT,openingVideoAttachmentId,activeThreadEnvironmentId,markdownCwd,@@ -629,6 +633,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({onUseArtifactTemplate,onImageExpand,onFileOpen,+ onFileDownload,openingVideoAttachmentId,onOpenTurnDiff,onToggleTurnFold,@@ -652,6 +657,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({onUseArtifactTemplate,onImageExpand,onFileOpen,+ onFileDownload,openingVideoAttachmentId,onOpenTurnDiff,onToggleTurnFold,@@ -1221,16 +1227,53 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"{otherUserFiles.length > 0 || unknownAttachments.length > 0 ? (<div className="mb-2 flex flex-col gap-1">{otherUserFiles.map((file) => {- const content = (+ const opensInPreview = isBrowserPreviewAttachment(file);+ const fileIdentity = (<>- <FileIcon className="size-4 shrink-0 text-secondary-label" />+ <PierreEntryIcon pathValue={file.name} kind="file" theme={ctx.resolvedTheme} /><span className="min-w-0 flex-1 truncate">{file.name}</span>+ </>+ );+ if (opensInPreview && file.downloadable !== false) {+ return (+ <div key={file.id} className="flex min-w-0 items-center gap-1">+ <button+ type="button"+ aria-label={`Preview ${file.name}`}+ onClick={() => ctx.onFileOpen(file)}+ className="focus-visible:ring-ring/70 flex min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-md py-1 text-left text-sm hover:underline focus-visible:ring-2 focus-visible:outline-none focus-visible:ring-inset"+ >+ {fileIdentity}+ <EyeIcon className="size-4 shrink-0" />+ </button>+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ size="icon-xs"+ variant="ghost-muted"+ aria-label={`Download ${file.name}`}+ onClick={() => ctx.onFileDownload(file)}+ />+ }+ >+ <DownloadIcon />+ </TooltipTrigger>+ <TooltipPopup side="top">Download {file.name}</TooltipPopup>+ </Tooltip>+ </div>+ );+ }++ const content = (+ <>+ {fileIdentity}{file.downloadable === false ? null : (<DownloadIcon className="size-4 shrink-0" />)}</>);- return file.previewUrl ? (+ return file.previewUrl && !opensInPreview ? (<akey={file.id}href={file.previewUrl}@@ -1247,7 +1290,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"<buttonkey={file.id}type="button"- aria-label={`Download ${file.name}`}+ aria-label={`${opensInPreview ? "Preview" : "Download"} ${file.name}`}onClick={() => ctx.onFileOpen(file)}className="flex min-w-0 cursor-pointer items-center gap-2 rounded-md py-1 text-left text-sm hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70">@@ -1257,7 +1300,11 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"})}{unknownAttachments.map((attachment) => (<div key={attachment.id} className="flex min-w-0 items-center gap-2 py-1 text-sm">- <FileIcon className="size-4 shrink-0 text-secondary-label" />+ <PierreEntryIcon+ pathValue={attachment.name}+ kind="file"+ theme={ctx.resolvedTheme}+ /><span className="min-w-0 flex-1 truncate">{attachment.name}</span></div>))}diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.tsindex 3b5295f180e..5ef590847c4 100644--- a/apps/web/src/components/files/FilePreviewPanel.test.ts+++ b/apps/web/src/components/files/FilePreviewPanel.test.ts@@ -5,7 +5,11 @@ import {normalizeFileCommentRange,remapFileCommentAnnotations,} from "./fileCommentAnnotations";-import { isMarkdownPreviewFile, setMarkdownTaskChecked } from "./filePreviewMode";+import {+ isMarkdownPreviewFile,+ setMarkdownTaskChecked,+ shouldShowFileExplorer,+} from "./filePreviewMode";describe("file comment annotations", () => {it("normalizes and formats selected line ranges", () => {@@ -66,6 +70,42 @@ describe("isMarkdownPreviewFile", () => {});});+describe("shouldShowFileExplorer", () => {+ it("hides the workspace tree for host files and attachments", () => {+ expect(+ shouldShowFileExplorer({+ relativePath: "/tmp/report.pdf",+ explorerOpen: true,+ attachmentOpen: false,+ }),+ ).toBe(false);+ expect(+ shouldShowFileExplorer({+ relativePath: "report.pdf",+ explorerOpen: true,+ attachmentOpen: true,+ }),+ ).toBe(false);+ });++ it("keeps the saved explorer preference for workspace files", () => {+ expect(+ shouldShowFileExplorer({+ relativePath: "docs/report.pdf",+ explorerOpen: true,+ attachmentOpen: false,+ }),+ ).toBe(true);+ expect(+ shouldShowFileExplorer({+ relativePath: "docs/report.pdf",+ explorerOpen: false,+ attachmentOpen: false,+ }),+ ).toBe(false);+ });+});+describe("setMarkdownTaskChecked", () => {const markdown = "- [ ] First\n- [x] Second\n";diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsxindex 40c67bfce5e..0ad18434d7e 100644--- a/apps/web/src/components/files/FilePreviewPanel.tsx+++ b/apps/web/src/components/files/FilePreviewPanel.tsx@@ -1,4 +1,5 @@import type {+ ChatFileAttachment,EditorId,EnvironmentId,ResolvedKeybindingsConfig,@@ -23,6 +24,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview";import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";import { OpenInPicker } from "~/components/chat/OpenInPicker";+import { PierreEntryIcon } from "~/components/chat/PierreEntryIcon";import { MediaVideoPlayer } from "~/components/media/MediaVideoPlayer";import { MediaActions, type MediaActionSource } from "~/components/media/MediaActions";import { useRemoteOpenState } from "~/remoteOpen";@@ -64,7 +66,11 @@ import { installFileEditorDismissal } from "./fileEditorDismissal";import { resolveCenteredFileLineScrollTop } from "./fileLineReveal";import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation";import { projectFileCacheKey, projectFileEditorCacheKey } from "./fileContentRevision";-import { isMarkdownPreviewFile, setMarkdownTaskChecked } from "./filePreviewMode";+import {+ isMarkdownPreviewFile,+ setMarkdownTaskChecked,+ shouldShowFileExplorer,+} from "./filePreviewMode";import { FileSaveCoordinator } from "./fileSaveCoordinator";import {confirmProjectFileQueryData,@@ -78,6 +84,7 @@ interface FilePreviewPanelProps {cwd: string;projectName: string;relativePath: string | null;+ attachment?: ChatFileAttachment;threadRef: ScopedThreadRef;composerDraftTarget: ScopedThreadRef | DraftId;keybindings: ResolvedKeybindingsConfig;@@ -200,6 +207,69 @@ function WorkspaceImagePreview(props: {const isPdfPreviewFile = (path: string): boolean => /\.pdf$/i.test(path.split(/[?#]/, 1)[0] ?? "");+function BrowserDocumentFrame(props: {+ readonly src: string;+ readonly title: string;+ readonly pdf: boolean;+}) {+ const className = "min-h-0 flex-1 border-0 bg-white";+ // The built-in PDF viewer needs an unsandboxed frame; a PDF runs no scripts.+ return props.pdf ? (+ // oxlint-disable-next-line react/iframe-missing-sandbox+ <iframe key={props.src} src={props.src} title={props.title} className={className} />+ ) : (+ <iframe+ key={props.src}+ src={props.src}+ title={props.title}+ className={className}+ sandbox="allow-scripts allow-forms allow-popups allow-modals"+ />+ );+}++function AttachmentBrowserPreview(props: {+ readonly environmentId: EnvironmentId;+ readonly attachment: ChatFileAttachment;+}) {+ const resource = useMemo(+ () => ({+ _tag: "attachment" as const,+ attachmentId: props.attachment.id,+ fileName: props.attachment.name,+ mimeType: props.attachment.mimeType,+ disposition: "inline" as const,+ }),+ [props.attachment.id, props.attachment.mimeType, props.attachment.name],+ );+ const assetUrl = useAssetUrlState(props.environmentId, resource);++ if (assetUrl._tag === "Failure") {+ return (+ <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">+ Unable to load attachment preview.+ </div>+ );+ }+ if (assetUrl._tag !== "Success") {+ return (+ <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">+ <LoaderCircle className="size-5 animate-spin" />+ </div>+ );+ }+ return (+ <BrowserDocumentFrame+ src={assetUrl.url}+ title={props.attachment.name}+ pdf={+ isPdfPreviewFile(props.attachment.name) ||+ props.attachment.mimeType.split(";", 1)[0]?.trim().toLowerCase() === "application/pdf"+ }+ />+ );+}+/*** Renders an HTML or PDF file in place from its signed asset URL. HTML runs in* a sandboxed frame with an opaque origin, so a page cannot reach the app's@@ -244,19 +314,11 @@ function WorkspaceBrowserPreview(props: {</div>);}- const src = `${assetUrl.url}${revisionSuffix}`;- const className = "min-h-0 flex-1 border-0 bg-white";- // The built-in PDF viewer needs an unsandboxed frame; a PDF runs no scripts.- return isPdfPreviewFile(props.absolutePath) ? (- // oxlint-disable-next-line react/iframe-missing-sandbox- <iframe key={src} src={src} title={props.title} className={className} />- ) : (- <iframe- key={src}- src={src}+ return (+ <BrowserDocumentFrame+ src={`${assetUrl.url}${revisionSuffix}`}title={props.title}- className={className}- sandbox="allow-scripts allow-forms allow-popups allow-modals"+ pdf={isPdfPreviewFile(props.absolutePath)}/>);}@@ -922,6 +984,7 @@ export default function FilePreviewPanel({cwd,projectName,relativePath,+ attachment,threadRef,composerDraftTarget,keybindings,@@ -951,9 +1014,20 @@ export default function FilePreviewPanel({const isPdf = relativePath !== null && isPdfPreviewFile(relativePath);const isHtml = relativePath !== null && !isPdf && isBrowserPreviewFile(relativePath);// A file outside the workspace (an absolute path) is shown, never edited.- const isHostFile = relativePath !== null && isAbsolutePath(relativePath);- const file = useProjectFileQuery(environmentId, cwd, relativePath, !isMedia && !isPdf);+ const isHostFile =+ attachment !== undefined || (relativePath !== null && isAbsolutePath(relativePath));+ const file = useProjectFileQuery(+ environmentId,+ cwd,+ relativePath,+ attachment === undefined && !isMedia && !isPdf,+ );const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen);+ const showExplorer = shouldShowFileExplorer({+ relativePath,+ explorerOpen,+ attachmentOpen: attachment !== undefined,+ });// Reading markdown rendered is a preference, not a property of one file. Keeping// it on the panel meant a thread switch dropped it and forced source back.const [renderMarkdownPreferred, setRenderMarkdownPreferred] = useLocalStorage(@@ -980,20 +1054,27 @@ export default function FilePreviewPanel({(handledReveal?.path === relativePath && handledReveal.requestId === revealRequestId);const renderMarkdown = isMarkdown && renderMarkdownPreferred && revealHandled;const renderBrowserFile = isPdf || (isHtml && renderBrowserFilePreferred && revealHandled);- const canToggleRendered = isMarkdown || isHtml;+ const canToggleRendered = attachment === undefined && (isMarkdown || isHtml);const rendered = isMarkdown ? renderMarkdown : renderBrowserFile;const setRenderedPreferred = isMarkdown? setRenderMarkdownPreferred: setRenderBrowserFilePreferred;const canOpenInBrowser =relativePath !== null &&+ attachment === undefined &&!isVideo &&isPreviewSupportedInRuntime() &&isBrowserPreviewFile(relativePath);- const absolutePath = relativePath ? resolvePathLinkTarget(relativePath, cwd) : null;+ const absolutePath =+ relativePath && attachment === undefined ? resolvePathLinkTarget(relativePath, cwd) : null;const onFilePostRender = useFileLineReveal(relativePath, revealLine, revealRequestId);useWorkspaceMutationRefresh({- enabled: relativePath !== null && !isMedia && !isPdf && !selectedFilePending,+ enabled:+ attachment === undefined &&+ relativePath !== null &&+ !isMedia &&+ !isPdf &&+ !selectedFilePending,mutationId: workspaceMutationId,refresh: file.refresh,resourceKey: `file:${environmentId}:${cwd}:${relativePath ?? ""}`,@@ -1050,24 +1131,36 @@ export default function FilePreviewPanel({className="flex h-10 min-h-10 shrink-0 items-center gap-2 border-b border-border/60 bg-background px-3 in-data-[preview-panel-mode=inline]:mb-3 in-data-[preview-panel-mode=inline]:h-7 in-data-[preview-panel-mode=inline]:min-h-7 in-data-[preview-panel-mode=inline]:border-b-transparent"data-surface-subheader>- <ScrollArea- ref={breadcrumbRef}- hideScrollbars- scrollFade- className="min-w-0 flex-1 rounded-none"- data-file-breadcrumbs- >- <div className="flex h-full w-max min-w-full items-center text-xs">- <FileBreadcrumbs- cwd={cwd}- environmentId={environmentId}- onOpenFile={onOpenFile}- projectName={projectName}- relativePath={relativePath}- workspaceMutationId={workspaceMutationId}+ {attachment ? (+ <div className="flex min-w-0 flex-1 items-center gap-1.5 text-xs">+ <PierreEntryIcon+ pathValue={attachment.name}+ kind="file"+ theme={resolvedTheme}+ className="size-3.5"/>+ <span className="truncate font-medium">{attachment.name}</span></div>- </ScrollArea>+ ) : (+ <ScrollArea+ ref={breadcrumbRef}+ hideScrollbars+ scrollFade+ className="min-w-0 flex-1 rounded-none"+ data-file-breadcrumbs+ >+ <div className="flex h-full w-max min-w-full items-center text-xs">+ <FileBreadcrumbs+ cwd={cwd}+ environmentId={environmentId}+ onOpenFile={onOpenFile}+ projectName={projectName}+ relativePath={relativePath}+ workspaceMutationId={workspaceMutationId}+ />+ </div>+ </ScrollArea>+ )}{absolutePath &&(environmentId === primaryEnvironmentId || remoteOpenState.mode !== "local-exec") ? (<OpenInPicker@@ -1124,25 +1217,27 @@ export default function FilePreviewPanel({<TooltipPopup>Open file in preview browser</TooltipPopup></Tooltip>) : null}- <Tooltip>- <TooltipTrigger- render={- <Toggle- className="shrink-0"- pressed={explorerOpen}- onPressedChange={toggleExplorer}- aria-label={explorerOpen ? "Hide file explorer" : "Show file explorer"}- variant="ghost"- size="sm"- >- <FolderTree className="size-3.5" />- </Toggle>- }- />- <TooltipPopup>- {explorerOpen ? "Hide file explorer" : "Show file explorer"}- </TooltipPopup>- </Tooltip>+ {!isHostFile ? (+ <Tooltip>+ <TooltipTrigger+ render={+ <Toggle+ className="shrink-0"+ pressed={explorerOpen}+ onPressedChange={toggleExplorer}+ aria-label={explorerOpen ? "Hide file explorer" : "Show file explorer"}+ variant="ghost"+ size="sm"+ >+ <FolderTree className="size-3.5" />+ </Toggle>+ }+ />+ <TooltipPopup>+ {explorerOpen ? "Hide file explorer" : "Show file explorer"}+ </TooltipPopup>+ </Tooltip>+ ) : null}</div>) : null}{relativePath && !isMedia && !renderBrowserFile && file.data?.truncated ? (@@ -1157,7 +1252,9 @@ export default function FilePreviewPanel({relativePath ? "flex" : "hidden",)}>- {relativePath && isVideo && absolutePath ? (+ {relativePath && attachment ? (+ <AttachmentBrowserPreview environmentId={environmentId} attachment={attachment} />+ ) : relativePath && isVideo && absolutePath ? (<WorkspaceVideoPreviewkey={`${environmentId}:${threadRef.threadId}:${absolutePath}`}environmentId={environmentId}@@ -1250,7 +1347,7 @@ export default function FilePreviewPanel({)) : null}</div>- {explorerOpen || relativePath === null ? (+ {showExplorer ? (<asideclassName={cn("flex min-h-0 shrink-0 bg-background",diff --git a/apps/web/src/components/files/filePreviewMode.ts b/apps/web/src/components/files/filePreviewMode.tsindex 63249dbc72f..9770d36fa2c 100644--- a/apps/web/src/components/files/filePreviewMode.ts+++ b/apps/web/src/components/files/filePreviewMode.ts@@ -1,5 +1,18 @@+import { isAbsolutePath } from "~/terminal-links";+export const isMarkdownPreviewFile = (path: string): boolean => /\.(?:md|mdx)$/i.test(path);+export function shouldShowFileExplorer(input: {+ readonly relativePath: string | null;+ readonly explorerOpen: boolean;+ readonly attachmentOpen: boolean;+}): boolean {+ if (input.attachmentOpen || (input.relativePath && isAbsolutePath(input.relativePath))) {+ return false;+ }+ return input.explorerOpen || input.relativePath === null;+}+export function setMarkdownTaskChecked(markdown: string,markerOffset: number,diff --git a/apps/web/src/rightPanelStore.test.ts b/apps/web/src/rightPanelStore.test.tsindex 04620c64ed7..7f981f2bcda 100644--- a/apps/web/src/rightPanelStore.test.ts+++ b/apps/web/src/rightPanelStore.test.ts@@ -279,6 +279,50 @@ describe("rightPanelStore", () => {});});+ it("opens an attachment as a file surface without the standalone explorer", () => {+ const attachment = {+ type: "file" as const,+ id: "thread-A-attachment-pdf",+ name: "report.pdf",+ mimeType: "application/pdf",+ sizeBytes: 42,+ };+ useRightPanelStore.getState().open(refA, "files");+ useRightPanelStore.getState().openAttachment(refA, attachment);++ expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({+ isOpen: true,+ activeSurfaceId: "attachment:thread-A-attachment-pdf",+ surfaces: [+ {+ id: "attachment:thread-A-attachment-pdf",+ kind: "file",+ relativePath: "report.pdf",+ revealLine: null,+ revealRequestId: 0,+ attachment,+ },+ ],+ });+ });++ it("keeps attachment and workspace file ids disjoint", () => {+ useRightPanelStore.getState().openFile(refA, "attachment:shared-id");+ useRightPanelStore.getState().openAttachment(refA, {+ type: "file",+ id: "shared-id",+ name: "report.pdf",+ mimeType: "application/pdf",+ sizeBytes: 42,+ });++ expect(+ selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA).surfaces.map(+ (surface) => surface.id,+ ),+ ).toEqual(["file:attachment:shared-id", "attachment:shared-id"]);+ });+it("updates line reveal requests when reopening a file surface", () => {useRightPanelStore.getState().openFile(refA, "src/index.ts", 42);useRightPanelStore.getState().openFile(refA, "src/index.ts", 87);@@ -336,6 +380,35 @@ describe("rightPanelStore", () => {});});+ it("keeps attachment previews when their workspace is unavailable", () => {+ const attachment = {+ type: "file" as const,+ id: "thread-A-attachment-pdf",+ name: "report.pdf",+ mimeType: "application/pdf",+ sizeBytes: 42,+ };+ useRightPanelStore.getState().openFile(refA, "README.md");+ useRightPanelStore.getState().openAttachment(refA, attachment);++ useRightPanelStore.getState().reconcileFileSurfaces(refA, false);++ expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({+ isOpen: true,+ activeSurfaceId: "attachment:thread-A-attachment-pdf",+ surfaces: [+ {+ id: "attachment:thread-A-attachment-pdf",+ kind: "file",+ relativePath: "report.pdf",+ revealLine: null,+ revealRequestId: 0,+ attachment,+ },+ ],+ });+ });+it("close hides the panel without clearing its selected surface", () => {useRightPanelStore.getState().open(refA, "agents");useRightPanelStore.getState().close(refA);diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.tsindex 2c70c884467..bc7da2d5a9e 100644--- a/apps/web/src/rightPanelStore.ts+++ b/apps/web/src/rightPanelStore.ts@@ -8,7 +8,7 @@* workspace paths, and diff/files remain singleton surfaces.*/import { scopedThreadKey } from "@t3tools/client-runtime/environment";-import type { ScopedThreadRef } from "@t3tools/contracts";+import type { ChatFileAttachment, ScopedThreadRef } from "@t3tools/contracts";import { create } from "zustand";import { createJSONStorage, persist } from "zustand/middleware";@@ -39,12 +39,15 @@ export type RightPanelSurface =| { id: "diff"; kind: "diff" }| { id: "files"; kind: "files" }| {- id: `file:${string}`;+ id: `file:${string}` | `attachment:${string}`;kind: "file";/** Workspace-relative, or absolute for a host file outside the workspace. */relativePath: string;revealLine: number | null;revealRequestId: number;+ /** Present when the file lives in the thread's attachment store rather+ than at a workspace or host path. */+ attachment?: ChatFileAttachment;}| {/**@@ -91,6 +94,7 @@ interface RightPanelStoreState {) => void;openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;openFile: (ref: ScopedThreadRef, relativePath: string, line?: number) => void;+ openAttachment: (ref: ScopedThreadRef, attachment: ChatFileAttachment) => void;openPullRequest: (ref: ScopedThreadRef,target: { environmentId?: string; projectId: string; repository: string; number: number },@@ -157,6 +161,15 @@ const fileSurface = (revealRequestId,});+const attachmentSurface = (attachment: ChatFileAttachment): RightPanelSurface => ({+ id: `attachment:${attachment.id}`,+ kind: "file",+ relativePath: attachment.name,+ revealLine: null,+ revealRequestId: 0,+ attachment,+});+const terminalSurface = (terminalId: string): RightPanelSurface => ({id: `terminal:${terminalId}`,kind: "terminal",@@ -401,6 +414,18 @@ export const useRightPanelStore = create<RightPanelStoreState>()(};}),})),+ openAttachment: (ref, attachment) =>+ set((state) => ({+ byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {+ const withoutStandaloneExplorer = current.surfaces.filter(+ (surface) => surface.kind !== "files",+ );+ return upsertSurface(+ { ...current, surfaces: withoutStandaloneExplorer },+ attachmentSurface(attachment),+ );+ }),+ })),openTerminal: (ref, terminalId) =>set((state) => ({byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>@@ -577,7 +602,9 @@ export const useRightPanelStore = create<RightPanelStoreState>()(byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {if (workspaceAvailable) return current;const surfaces = current.surfaces.filter(- (surface) => surface.kind !== "files" && surface.kind !== "file",+ (surface) =>+ surface.kind !== "files" &&+ (surface.kind !== "file" || surface.attachment !== undefined),);if (surfaces.length === current.surfaces.length) return current;const activeStillExists = surfaces.some(diff --git a/apps/web/src/types.ts b/apps/web/src/types.tsindex 8638cade733..bb616585d1b 100644--- a/apps/web/src/types.ts+++ b/apps/web/src/types.ts@@ -66,6 +66,15 @@ export function isVideoAttachment(attachment: ChatFileAttachment): boolean {return videoMimeType(attachment) !== null;}+export function isBrowserPreviewAttachment(attachment: ChatFileAttachment): boolean {+ const mimeType = attachment.mimeType.split(";", 1)[0]?.trim().toLowerCase();+ return (+ /\.(?:html?|pdf)$/i.test(attachment.name) ||+ mimeType === "application/pdf" ||+ mimeType === "text/html"+ );+}+export interface ChatMessage extends Omit<OrchestrationMessage, "attachments"> {readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;}diff --git a/docs/user/composer.md b/docs/user/composer.mdindex eea5a658a33..13b4527ad26 100644--- a/docs/user/composer.md+++ b/docs/user/composer.md@@ -31,6 +31,9 @@ Use Share to save a copy or send it to another app. PDFs support page navigationPDF links in assistant responses open the same preview. On Android, images open in the imageviewer and PDFs open the system chooser.+On web and desktop, select a sent PDF or HTML attachment to open it in the file viewer, or use the+download button beside it to save a copy. Other attached files download when selected.+Select a video attachment before or after sending to play it. Web and desktop use the browser'sbuilt-in controls. On mobile, videos open in a full-screen player with native playback controls.Supported videos show a thumbnail in the conversation and composer.@@ -133,10 +136,10 @@ are not supported; use the Markdown embed syntax above.When an agent links to a file it wrote outside the workspace, such as a Markdown report in`/tmp`, select the link to open it in the file viewer. The viewer shows the file read-only, with-rendered Markdown available as usual; it cannot edit files outside the workspace. HTML and PDF-files outside the workspace open the same way as ones inside it. Because such a file is served on-its own, an HTML page outside the workspace cannot load scripts, styles, or images from files beside-it.+rendered Markdown available as usual; it cannot edit files outside the workspace. The workspace+file tree stays hidden because it does not describe the open file. HTML and PDF files outside the+workspace open the same way as ones inside it. Because such a file is served on its own, an HTML+page outside the workspace cannot load scripts, styles, or images from files beside it.## HTML and PDF files in the file viewerdiff --git a/packages/contracts/src/assets.ts b/packages/contracts/src/assets.tsindex e944bd71eb1..9859a8594a6 100644--- a/packages/contracts/src/assets.ts+++ b/packages/contracts/src/assets.ts@@ -30,6 +30,9 @@ export const AssetResource = Schema.Union([an octet-stream download without a filename. */fileName: Schema.optionalKey(TrimmedNonEmptyString.check(Schema.isMaxLength(255))),mimeType: Schema.optionalKey(TrimmedNonEmptyString.check(Schema.isMaxLength(100))),+ /** Generic attachments download by default. Document viewers opt into an+ inline response after deciding the file type is safe to preview. */+ disposition: Schema.optionalKey(Schema.Literals(["inline", "attachment"])),}),Schema.TaggedStruct("project-favicon", {cwd: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),