Skip to content

Commit d3f0821

Browse files
Julius Marmingeclaude
andcommitted
feat(web): preview document attachments in the file viewer
Sent PDF and HTML attachments could only be downloaded. Clicking one now opens it in the right-panel file viewer, with a download button beside it. Other attachments download as before. The attachment resource gains a disposition field so a document viewer can ask for an inline response; generic attachments still download by default and the server honors inline only for PDF and HTML. The file viewer takes an optional attachment and hides the workspace tree, breadcrumbs, and editor affordances for it. Attachment surfaces use their own id namespace so they never collide with a workspace file at a matching path. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 2971ec3 commit d3f0821

16 files changed

Lines changed: 491 additions & 97 deletions

‎apps/server/src/assets/AssetAccess.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -576,6 +576,39 @@ describe("AssetAccess", () => {
576576
});
577577
}).pipe(Effect.provide(testLayer)),
578578
);
579+
580+
it.effect("serves document attachments inline when a viewer requests it", () =>
581+
Effect.gen(function* () {
582+
const config = yield* ServerConfig.ServerConfig;
583+
const fileSystem = yield* FileSystem.FileSystem;
584+
const path = yield* Path.Path;
585+
const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001-pdf";
586+
const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.pdf`);
587+
yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
588+
yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
589+
590+
const result = yield* issueAssetUrl({
591+
resource: {
592+
_tag: "attachment",
593+
attachmentId,
594+
fileName: "report.pdf",
595+
mimeType: "application/pdf",
596+
disposition: "inline",
597+
},
598+
});
599+
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
600+
const separatorIndex = suffix.indexOf("/");
601+
602+
expect(
603+
yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
604+
).toEqual({
605+
kind: "file",
606+
path: attachmentPath,
607+
fileName: "report.pdf",
608+
mimeType: "application/pdf",
609+
});
610+
}).pipe(Effect.provide(testLayer)),
611+
);
579612
it.effect("issues project favicon capabilities with a signed fallback", () =>
580613
Effect.gen(function* () {
581614
const fileSystem = yield* FileSystem.FileSystem;

‎apps/server/src/assets/AssetAccess.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -362,15 +362,18 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
362362
}
363363
// Generic files carry their extension inside the attachment id (that
364364
// shape resolves the on-disk path); images do not. Videos and images
365-
// render inline; other generic files download.
365+
// render inline. Other generic files download unless a document viewer
366+
// explicitly requested an inline response.
366367
const isGenericFile = parseAttachmentFileExtension(input.resource.attachmentId) !== null;
367368
const videoMimeType = input.resource.mimeType?.split(";", 1)[0]?.trim() ?? "";
368369
const isVideo = INLINE_VIDEO_MIME_TYPE_PATTERN.test(videoMimeType);
369370
claims = {
370371
version: 1,
371372
kind: "attachment",
372373
attachmentId: input.resource.attachmentId,
373-
...(isGenericFile && !isVideo ? { download: true } : {}),
374+
...(isGenericFile && !isVideo && input.resource.disposition !== "inline"
375+
? { download: true }
376+
: {}),
374377
...(input.resource.fileName !== undefined ? { fileName: input.resource.fileName } : {}),
375378
...(input.resource.mimeType !== undefined
376379
? { mimeType: isVideo ? videoMimeType : input.resource.mimeType }

‎apps/server/src/http.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,19 @@ describe("assetResponseHeaders", () => {
324324
"X-Content-Type-Options": "nosniff",
325325
});
326326
});
327+
it("serves inline attachment documents with their declared mime type", () => {
328+
expect(
329+
assetResponseHeaders("/attachments/upload.bin", { mimeType: "application/pdf" }),
330+
).toMatchObject({
331+
"Content-Type": "application/pdf",
332+
});
333+
expect(
334+
assetResponseHeaders("/attachments/upload.bin", { mimeType: "text/html" }),
335+
).toMatchObject({
336+
"Content-Type": "text/html; charset=utf-8",
337+
"Content-Security-Policy": "sandbox allow-scripts allow-forms allow-popups allow-modals",
338+
});
339+
});
327340
it("serves HTML assets as utf-8 inside a sandboxed origin", () => {
328341
for (const path of ["/workspace/page.html", "/workspace/PAGE.HTM", "/tmp/report.html"]) {
329342
expect(assetResponseHeaders(path)).toMatchObject({

‎apps/server/src/http.ts‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@ const isSafeDownloadMimeType = (mimeType: string): boolean =>
6464
!/(?:^text\/html$|\/xml(?:$|-)|\+xml$)/i.test(mimeType.trim().toLowerCase());
6565
const isSafeInlineVideoMimeType = (mimeType: string): boolean =>
6666
DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) && mimeType.toLowerCase().startsWith("video/");
67+
const isSafeInlineDocumentMimeType = (mimeType: string): boolean =>
68+
mimeType.toLowerCase() === "application/pdf" || mimeType.toLowerCase() === "text/html";
6769

6870
/** RFC 6266 disposition with an ASCII fallback name plus a UTF-8 `filename*`. */
6971
export function downloadContentDisposition(fileName?: string): string {
@@ -93,7 +95,7 @@ export function assetResponseHeaders(
9395
},
9496
): Record<string, string> {
9597
const lowerPath = filePath.toLowerCase();
96-
const inlineVideoMimeType = options?.mimeType?.split(";", 1)[0]?.trim();
98+
const inlineMimeType = options?.mimeType?.split(";", 1)[0]?.trim();
9799
return {
98100
"Cache-Control": "private, max-age=3600",
99101
"X-Content-Type-Options": "nosniff",
@@ -106,14 +108,24 @@ export function assetResponseHeaders(
106108
? options.mimeType
107109
: "application/octet-stream",
108110
}
109-
: inlineVideoMimeType !== undefined && isSafeInlineVideoMimeType(inlineVideoMimeType)
110-
? { "Content-Type": inlineVideoMimeType }
111-
: lowerPath.endsWith(".html") || lowerPath.endsWith(".htm")
111+
: inlineMimeType !== undefined && isSafeInlineVideoMimeType(inlineMimeType)
112+
? { "Content-Type": inlineMimeType }
113+
: inlineMimeType !== undefined && isSafeInlineDocumentMimeType(inlineMimeType)
112114
? {
113-
"Content-Type": "text/html; charset=utf-8",
114-
"Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY,
115+
"Content-Type":
116+
inlineMimeType.toLowerCase() === "text/html"
117+
? "text/html; charset=utf-8"
118+
: "application/pdf",
119+
...(inlineMimeType.toLowerCase() === "text/html"
120+
? { "Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY }
121+
: {}),
115122
}
116-
: {}),
123+
: lowerPath.endsWith(".html") || lowerPath.endsWith(".htm")
124+
? {
125+
"Content-Type": "text/html; charset=utf-8",
126+
"Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY,
127+
}
128+
: {}),
117129
...(!options?.download && lowerPath.endsWith(".svg")
118130
? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY }
119131
: {}),

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ import {
132132
DEFAULT_THREAD_TERMINAL_ID,
133133
MAX_TERMINALS_PER_GROUP,
134134
type ChatMessage,
135+
isBrowserPreviewAttachment,
135136
isImageAttachment,
136137
videoMimeType,
137138
type SessionPhase,
@@ -2602,7 +2603,7 @@ function ChatViewContent(props: ChatViewProps) {
26022603
});
26032604
}, []);
26042605
const serverMessages = activeThread?.messages;
2605-
const openFileAttachment = useCallback(
2606+
const downloadFileAttachment = useCallback(
26062607
async (attachment: ChatFileAttachment) => {
26072608
const connection = readPreparedConnection(environmentId);
26082609
if (!connection) {
@@ -2654,6 +2655,16 @@ function ChatViewContent(props: ChatViewProps) {
26542655
},
26552656
[createAttachmentAssetUrl, environmentId, routeThreadKey],
26562657
);
2658+
const openFileAttachment = useCallback(
2659+
(attachment: ChatFileAttachment) => {
2660+
if (isBrowserPreviewAttachment(attachment) && activeThreadRef) {
2661+
useRightPanelStore.getState().openAttachment(activeThreadRef, attachment);
2662+
return;
2663+
}
2664+
void downloadFileAttachment(attachment);
2665+
},
2666+
[activeThreadRef, downloadFileAttachment],
2667+
);
26572668
const serverAttachmentIds = useMemo(() => {
26582669
const attachmentIds = new Set<string>();
26592670
for (const message of serverMessages ?? []) {
@@ -7351,14 +7362,18 @@ function ChatViewContent(props: ChatViewProps) {
73517362
/>
73527363
) : (renderedRightPanelSurface?.kind === "files" ||
73537364
renderedRightPanelSurface?.kind === "file") &&
7354-
activeProject &&
7355-
activeWorkspaceRoot ? (
7365+
((activeProject && activeWorkspaceRoot) ||
7366+
(renderedRightPanelSurface.kind === "file" && renderedRightPanelSurface.attachment)) ? (
73567367
<Suspense fallback={null}>
73577368
<FilePreviewPanel
7358-
key={`${activeProject.environmentId}:${activeWorkspaceRoot}`}
7359-
environmentId={activeProject.environmentId}
7360-
cwd={activeWorkspaceRoot}
7361-
projectName={activeProject.title}
7369+
key={`${activeThread.environmentId}:${
7370+
renderedRightPanelSurface.kind === "file" && renderedRightPanelSurface.attachment
7371+
? `attachment:${renderedRightPanelSurface.attachment.id}`
7372+
: activeWorkspaceRoot
7373+
}`}
7374+
environmentId={activeThread.environmentId}
7375+
cwd={activeWorkspaceRoot ?? ""}
7376+
projectName={activeProject?.title ?? ""}
73627377
threadRef={activeThreadRef}
73637378
composerDraftTarget={composerDraftTarget}
73647379
keybindings={keybindings}
@@ -7368,6 +7383,9 @@ function ChatViewContent(props: ChatViewProps) {
73687383
? renderedRightPanelSurface.relativePath
73697384
: null
73707385
}
7386+
{...(renderedRightPanelSurface.kind === "file" && renderedRightPanelSurface.attachment
7387+
? { attachment: renderedRightPanelSurface.attachment }
7388+
: {})}
73717389
revealLine={
73727390
renderedRightPanelSurface.kind === "file"
73737391
? (renderedRightPanelSurface.revealLine ?? null)
@@ -7508,6 +7526,7 @@ function ChatViewContent(props: ChatViewProps) {
75087526
isRevertingCheckpoint={isRevertingCheckpoint}
75097527
onImageExpand={onExpandTimelineImage}
75107528
onFileOpen={openFileAttachment}
7529+
onFileDownload={downloadFileAttachment}
75117530
openingVideoAttachmentId={openingVideoAttachmentId}
75127531
markdownCwd={gitCwd ?? undefined}
75137532
resolvedTheme={resolvedTheme}

‎apps/web/src/components/RightPanelTabs.tsx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -793,7 +793,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
793793
if (surfaceIndex < 0) return;
794794

795795
const items: ContextMenuItem<TabContextMenuAction>[] = [];
796-
if (surface.kind === "file") {
796+
if (surface.kind === "file" && surface.attachment === undefined) {
797797
items.push({ id: "copy-path", label: "Copy path" });
798798
}
799799
const menuPreviewTabId = previewTabIdOf(surface, props.previewSessions);
@@ -837,7 +837,9 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
837837
const action = await api.contextMenu.show(items, { x: event.clientX, y: event.clientY });
838838
switch (action) {
839839
case "copy-path":
840-
if (surface.kind === "file") props.onCopyFilePath(surface.relativePath);
840+
if (surface.kind === "file" && surface.attachment === undefined) {
841+
props.onCopyFilePath(surface.relativePath);
842+
}
841843
break;
842844
case "toggle-mute": {
843845
// menuOverlay repeats the disabled gate above: the desktop tab must

‎apps/web/src/components/chat/MessagesTimeline.test.tsx‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -437,7 +437,7 @@ describe("MessagesTimeline", () => {
437437
expect(resolveTimelineMinimapInteractiveWidth(40, true)).toBe("22rem");
438438
});
439439

440-
it("renders generic attachments as download links instead of image previews", () => {
440+
it("gives browser documents separate preview and download controls", () => {
441441
const entry = {
442442
...buildUserTimelineEntry("Read the report."),
443443
message: {
@@ -459,9 +459,9 @@ describe("MessagesTimeline", () => {
459459
<MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
460460
);
461461

462-
expect(markup).toContain(
463-
'<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">',
464-
);
462+
expect(markup).toContain('aria-label="Preview report.pdf"');
463+
expect(markup).toContain('aria-label="Download report.pdf"');
464+
expect(markup).not.toContain('download="report.pdf"');
465465
expect(markup).not.toContain('alt="report.pdf"');
466466
});
467467

@@ -502,7 +502,7 @@ describe("MessagesTimeline", () => {
502502
expect(busyMarkup).not.toContain('disabled=""');
503503
expect(busyMarkup).toContain(">Loading…</span>");
504504
});
505-
it("renders a file download button without creating its URL in advance", () => {
505+
it("renders an ordinary file download button without creating its URL in advance", () => {
506506
const entry = {
507507
...buildUserTimelineEntry("Read the report."),
508508
message: {
@@ -511,8 +511,8 @@ describe("MessagesTimeline", () => {
511511
{
512512
type: "file" as const,
513513
id: "attachment-report-pdf",
514-
name: "report.pdf",
515-
mimeType: "application/pdf",
514+
name: "archive.zip",
515+
mimeType: "application/zip",
516516
sizeBytes: 42,
517517
},
518518
],
@@ -524,9 +524,9 @@ describe("MessagesTimeline", () => {
524524
);
525525

526526
expect(markup).toContain(
527-
'<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">',
527+
'<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">',
528528
);
529-
expect(markup).not.toContain("href=");
529+
expect(markup).not.toContain("<a href=");
530530
});
531531

532532
it("does not download an optimistic file before the server supplies its attachment ID", () => {
@@ -581,7 +581,7 @@ describe("MessagesTimeline", () => {
581581
expect(markup).toContain("voice-memo.ogg");
582582
expect(markup).not.toContain('aria-label="Download voice-memo.ogg"');
583583
expect(markup).not.toContain('alt="voice-memo.ogg"');
584-
expect(markup).not.toContain("href=");
584+
expect(markup).not.toContain("<a href=");
585585
});
586586

587587
it("keeps reserved end space when tool work starts while reading history", () => {

0 commit comments

Comments
 (0)