@devries-cameron20 / t3code Mirror · read-only / commits / efea68679f
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 17:00 UTC

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

maria committed Oct 25, 2026 at 19:06 UTC efea68679fac762bba56df1ea0d8de787b24267e
12 files changed +268 -7
apps/server/src/assets/AssetAccess.test.ts
+38
@@ -979,6 +979,44 @@ describe("AssetAccess", () => {
979 }).pipe(Effect.provide(layerTest)),
980 );
981
982 + it.effect("serves document attachments inline when a viewer requests it", () =>
983 + Effect.gen(function* () {
984 + const config = yield* ServerConfig.ServerConfig;
985 + const fileSystem = yield* FileSystem.FileSystem;
986 + const path = yield* Path.Path;
987 + yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
988 + for (const [extension, mimeType] of [
989 + ["pdf", "application/pdf"],
990 + ["svg", "image/svg+xml"],
991 + ] as const) {
992 + const attachmentId = `thread-1-00000000-0000-4000-8000-000000000001-${extension}`;
993 + const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.${extension}`);
994 + yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
995 +
996 + const result = yield* issueAssetUrl({
997 + resource: {
998 + _tag: "attachment",
999 + attachmentId,
1000 + fileName: `report.${extension}`,
1001 + mimeType,
1002 + disposition: "inline",
1003 + },
1004 + });
1005 + const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1006 + const separatorIndex = suffix.indexOf("/");
1007 +
1008 + expect(
1009 + yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
1010 + ).toEqual({
1011 + kind: "file",
1012 + path: attachmentPath,
1013 + fileName: `report.${extension}`,
1014 + mimeType,
1015 + });
1016 + }
1017 + }).pipe(Effect.provide(layerTest)),
1018 + );
1019 +
1020 it.effect("keeps inline requests for other attachment types as downloads", () =>
1021 Effect.gen(function* () {
1022 const config = yield* ServerConfig.ServerConfig;
apps/server/src/assets/AssetAccess.ts
+1
@@ -82,6 +82,7 @@ const PROJECT_FAVICON_ICNS_MIN_SIZE = 96;
82 const INLINE_VIDEO_MIME_TYPE_PATTERN = /^video\/[\w!#$&^.+-]+$/i;
83 // Use server-assigned attachment extensions, never client MIME types.
84 const INLINE_PREVIEW_MIME_TYPES: Record<string, string> = {
85 + svg: "image/svg+xml",
86 pdf: "application/pdf",
87 html: "text/html",
88 htm: "text/html",
apps/server/src/assets/AttachmentUpload.test.ts
+46
@@ -4,6 +4,7 @@ import * as NodePath from "node:path";
4
5 import * as NodeServices from "@effect/platform-node/NodeServices";
6 import { describe, expect, it } from "@effect/vitest";
7 +import { ChatAttachmentId } from "@t3tools/contracts";
8 import * as Deferred from "effect/Deferred";
9 import * as Effect from "effect/Effect";
10 import * as Fiber from "effect/Fiber";
@@ -14,6 +15,10 @@ import * as Stream from "effect/Stream";
15 import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
16 import { base64UrlEncode, signPayload } from "../auth/utils.ts";
17 import * as ServerConfig from "../config.ts";
18 +import {
19 + claimPendingAttachments,
20 + releaseClaimedAttachments,
21 +} from "../orchestration-v2/AttachmentClaims.ts";
22 import {
23 ATTACHMENT_UPLOAD_ROUTE_PREFIX,
24 deletePendingAttachment,
@@ -139,6 +144,47 @@ describe("AttachmentUpload", () => {
144 }).pipe(Effect.provide(layerTest)),
145 );
146
147 + it.effect("stores MIME-identified SVG files with a previewable signed extension", () =>
148 + Effect.gen(function* () {
149 + const config = yield* ServerConfig.ServerConfig;
150 + const bytes = new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"/>');
151 + for (const name of ["diagram", "diagram.bin"]) {
152 + const issued = yield* issueAttachmentUploadUrl({
153 + type: "file",
154 + name,
155 + mimeType: "image/svg+xml",
156 + sizeBytes: bytes.length,
157 + });
158 + const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
159 + const claims = yield* validateAttachmentUploadToken(token);
160 + if (!claims) throw new Error("Expected valid SVG upload claims.");
161 + expect(claims.name).toBe(`${name}.svg`);
162 + expect(issued.attachmentId).toMatch(/-svg$/);
163 + expect(yield* storeAttachmentUpload(claims, bytes)).toEqual({ ok: true });
164 + expect(
165 + NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${issued.attachmentId}.svg`)),
166 + ).toEqual(Buffer.from(bytes));
167 + const claimed = yield* claimPendingAttachments({
168 + threadId: "svg-upload-thread",
169 + attachments: [
170 + {
171 + type: "file",
172 + id: ChatAttachmentId.make(issued.attachmentId),
173 + name,
174 + mimeType: "image/svg+xml",
175 + sizeBytes: bytes.length,
176 + },
177 + ],
178 + });
179 + expect(claimed.attachments[0]?.name).toBe(`${name}.svg`);
180 + expect(NodeFS.readFileSync(claimed.claimedPaths[0]!)).toEqual(Buffer.from(bytes));
181 + yield* releaseClaimedAttachments(claimed.claimedPaths);
182 + yield* deletePendingAttachment(issued.attachmentId);
183 + }
184 + expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([]);
185 + }).pipe(Effect.provide(layerTest)),
186 + );
187 +
188 it.effect("removes partial streamed uploads that exceed their signed size", () =>
189 Effect.gen(function* () {
190 const config = yield* ServerConfig.ServerConfig;
apps/server/src/assets/AttachmentUpload.ts
+7 -2
@@ -3,6 +3,7 @@ import {
3 type AttachmentCreateUploadUrlInput,
4 AttachmentUploadSigningKeyError,
5 } from "@t3tools/contracts";
6 +import { isSvgAttachment } from "@t3tools/shared/image";
7 import * as Clock from "effect/Clock";
8 import * as Crypto from "effect/Crypto";
9 import * as Effect from "effect/Effect";
@@ -93,8 +94,12 @@ export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(f
94 }
95
96 const attachmentType = input.type ?? "image";
97 + const name =
98 + attachmentType === "file" && isSvgAttachment(input) && !/\.svg$/i.test(input.name)
99 + ? `${input.name}.svg`
100 + : input.name;
101 const attachmentId = createPendingAttachmentId(
97 - attachmentType === "file" ? attachmentFileExtension(input.name) : undefined,
102 + attachmentType === "file" ? attachmentFileExtension(name) : undefined,
103 );
104 const expiresAt = nowMs + ATTACHMENT_UPLOAD_URL_TTL_MS;
105 const encodedPayload = base64UrlEncode(
@@ -103,7 +108,7 @@ export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(f
108 kind: "attachment-upload",
109 type: attachmentType,
110 attachmentId,
106 - name: input.name,
111 + name,
112 mimeType: input.mimeType,
113 sizeBytes: input.sizeBytes,
114 expiresAt,
apps/server/src/orchestration-v2/AttachmentClaims.ts
+7
@@ -6,6 +6,7 @@ import {
6 } from "@t3tools/contracts";
7 import * as Effect from "effect/Effect";
8 import * as Schema from "effect/Schema";
9 +import { isSvgAttachment } from "@t3tools/shared/image";
10
11 import {
12 parseThreadSegmentFromAttachmentId,
@@ -106,6 +107,12 @@ export const claimPendingAttachments = Effect.fn("AttachmentClaims.claimPendingA
107 const normalized: ChatAttachment = {
108 ...attachment,
109 id: ChatAttachmentId.make(claim.finalId),
110 + name:
111 + attachment.type === "file" &&
112 + isSvgAttachment(attachment) &&
113 + !/\.svg$/i.test(attachment.name)
114 + ? `${attachment.name}.svg`
115 + : attachment.name,
116 mimeType: attachment.mimeType.toLowerCase(),
117 };
118 const expectedPath = resolveAttachmentPath({
apps/web/src/components/chat/UserMessageContextChips.tsx
+9 -1
@@ -1,3 +1,4 @@
1 +import { isSvgAttachment } from "@t3tools/shared/image";
2 import { useRenderedAppearance } from "../../hooks/useTheme";
3 import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
4 import { ReadOnlySourcePreview } from "../files/AttachmentFilePreview";
@@ -268,6 +269,7 @@ function UserMessageElementDetails({
269 }
270
271 interface UserMessageContextRenderContext {
272 + environmentId: import("@t3tools/contracts").EnvironmentId;
273 reference: ChatMarkdownContextReference;
274 annotationImage: ChatImageAttachment | null;
275 attachment: ChatImageAttachment | ChatFileAttachment | null;
@@ -378,6 +380,11 @@ const userMessageContextPresentationRegistry = createContextPresentationRegistry
380 return (
381 <FileChip
382 name={record.name}
383 + svgPreview={
384 + isSvgAttachment(attachment)
385 + ? { environmentId: context.environmentId, attachmentId: attachment.id }
386 + : undefined
387 + }
388 size={size}
389 isVideo={isVideo}
390 theme={context.resolvedTheme}
@@ -509,13 +516,14 @@ export function UserMessageContextReferenceChip(props: {
516 onExpandVideo: (file: ChatFileAttachment) => void;
517 onOpenFile: (file: ChatFileAttachment) => void;
518 }) {
512 - const { resolvedTheme } = use(TimelineRowCtx);
519 + const { resolvedTheme, activeThreadEnvironmentId } = use(TimelineRowCtx);
520 const copyMarkdown = formatComposerContextReference({
521 kind: props.reference.kind,
522 contextId: props.reference.contextId as ComposerContextId,
523 label: props.reference.label,
524 });
525 return userMessageContextPresentationRegistry.render(props.reference.kind, props.record, {
526 + environmentId: activeThreadEnvironmentId,
527 reference: props.reference,
528 annotationImage: props.annotationImage,
529 attachment: props.attachment,
apps/web/src/components/chat/composerAttachmentFiles.test.ts
+32
@@ -18,6 +18,22 @@ import {
18 } from "./composerAttachmentFiles";
19
20 describe("composer attachment files", () => {
21 + it("attaches SVG as a file and rejects other unsupported images", () => {
22 + expect(classifyComposerAttachmentFile({ name: "diagram.svg", type: "image/svg+xml" })).toBe(
23 + "file",
24 + );
25 + expect(classifyComposerAttachmentFile({ name: "diagram.SVG", type: "" })).toBe("file");
26 + expect(
27 + classifyComposerAttachmentFile({ name: "diagram.svg", type: "application/octet-stream" }),
28 + ).toBe("file");
29 + expect(classifyComposerAttachmentFile({ name: "photo.tiff", type: "image/tiff" })).toBe(
30 + "unsupported-image",
31 + );
32 + expect(classifyComposerAttachmentFile({ name: "report.pdf", type: "application/pdf" })).toBe(
33 + "file",
34 + );
35 + });
36 +
37 it("keeps DNG originals on the file path without changing their bytes", async () => {
38 const bytes = new Uint8Array([0x49, 0x49, 0x2a, 0x00, 0x08, 0, 0, 0, 0xfe, 0xff, 0x00, 0x80]);
39 const files = [
@@ -96,6 +112,22 @@ describe("composer attachment files", () => {
112 ).toBe(false);
113 });
114
115 + it("claims SVG and unsupported image pastes even when text is present", () => {
116 + const images = [
117 + new File(["svg"], "diagram.svg", { type: "image/svg+xml" }),
118 + new File(["tiff"], "photo.tiff", { type: "image/tiff" }),
119 + ];
120 +
121 + for (const image of images) {
122 + expect(
123 + shouldHandleComposerAttachmentPaste({
124 + files: [image],
125 + plainText: "Image caption",
126 + }),
127 + ).toBe(true);
128 + }
129 + });
130 +
131 it("uses the hard local limit while server config is unknown", () => {
132 expect(
133 fileAttachmentStagingLimit({
apps/web/src/components/chat/composerAttachmentFiles.ts
+8 -1
@@ -11,6 +11,7 @@ import {
11 import type { ComposerFileAttachment, ComposerImageAttachment } from "../../composerDraftStore";
12 import { isHeicImageFile } from "../../lib/imageCompression";
13 import { isVideoAttachment, videoMimeType } from "../../types";
14 +import { isSvgAttachment } from "@t3tools/shared/image";
15
16 type ComposerAttachmentFileKind = "image" | "file" | "unsupported-image";
17
@@ -72,6 +73,7 @@ function isDngFile(file: Pick<File, "name" | "type">): boolean {
73 export function composerFileAttachmentMimeType(file: Pick<File, "name" | "type">): string {
74 // Downstream image detection uses MIME, even for attachments staged as files.
75 if (isDngFile(file)) return "image/x-adobe-dng";
76 + if (isSvgAttachment({ name: file.name, mimeType: file.type })) return "image/svg+xml";
77 return (
78 videoMimeType({ name: file.name, mimeType: file.type }) ??
79 (file.type || "application/octet-stream")
@@ -81,6 +83,7 @@ export function composerFileAttachmentMimeType(file: Pick<File, "name" | "type">
83 export function classifyComposerAttachmentFile(
84 file: Pick<File, "name" | "type">,
85 ): ComposerAttachmentFileKind {
86 + if (isSvgAttachment({ name: file.name, mimeType: file.type })) return "file";
87 if (isDngFile(file)) return "file";
88 if (isHeicImageFile(file)) {
89 return "image";
@@ -164,7 +167,11 @@ export function shouldHandleComposerAttachmentPaste(input: {
167 input.files.some((file) => {
168 if (isDngFile(file)) return true;
169 const classification = classifyComposerAttachmentFile(file);
167 - return classification === "image" || classification === "unsupported-image";
170 + return (
171 + classification === "image" ||
172 + classification === "unsupported-image" ||
173 + isSvgAttachment({ name: file.name, mimeType: file.type })
174 + );
175 })
176 ) {
177 return true;
apps/web/src/components/composerContextPresentation.tsx
+10
@@ -1,4 +1,5 @@
1 import ChatMarkdown from "./ChatMarkdown";
2 +import { isSvgAttachment } from "@t3tools/shared/image";
3 import { ReadOnlySourcePreview } from "./files/AttachmentFilePreview";
4 import type { PreviewAnnotationPayload, ThreadContextRecord } from "@t3tools/contracts";
5 import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
@@ -222,6 +223,15 @@ function FileContextChip(props: {
223 return (
224 <FileChip
225 name={props.record.name}
226 + svgPreview={
227 + isSvgAttachment(props.record)
228 + ? {
229 + file: props.record.file,
230 + environmentId: props.record.uploadEnvironmentId,
231 + attachmentId: props.record.uploadedAttachmentId,
232 + }
233 + : undefined
234 + }
235 size={size}
236 isVideo={isVideo}
237 theme={resolvedTheme}
apps/web/src/components/contextChipParts.tsx
+79 -3
@@ -1,12 +1,14 @@
1 import type { EnvironmentId, PullRequestContextMetadata } from "@t3tools/contracts";
2 import { CircleDashedIcon, FilmIcon, ImageIcon } from "lucide-react";
3 import {
4 + useEffect,
5 useState,
6 type ComponentProps,
7 type CSSProperties,
8 type MouseEvent,
9 type ReactNode,
10 } from "react";
11 +import { useAssetUrlState } from "~/assets/assetUrls";
12
13 import { PULL_REQUEST_STATE_PRESENTATION } from "~/components/pullRequest/pullRequestIcons";
14 import type { PullRequestContextDisplayState } from "~/lib/composerContextRecords";
@@ -167,13 +169,17 @@ export function ImageChipButton({
169 previewUrl,
170 size,
171 suffix,
172 + disabled,
173 + onPreviewError,
174 style,
175 ...props
176 }: Omit<ComponentProps<typeof ContextChip>, "kind" | "render"> & {
177 name: string;
178 previewUrl: string | undefined;
179 size: string;
176 - suffix?: string | null;
180 + suffix?: string | null | undefined;
181 + disabled?: boolean | undefined;
182 + onPreviewError?: (() => void) | undefined;
183 }) {
184 const [sample, setSample] = useState<{ url: string; color: string | undefined }>();
185 const [corsFailedUrl, setCorsFailedUrl] = useState<string>();
@@ -181,7 +187,7 @@ export function ImageChipButton({
187 return (
188 <ContextChip
189 kind="image"
184 - render={<button type="button" />}
190 + render={<button type="button" disabled={disabled} />}
191 aria-label={`Image attachment, ${name}, ${size}`}
192 style={{ ...style, ...(accent ? { "--context-chip-accent": accent } : {}) } as CSSProperties}
193 {...props}
@@ -193,7 +199,10 @@ export function ImageChipButton({
199 src={previewUrl}
200 alt=""
201 className="size-[1.17em] shrink-0 rounded-sm object-cover"
196 - onError={() => setCorsFailedUrl(previewUrl)}
202 + onError={() => {
203 + if (corsFailedUrl === previewUrl) onPreviewError?.();
204 + else setCorsFailedUrl(previewUrl);
205 + }}
206 onLoad={(event) =>
207 setSample({ url: previewUrl, color: averageImageColor(event.currentTarget) })
208 }
@@ -223,7 +232,15 @@ export function FileChip(props: {
232 error?: boolean;
233 unresolved?: boolean;
234 onOpen?: (() => void) | undefined;
235 + svgPreview?:
236 + | {
237 + file?: Blob | null | undefined;
238 + environmentId?: EnvironmentId | undefined;
239 + attachmentId?: string | undefined;
240 + }
241 + | undefined;
242 }) {
243 + if (props.svgPreview && !props.unresolved) return <SvgFileChip {...props} />;
244 const content = <FileChipContent {...props} />;
245 const state = props.unresolved
246 ? ("unresolved" as const)
@@ -263,6 +280,65 @@ export function FileChip(props: {
280 );
281 }
282
283 +function SvgFileChip(props: ComponentProps<typeof FileChip>) {
284 + const preview = props.svgPreview;
285 + const [local, setLocal] = useState<{ file: Blob; url: string }>();
286 + const [failedPreviewUrl, setFailedPreviewUrl] = useState<string>();
287 + const asset = useAssetUrlState(
288 + preview?.file ? null : (preview?.environmentId ?? null),
289 + preview?.attachmentId
290 + ? {
291 + _tag: "attachment",
292 + attachmentId: preview.attachmentId,
293 + fileName: props.name,
294 + mimeType: "image/svg+xml",
295 + disposition: "inline",
296 + }
297 + : null,
298 + );
299 + useEffect(() => {
300 + const file = preview?.file;
301 + if (!file) return;
302 + const url = URL.createObjectURL(file);
303 + // oxlint-disable-next-line react/set-state-in-effect -- Publish a Blob URL with its cleanup registered.
304 + setLocal({ file, url });
305 + return () => URL.revokeObjectURL(url);
306 + }, [preview?.file]);
307 + const url = preview?.file
308 + ? local?.file === preview.file
309 + ? local.url
310 + : undefined
311 + : asset._tag === "Success"
312 + ? asset.url
313 + : undefined;
314 + if (url !== undefined && failedPreviewUrl === url) {
315 + return <FileChip {...props} svgPreview={undefined} />;
316 + }
317 + return (
318 + <Tooltip>
319 + <TooltipTrigger
320 + render={
321 + <ImageChipButton
322 + name={props.name}
323 + size={props.size}
324 + previewUrl={url}
325 + suffix={props.suffix}
326 + disabled={props.disabled}
327 + onClick={props.onOpen}
328 + onPreviewError={() => setFailedPreviewUrl(url)}
329 + data-markdown-copy={props.copyMarkdown}
330 + aria-label={props.accessibleLabel}
331 + {...(props.error ? { state: "invalid" as const } : {})}
332 + />
333 + }
334 + />
335 + <TooltipPopup side="top" className="whitespace-pre-wrap">
336 + {props.tooltip}
337 + </TooltipPopup>
338 + </Tooltip>
339 + );
340 +}
341 +
342 function FileChipContent(props: {
343 name: string;
344 size: string;
packages/shared/src/image.test.ts new
+20
@@ -0,0 +1,20 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +
3 +import { imageMimeType, isSvgAttachment } from "./image.ts";
4 +
5 +describe("isSvgAttachment", () => {
6 + it("recognizes SVG previews without promoting them to provider images", () => {
7 + for (const mimeType of [
8 + "image/svg+xml",
9 + "IMAGE/SVG+XML; charset=utf-8",
10 + "",
11 + "application/octet-stream",
12 + ]) {
13 + const attachment = { name: "diagram.SVG", mimeType };
14 + expect(isSvgAttachment(attachment)).toBe(true);
15 + expect(imageMimeType(attachment)).toBeNull();
16 + }
17 + expect(isSvgAttachment({ name: "diagram.svg", mimeType: "application/pdf" })).toBe(false);
18 + expect(isSvgAttachment({ name: "photo.png", mimeType: "image/png" })).toBe(false);
19 + });
20 +});
packages/shared/src/image.ts
+11
@@ -15,6 +15,17 @@ export const GENERIC_MIME_TYPES = new Set([
15 "application/unknown",
16 ]);
17
18 +export function isSvgAttachment(attachment: {
19 + readonly name: string;
20 + readonly mimeType: string;
21 +}): boolean {
22 + const mimeType = attachment.mimeType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
23 + return (
24 + mimeType === "image/svg+xml" ||
25 + ((mimeType === "" || GENERIC_MIME_TYPES.has(mimeType)) && /\.svg$/i.test(attachment.name))
26 + );
27 +}
28 +
29 export function imageMimeType(attachment: {
30 readonly name: string;
31 readonly mimeType: string;