Skip to content
TypeScript

feat(web): attach svg files to messages (#21355)

mariaefea68679fac
diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts
index d3eb0e05154..89c37228d8f 100644
--- a/apps/server/src/assets/AssetAccess.test.ts
+++ b/apps/server/src/assets/AssetAccess.test.ts
@@ -979,6 +979,44 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(layerTest)),
);
+ 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;
+ yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
+ for (const [extension, mimeType] of [
+ ["pdf", "application/pdf"],
+ ["svg", "image/svg+xml"],
+ ] as const) {
+ const attachmentId = `thread-1-00000000-0000-4000-8000-000000000001-${extension}`;
+ const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.${extension}`);
+ yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
+
+ const result = yield* issueAssetUrl({
+ resource: {
+ _tag: "attachment",
+ attachmentId,
+ fileName: `report.${extension}`,
+ mimeType,
+ 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.${extension}`,
+ mimeType,
+ });
+ }
+ }).pipe(Effect.provide(layerTest)),
+ );
+
it.effect("keeps inline requests for other attachment types as downloads", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts
index 242562baf80..934fc9530a1 100644
--- a/apps/server/src/assets/AssetAccess.ts
+++ b/apps/server/src/assets/AssetAccess.ts
@@ -82,6 +82,7 @@ const PROJECT_FAVICON_ICNS_MIN_SIZE = 96;
const INLINE_VIDEO_MIME_TYPE_PATTERN = /^video\/[\w!#$&^.+-]+$/i;
// Use server-assigned attachment extensions, never client MIME types.
const INLINE_PREVIEW_MIME_TYPES: Record<string, string> = {
+ svg: "image/svg+xml",
pdf: "application/pdf",
html: "text/html",
htm: "text/html",
diff --git a/apps/server/src/assets/AttachmentUpload.test.ts b/apps/server/src/assets/AttachmentUpload.test.ts
index 1eb60a1544b..85433315ff4 100644
--- a/apps/server/src/assets/AttachmentUpload.test.ts
+++ b/apps/server/src/assets/AttachmentUpload.test.ts
@@ -4,6 +4,7 @@ import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
+import { ChatAttachmentId } from "@t3tools/contracts";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
@@ -14,6 +15,10 @@ import * as Stream from "effect/Stream";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { base64UrlEncode, signPayload } from "../auth/utils.ts";
import * as ServerConfig from "../config.ts";
+import {
+ claimPendingAttachments,
+ releaseClaimedAttachments,
+} from "../orchestration-v2/AttachmentClaims.ts";
import {
ATTACHMENT_UPLOAD_ROUTE_PREFIX,
deletePendingAttachment,
@@ -139,6 +144,47 @@ describe("AttachmentUpload", () => {
}).pipe(Effect.provide(layerTest)),
);
+ it.effect("stores MIME-identified SVG files with a previewable signed extension", () =>
+ Effect.gen(function* () {
+ const config = yield* ServerConfig.ServerConfig;
+ const bytes = new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"/>');
+ for (const name of ["diagram", "diagram.bin"]) {
+ const issued = yield* issueAttachmentUploadUrl({
+ type: "file",
+ name,
+ mimeType: "image/svg+xml",
+ sizeBytes: bytes.length,
+ });
+ const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
+ const claims = yield* validateAttachmentUploadToken(token);
+ if (!claims) throw new Error("Expected valid SVG upload claims.");
+ expect(claims.name).toBe(`${name}.svg`);
+ expect(issued.attachmentId).toMatch(/-svg$/);
+ expect(yield* storeAttachmentUpload(claims, bytes)).toEqual({ ok: true });
+ expect(
+ NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${issued.attachmentId}.svg`)),
+ ).toEqual(Buffer.from(bytes));
+ const claimed = yield* claimPendingAttachments({
+ threadId: "svg-upload-thread",
+ attachments: [
+ {
+ type: "file",
+ id: ChatAttachmentId.make(issued.attachmentId),
+ name,
+ mimeType: "image/svg+xml",
+ sizeBytes: bytes.length,
+ },
+ ],
+ });
+ expect(claimed.attachments[0]?.name).toBe(`${name}.svg`);
+ expect(NodeFS.readFileSync(claimed.claimedPaths[0]!)).toEqual(Buffer.from(bytes));
+ yield* releaseClaimedAttachments(claimed.claimedPaths);
+ yield* deletePendingAttachment(issued.attachmentId);
+ }
+ expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([]);
+ }).pipe(Effect.provide(layerTest)),
+ );
+
it.effect("removes partial streamed uploads that exceed their signed size", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
diff --git a/apps/server/src/assets/AttachmentUpload.ts b/apps/server/src/assets/AttachmentUpload.ts
index efbe6a5ba6a..d0121486b39 100644
--- a/apps/server/src/assets/AttachmentUpload.ts
+++ b/apps/server/src/assets/AttachmentUpload.ts
@@ -3,6 +3,7 @@ import {
type AttachmentCreateUploadUrlInput,
AttachmentUploadSigningKeyError,
} from "@t3tools/contracts";
+import { isSvgAttachment } from "@t3tools/shared/image";
import * as Clock from "effect/Clock";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
@@ -93,8 +94,12 @@ export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(f
}
const attachmentType = input.type ?? "image";
+ const name =
+ attachmentType === "file" && isSvgAttachment(input) && !/\.svg$/i.test(input.name)
+ ? `${input.name}.svg`
+ : input.name;
const attachmentId = createPendingAttachmentId(
- attachmentType === "file" ? attachmentFileExtension(input.name) : undefined,
+ attachmentType === "file" ? attachmentFileExtension(name) : undefined,
);
const expiresAt = nowMs + ATTACHMENT_UPLOAD_URL_TTL_MS;
const encodedPayload = base64UrlEncode(
@@ -103,7 +108,7 @@ export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(f
kind: "attachment-upload",
type: attachmentType,
attachmentId,
- name: input.name,
+ name,
mimeType: input.mimeType,
sizeBytes: input.sizeBytes,
expiresAt,
diff --git a/apps/server/src/orchestration-v2/AttachmentClaims.ts b/apps/server/src/orchestration-v2/AttachmentClaims.ts
index e20d18014bf..b752fb00b7a 100644
--- a/apps/server/src/orchestration-v2/AttachmentClaims.ts
+++ b/apps/server/src/orchestration-v2/AttachmentClaims.ts
@@ -6,6 +6,7 @@ import {
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
+import { isSvgAttachment } from "@t3tools/shared/image";
import {
parseThreadSegmentFromAttachmentId,
@@ -106,6 +107,12 @@ export const claimPendingAttachments = Effect.fn("AttachmentClaims.claimPendingA
const normalized: ChatAttachment = {
...attachment,
id: ChatAttachmentId.make(claim.finalId),
+ name:
+ attachment.type === "file" &&
+ isSvgAttachment(attachment) &&
+ !/\.svg$/i.test(attachment.name)
+ ? `${attachment.name}.svg`
+ : attachment.name,
mimeType: attachment.mimeType.toLowerCase(),
};
const expectedPath = resolveAttachmentPath({
diff --git a/apps/web/src/components/chat/UserMessageContextChips.tsx b/apps/web/src/components/chat/UserMessageContextChips.tsx
index cc5474c3790..6d9c566c52f 100644
--- a/apps/web/src/components/chat/UserMessageContextChips.tsx
+++ b/apps/web/src/components/chat/UserMessageContextChips.tsx
@@ -1,3 +1,4 @@
+import { isSvgAttachment } from "@t3tools/shared/image";
import { useRenderedAppearance } from "../../hooks/useTheme";
import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
import { ReadOnlySourcePreview } from "../files/AttachmentFilePreview";
@@ -268,6 +269,7 @@ function UserMessageElementDetails({
}
interface UserMessageContextRenderContext {
+ environmentId: import("@t3tools/contracts").EnvironmentId;
reference: ChatMarkdownContextReference;
annotationImage: ChatImageAttachment | null;
attachment: ChatImageAttachment | ChatFileAttachment | null;
@@ -378,6 +380,11 @@ const userMessageContextPresentationRegistry = createContextPresentationRegistry
return (
<FileChip
name={record.name}
+ svgPreview={
+ isSvgAttachment(attachment)
+ ? { environmentId: context.environmentId, attachmentId: attachment.id }
+ : undefined
+ }
size={size}
isVideo={isVideo}
theme={context.resolvedTheme}
@@ -509,13 +516,14 @@ export function UserMessageContextReferenceChip(props: {
onExpandVideo: (file: ChatFileAttachment) => void;
onOpenFile: (file: ChatFileAttachment) => void;
}) {
- const { resolvedTheme } = use(TimelineRowCtx);
+ const { resolvedTheme, activeThreadEnvironmentId } = use(TimelineRowCtx);
const copyMarkdown = formatComposerContextReference({
kind: props.reference.kind,
contextId: props.reference.contextId as ComposerContextId,
label: props.reference.label,
});
return userMessageContextPresentationRegistry.render(props.reference.kind, props.record, {
+ environmentId: activeThreadEnvironmentId,
reference: props.reference,
annotationImage: props.annotationImage,
attachment: props.attachment,
diff --git a/apps/web/src/components/chat/composerAttachmentFiles.test.ts b/apps/web/src/components/chat/composerAttachmentFiles.test.ts
index 39477442bd2..38096eb034c 100644
--- a/apps/web/src/components/chat/composerAttachmentFiles.test.ts
+++ b/apps/web/src/components/chat/composerAttachmentFiles.test.ts
@@ -18,6 +18,22 @@ import {
} from "./composerAttachmentFiles";
describe("composer attachment files", () => {
+ it("attaches SVG as a file and rejects other unsupported images", () => {
+ expect(classifyComposerAttachmentFile({ name: "diagram.svg", type: "image/svg+xml" })).toBe(
+ "file",
+ );
+ expect(classifyComposerAttachmentFile({ name: "diagram.SVG", type: "" })).toBe("file");
+ expect(
+ classifyComposerAttachmentFile({ name: "diagram.svg", type: "application/octet-stream" }),
+ ).toBe("file");
+ expect(classifyComposerAttachmentFile({ name: "photo.tiff", type: "image/tiff" })).toBe(
+ "unsupported-image",
+ );
+ expect(classifyComposerAttachmentFile({ name: "report.pdf", type: "application/pdf" })).toBe(
+ "file",
+ );
+ });
+
it("keeps DNG originals on the file path without changing their bytes", async () => {
const bytes = new Uint8Array([0x49, 0x49, 0x2a, 0x00, 0x08, 0, 0, 0, 0xfe, 0xff, 0x00, 0x80]);
const files = [
@@ -96,6 +112,22 @@ describe("composer attachment files", () => {
).toBe(false);
});
+ it("claims SVG and unsupported image pastes even when text is present", () => {
+ const images = [
+ new File(["svg"], "diagram.svg", { type: "image/svg+xml" }),
+ new File(["tiff"], "photo.tiff", { type: "image/tiff" }),
+ ];
+
+ for (const image of images) {
+ expect(
+ shouldHandleComposerAttachmentPaste({
+ files: [image],
+ plainText: "Image caption",
+ }),
+ ).toBe(true);
+ }
+ });
+
it("uses the hard local limit while server config is unknown", () => {
expect(
fileAttachmentStagingLimit({
diff --git a/apps/web/src/components/chat/composerAttachmentFiles.ts b/apps/web/src/components/chat/composerAttachmentFiles.ts
index 6078c4f5b48..7454d1edbb7 100644
--- a/apps/web/src/components/chat/composerAttachmentFiles.ts
+++ b/apps/web/src/components/chat/composerAttachmentFiles.ts
@@ -11,6 +11,7 @@ import {
import type { ComposerFileAttachment, ComposerImageAttachment } from "../../composerDraftStore";
import { isHeicImageFile } from "../../lib/imageCompression";
import { isVideoAttachment, videoMimeType } from "../../types";
+import { isSvgAttachment } from "@t3tools/shared/image";
type ComposerAttachmentFileKind = "image" | "file" | "unsupported-image";
@@ -72,6 +73,7 @@ function isDngFile(file: Pick<File, "name" | "type">): boolean {
export function composerFileAttachmentMimeType(file: Pick<File, "name" | "type">): string {
// Downstream image detection uses MIME, even for attachments staged as files.
if (isDngFile(file)) return "image/x-adobe-dng";
+ if (isSvgAttachment({ name: file.name, mimeType: file.type })) return "image/svg+xml";
return (
videoMimeType({ name: file.name, mimeType: file.type }) ??
(file.type || "application/octet-stream")
@@ -81,6 +83,7 @@ export function composerFileAttachmentMimeType(file: Pick<File, "name" | "type">
export function classifyComposerAttachmentFile(
file: Pick<File, "name" | "type">,
): ComposerAttachmentFileKind {
+ if (isSvgAttachment({ name: file.name, mimeType: file.type })) return "file";
if (isDngFile(file)) return "file";
if (isHeicImageFile(file)) {
return "image";
@@ -164,7 +167,11 @@ export function shouldHandleComposerAttachmentPaste(input: {
input.files.some((file) => {
if (isDngFile(file)) return true;
const classification = classifyComposerAttachmentFile(file);
- return classification === "image" || classification === "unsupported-image";
+ return (
+ classification === "image" ||
+ classification === "unsupported-image" ||
+ isSvgAttachment({ name: file.name, mimeType: file.type })
+ );
})
) {
return true;
diff --git a/apps/web/src/components/composerContextPresentation.tsx b/apps/web/src/components/composerContextPresentation.tsx
index c642a29c89a..c10d53d1fb9 100644
--- a/apps/web/src/components/composerContextPresentation.tsx
+++ b/apps/web/src/components/composerContextPresentation.tsx
@@ -1,4 +1,5 @@
import ChatMarkdown from "./ChatMarkdown";
+import { isSvgAttachment } from "@t3tools/shared/image";
import { ReadOnlySourcePreview } from "./files/AttachmentFilePreview";
import type { PreviewAnnotationPayload, ThreadContextRecord } from "@t3tools/contracts";
import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
@@ -222,6 +223,15 @@ function FileContextChip(props: {
return (
<FileChip
name={props.record.name}
+ svgPreview={
+ isSvgAttachment(props.record)
+ ? {
+ file: props.record.file,
+ environmentId: props.record.uploadEnvironmentId,
+ attachmentId: props.record.uploadedAttachmentId,
+ }
+ : undefined
+ }
size={size}
isVideo={isVideo}
theme={resolvedTheme}
diff --git a/apps/web/src/components/contextChipParts.tsx b/apps/web/src/components/contextChipParts.tsx
index 4260a415127..d6c3b842b5f 100644
--- a/apps/web/src/components/contextChipParts.tsx
+++ b/apps/web/src/components/contextChipParts.tsx
@@ -1,12 +1,14 @@
import type { EnvironmentId, PullRequestContextMetadata } from "@t3tools/contracts";
import { CircleDashedIcon, FilmIcon, ImageIcon } from "lucide-react";
import {
+ useEffect,
useState,
type ComponentProps,
type CSSProperties,
type MouseEvent,
type ReactNode,
} from "react";
+import { useAssetUrlState } from "~/assets/assetUrls";
import { PULL_REQUEST_STATE_PRESENTATION } from "~/components/pullRequest/pullRequestIcons";
import type { PullRequestContextDisplayState } from "~/lib/composerContextRecords";
@@ -167,13 +169,17 @@ export function ImageChipButton({
previewUrl,
size,
suffix,
+ disabled,
+ onPreviewError,
style,
...props
}: Omit<ComponentProps<typeof ContextChip>, "kind" | "render"> & {
name: string;
previewUrl: string | undefined;
size: string;
- suffix?: string | null;
+ suffix?: string | null | undefined;
+ disabled?: boolean | undefined;
+ onPreviewError?: (() => void) | undefined;
}) {
const [sample, setSample] = useState<{ url: string; color: string | undefined }>();
const [corsFailedUrl, setCorsFailedUrl] = useState<string>();
@@ -181,7 +187,7 @@ export function ImageChipButton({
return (
<ContextChip
kind="image"
- render={<button type="button" />}
+ render={<button type="button" disabled={disabled} />}
aria-label={`Image attachment, ${name}, ${size}`}
style={{ ...style, ...(accent ? { "--context-chip-accent": accent } : {}) } as CSSProperties}
{...props}
@@ -193,7 +199,10 @@ export function ImageChipButton({
src={previewUrl}
alt=""
className="size-[1.17em] shrink-0 rounded-sm object-cover"
- onError={() => setCorsFailedUrl(previewUrl)}
+ onError={() => {
+ if (corsFailedUrl === previewUrl) onPreviewError?.();
+ else setCorsFailedUrl(previewUrl);
+ }}
onLoad={(event) =>
setSample({ url: previewUrl, color: averageImageColor(event.currentTarget) })
}
@@ -223,7 +232,15 @@ export function FileChip(props: {
error?: boolean;
unresolved?: boolean;
onOpen?: (() => void) | undefined;
+ svgPreview?:
+ | {
+ file?: Blob | null | undefined;
+ environmentId?: EnvironmentId | undefined;
+ attachmentId?: string | undefined;
+ }
+ | undefined;
}) {
+ if (props.svgPreview && !props.unresolved) return <SvgFileChip {...props} />;
const content = <FileChipContent {...props} />;
const state = props.unresolved
? ("unresolved" as const)
@@ -263,6 +280,65 @@ export function FileChip(props: {
);
}
+function SvgFileChip(props: ComponentProps<typeof FileChip>) {
+ const preview = props.svgPreview;
+ const [local, setLocal] = useState<{ file: Blob; url: string }>();
+ const [failedPreviewUrl, setFailedPreviewUrl] = useState<string>();
+ const asset = useAssetUrlState(
+ preview?.file ? null : (preview?.environmentId ?? null),
+ preview?.attachmentId
+ ? {
+ _tag: "attachment",
+ attachmentId: preview.attachmentId,
+ fileName: props.name,
+ mimeType: "image/svg+xml",
+ disposition: "inline",
+ }
+ : null,
+ );
+ useEffect(() => {
+ const file = preview?.file;
+ if (!file) return;
+ const url = URL.createObjectURL(file);
+ // oxlint-disable-next-line react/set-state-in-effect -- Publish a Blob URL with its cleanup registered.
+ setLocal({ file, url });
+ return () => URL.revokeObjectURL(url);
+ }, [preview?.file]);
+ const url = preview?.file
+ ? local?.file === preview.file
+ ? local.url
+ : undefined
+ : asset._tag === "Success"
+ ? asset.url
+ : undefined;
+ if (url !== undefined && failedPreviewUrl === url) {
+ return <FileChip {...props} svgPreview={undefined} />;
+ }
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <ImageChipButton
+ name={props.name}
+ size={props.size}
+ previewUrl={url}
+ suffix={props.suffix}
+ disabled={props.disabled}
+ onClick={props.onOpen}
+ onPreviewError={() => setFailedPreviewUrl(url)}
+ data-markdown-copy={props.copyMarkdown}
+ aria-label={props.accessibleLabel}
+ {...(props.error ? { state: "invalid" as const } : {})}
+ />
+ }
+ />
+ <TooltipPopup side="top" className="whitespace-pre-wrap">
+ {props.tooltip}
+ </TooltipPopup>
+ </Tooltip>
+ );
+}
+
function FileChipContent(props: {
name: string;
size: string;
diff --git a/packages/shared/src/image.test.ts b/packages/shared/src/image.test.ts
new file mode 100644
index 00000000000..b8969c39630
--- /dev/null
+++ b/packages/shared/src/image.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { imageMimeType, isSvgAttachment } from "./image.ts";
+
+describe("isSvgAttachment", () => {
+ it("recognizes SVG previews without promoting them to provider images", () => {
+ for (const mimeType of [
+ "image/svg+xml",
+ "IMAGE/SVG+XML; charset=utf-8",
+ "",
+ "application/octet-stream",
+ ]) {
+ const attachment = { name: "diagram.SVG", mimeType };
+ expect(isSvgAttachment(attachment)).toBe(true);
+ expect(imageMimeType(attachment)).toBeNull();
+ }
+ expect(isSvgAttachment({ name: "diagram.svg", mimeType: "application/pdf" })).toBe(false);
+ expect(isSvgAttachment({ name: "photo.png", mimeType: "image/png" })).toBe(false);
+ });
+});
diff --git a/packages/shared/src/image.ts b/packages/shared/src/image.ts
index e273a575e08..30615c24f96 100644
--- a/packages/shared/src/image.ts
+++ b/packages/shared/src/image.ts
@@ -15,6 +15,17 @@ export const GENERIC_MIME_TYPES = new Set([
"application/unknown",
]);
+export function isSvgAttachment(attachment: {
+ readonly name: string;
+ readonly mimeType: string;
+}): boolean {
+ const mimeType = attachment.mimeType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
+ return (
+ mimeType === "image/svg+xml" ||
+ ((mimeType === "" || GENERIC_MIME_TYPES.has(mimeType)) && /\.svg$/i.test(attachment.name))
+ );
+}
+
export function imageMimeType(attachment: {
readonly name: string;
readonly mimeType: string;