Compare commits

...
Author SHA1 Message Date
Julius Marmingeandcodex aa8b28991e fix(attachments): address file review edge cases
Revoke file preview blobs, recover image MIME types from generic browser metadata, and let the client-provided download name win over the server storage id.

Co-authored-by: codex <[email protected]>
2026-07-20 18:20:27 +02:00
Andrei Drăgan RădulețandClaude Fable 5 c640240680 test(server): cover file attachment ingestion, GC, prompt injection, and downloads
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-20 18:09:35 +02:00
Andrei Drăgan RădulețandClaude Fable 5 f8da3b51bc test(contracts,web): cover file attachment variant, drafts, and rendering
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-20 18:08:48 +02:00
Andrei Drăgan RădulețandClaude Fable 5 4050afee4d feat(web): accept any file in the composer, render file chips
- drag/drop and paste accept non-image files (staged as name+size
  chips); images keep the existing preview tiles and expand dialog
- timeline renders file attachments as download chips via the signed
  asset URL
- drafts persist an optional attachment type (missing = image, so
  existing persisted drafts decode unchanged; no storage version bump)
- limits and copy: 10 MB per attachment, 8 attachments per message

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-20 18:08:47 +02:00
Andrei Drăgan RădulețandClaude Fable 5 9b89ef9698 feat(server): serve non-image attachments as downloads
Content-Disposition: attachment for any attachment whose extension is
not an image extension, so uploaded content is never rendered inline on
the same-origin asset route.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-20 18:08:18 +02:00
Andrei Drăgan RădulețandClaude Fable 5 1d934d2255 feat(server): deliver file attachments by path in the turn prompt
File attachments already live on the server's disk; append an
'[Attached file: ...]' line to the turn input at the single sendTurn
choke point and pass only image attachments to the provider. The agent
reads the file with its own tools, so Claude/Codex/Grok need no adapter
changes and remote environments work by construction.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-20 18:08:18 +02:00
Andrei Drăgan RădulețandClaude Fable 5 b18a3296f5 feat(server): persist non-image file attachments
- inferFileExtension with a conservative SAFE_FILE_EXTENSIONS allowlist
  (.bin fallback) so resolve-by-id keeps working and risky extensions
  (.html/.svg-for-files) never land on the same-origin asset route
- Normalizer accepts any MIME for type:"file" uploads; image gate and
  size limits unchanged
- attachment GC keep-set includes file attachments (previously any
  non-image attachment would be pruned from disk)

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-20 18:08:18 +02:00
Andrei Drăgan RădulețandClaude Fable 5 cca513e2ab feat(contracts): add ChatFileAttachment variant to attachment unions
Additive union member: existing image rows/drafts decode unchanged.
Limits shared with images (10 MB, 8 per message).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-20 18:08:18 +02:00
33 changed files with 1431 additions and 91 deletions

No files matched your search

@@ -0,0 +1,20 @@
import { describe, expect, it } from "vite-plus/test";
import { buildAssetResponseHeaders } from "./assetResponseHeaders.ts";
describe("buildAssetResponseHeaders", () => {
it("forces non-image assets to download without overriding the client filename", () => {
expect(buildAssetResponseHeaders({ download: true })).toEqual({
"Cache-Control": "private, max-age=3600",
"Content-Disposition": "attachment",
"X-Content-Type-Options": "nosniff",
});
});
it("does not force image assets to download", () => {
expect(buildAssetResponseHeaders({ download: false })).toEqual({
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
});
});
});
+7
View File
@@ -0,0 +1,7 @@
export function buildAssetResponseHeaders(input: { readonly download?: boolean }) {
return {
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
...(input.download ? { "Content-Disposition": "attachment" } : {}),
};
}
@@ -198,6 +198,32 @@ describe("AssetAccess", () => {
expect(yield* resolveAsset(token, "ignored.png")).toEqual({
kind: "file",
path: attachmentPath,
download: false,
});
}).pipe(Effect.provide(testLayer)),
);
it.effect("marks non-image attachment capabilities for download", () =>
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";
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 },
});
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const separatorIndex = suffix.indexOf("/");
const token = suffix.slice(0, separatorIndex);
expect(yield* resolveAsset(token, "ignored.pdf")).toEqual({
kind: "file",
path: attachmentPath,
download: true,
});
}).pipe(Effect.provide(testLayer)),
);
+17 -4
View File
@@ -36,6 +36,7 @@ import {
} from "../auth/utils.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { resolveAttachmentPathById } from "../attachmentStore.ts";
import { SAFE_IMAGE_FILE_EXTENSIONS } from "../imageMime.ts";
import * as ServerConfig from "../config.ts";
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
@@ -91,7 +92,11 @@ const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
export type ResolvedAsset = { readonly kind: "file"; readonly path: string };
export type ResolvedAsset = {
readonly kind: "file";
readonly path: string;
readonly download?: boolean;
};
function decodeClaims(encodedPayload: string): AssetClaims | null {
try {
@@ -383,9 +388,17 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
),
Effect.orElseSucceed(() => Option.none()),
);
return Option.isSome(info) && info.value.type === "File"
? ({ kind: "file", path: attachmentPath } satisfies ResolvedAsset)
: null;
if (!Option.isSome(info) || info.value.type !== "File") {
return null;
}
// Non-image attachments are downloaded rather than rendered inline so the
// same-origin asset route never interprets uploaded content (e.g. HTML/XML).
const extension = attachmentPath.slice(attachmentPath.lastIndexOf(".")).toLowerCase();
return {
kind: "file",
path: attachmentPath,
download: !SAFE_IMAGE_FILE_EXTENSIONS.has(extension),
} satisfies ResolvedAsset;
}
if (claims.kind === "project-favicon") {
+97
View File
@@ -0,0 +1,97 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodePath from "node:path";
import { describe, expect, it } from "vite-plus/test";
import { appendFileAttachmentPromptText } from "./attachmentPrompt.ts";
const attachmentsDir = NodePath.join(NodePath.sep, "tmp", "t3-attachment-prompt");
describe("attachmentPrompt", () => {
it("appends a prompt line for file attachments", () => {
const result = appendFileAttachmentPromptText({
text: "hello",
attachmentsDir,
attachments: [
{
type: "file",
id: "thread-1-00000000-0000-4000-8000-000000000001",
name: "notes.txt",
mimeType: "text/plain",
sizeBytes: 2048,
},
],
});
const attachmentPath = NodePath.join(
attachmentsDir,
"thread-1-00000000-0000-4000-8000-000000000001.txt",
);
expect(result).toBe(
`hello\n\n[Attached file: ${attachmentPath} (notes.txt, text/plain, 2.0 KB). Read it from disk when needed.]`,
);
});
it("returns text unchanged when only image attachments are present", () => {
expect(
appendFileAttachmentPromptText({
text: "hello",
attachmentsDir,
attachments: [
{
type: "image",
id: "thread-1-00000000-0000-4000-8000-000000000002",
name: "screen.png",
mimeType: "image/png",
sizeBytes: 4,
},
],
}),
).toBe("hello");
});
it("returns only the prompt lines when the text is empty", () => {
const result = appendFileAttachmentPromptText({
text: "",
attachmentsDir,
attachments: [
{
type: "file",
id: "thread-1-00000000-0000-4000-8000-000000000003",
name: "data.csv",
mimeType: "text/csv",
sizeBytes: 12,
},
],
});
const attachmentPath = NodePath.join(
attachmentsDir,
"thread-1-00000000-0000-4000-8000-000000000003.csv",
);
expect(result).toBe(
`[Attached file: ${attachmentPath} (data.csv, text/csv, 12 B). Read it from disk when needed.]`,
);
});
it("strips control characters, brackets, and parentheses from attachment names", () => {
const result = appendFileAttachmentPromptText({
text: "hello",
attachmentsDir,
attachments: [
{
type: "file",
id: "thread-1-00000000-0000-4000-8000-000000000004",
name: "a(b)\u0001[c].txt",
mimeType: "text/plain",
sizeBytes: 5,
},
],
});
const attachmentPath = NodePath.join(
attachmentsDir,
"thread-1-00000000-0000-4000-8000-000000000004.txt",
);
expect(result).toBe(
`hello\n\n[Attached file: ${attachmentPath} (a b c .txt, text/plain, 5 B). Read it from disk when needed.]`,
);
});
});
+55
View File
@@ -0,0 +1,55 @@
import type { ChatAttachment } from "@t3tools/contracts";
import { resolveAttachmentPath } from "./attachmentStore.ts";
const SIZE_LABEL_UNITS = ["B", "KB", "MB"] as const;
function formatSizeLabel(sizeBytes: number): string {
let value = sizeBytes;
let unitIndex = 0;
while (value >= 1024 && unitIndex < SIZE_LABEL_UNITS.length - 1) {
value /= 1024;
unitIndex += 1;
}
const rounded = unitIndex === 0 ? String(value) : value.toFixed(1);
return `${rounded} ${SIZE_LABEL_UNITS[unitIndex]}`;
}
function sanitizePromptFileName(name: string): string {
// eslint-disable-next-line no-control-regex
return name.replace(/[\u0000-\u001f\u007f()[\]]+/gu, " ").trim();
}
/**
* Non-image attachments are delivered by reference: the file already lives on
* the server's disk, so the provider agent reads it with its own tools. Images
* keep their native content-block path and are not mentioned here.
*/
export function appendFileAttachmentPromptText(input: {
readonly text: string;
readonly attachmentsDir: string;
readonly attachments: ReadonlyArray<ChatAttachment>;
}): string {
const lines: Array<string> = [];
for (const attachment of input.attachments) {
if (attachment.type !== "file") {
continue;
}
const attachmentPath = resolveAttachmentPath({
attachmentsDir: input.attachmentsDir,
attachment,
});
if (!attachmentPath) {
continue;
}
const name = sanitizePromptFileName(attachment.name);
lines.push(
`[Attached file: ${attachmentPath} (${name}, ${attachment.mimeType}, ${formatSizeLabel(attachment.sizeBytes)}). Read it from disk when needed.]`,
);
}
if (lines.length === 0) {
return input.text;
}
const joined = lines.join("\n");
return input.text.trim().length > 0 ? `${input.text}\n\n${joined}` : joined;
}
+32
View File
@@ -6,6 +6,7 @@ import * as NodePath from "node:path";
import { describe, expect, it } from "vite-plus/test";
import {
attachmentRelativePath,
createAttachmentId,
parseThreadSegmentFromAttachmentId,
resolveAttachmentPathById,
@@ -44,6 +45,37 @@ describe("attachmentStore", () => {
expect(parseThreadSegmentFromAttachmentId(attachmentId)).toBe("thread-foo");
});
it("builds file attachment relative paths with the inferred file extension", () => {
expect(
attachmentRelativePath({
type: "file",
id: "thread-1-00000000-0000-4000-8000-000000000001",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 5,
}),
).toBe("thread-1-00000000-0000-4000-8000-000000000001.pdf");
});
it("resolves attachment path by id for a written file attachment extension", () => {
const attachmentsDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
);
try {
const attachmentId = "thread-1-attachment";
const pdfPath = NodePath.join(attachmentsDir, `${attachmentId}.pdf`);
NodeFS.writeFileSync(pdfPath, Buffer.from("hello"));
const resolved = resolveAttachmentPathById({
attachmentsDir,
attachmentId,
});
expect(resolved).toBe(pdfPath);
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
it("resolves attachment path by id using the extension that exists on disk", () => {
const attachmentsDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
+16 -2
View File
@@ -8,9 +8,16 @@ import {
normalizeAttachmentRelativePath,
resolveAttachmentRelativePath,
} from "./attachmentPaths.ts";
import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
import {
inferFileExtension,
inferImageExtension,
SAFE_FILE_EXTENSIONS,
SAFE_IMAGE_FILE_EXTENSIONS,
} from "./imageMime.ts";
const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
const ATTACHMENT_FILENAME_EXTENSIONS = [
...new Set([...SAFE_IMAGE_FILE_EXTENSIONS, ...SAFE_FILE_EXTENSIONS, ".bin"]),
];
const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
@@ -63,6 +70,13 @@ export function attachmentRelativePath(attachment: ChatAttachment): string {
});
return `${attachment.id}${extension}`;
}
case "file": {
const extension = inferFileExtension({
mimeType: attachment.mimeType,
fileName: attachment.name,
});
return `${attachment.id}${extension}`;
}
}
}
+2 -4
View File
@@ -25,6 +25,7 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import { OtlpTracer } from "effect/unstable/observability";
import * as ServerConfig from "./config.ts";
import { buildAssetResponseHeaders } from "./assetResponseHeaders.ts";
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
@@ -194,10 +195,7 @@ export const assetRouteLayer = HttpRouter.add(
}
return yield* HttpServerResponse.file(asset.path, {
status: 200,
headers: {
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
},
headers: buildAssetResponseHeaders(asset),
}).pipe(
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
);
+36 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
import { inferFileExtension, inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
describe("imageMime", () => {
it("parses base64 data URL with mime type", () => {
@@ -92,4 +92,39 @@ describe("imageMime", () => {
it("does not read inherited keys from mime extension map", () => {
expect(inferImageExtension({ mimeType: "constructor" })).toBe(".bin");
});
it("infers file extension from an allowlisted file name extension", () => {
expect(
inferFileExtension({ mimeType: "application/octet-stream", fileName: "report.PDF" }),
).toBe(".pdf");
});
it("infers file extension from the last segment of a multi-dot file name", () => {
expect(inferFileExtension({ mimeType: "application/octet-stream", fileName: "a.b.csv" })).toBe(
".csv",
);
});
it("falls back to an allowlisted mime extension when the file name extension is unsafe", () => {
expect(inferFileExtension({ mimeType: "application/pdf", fileName: "notes.exe" })).toBe(".pdf");
});
it("falls back to an allowlisted mime extension when the file name has no extension", () => {
expect(inferFileExtension({ mimeType: "text/plain", fileName: "notes" })).toBe(".txt");
});
it("defaults file extension to .bin when neither file name nor mime is allowlisted", () => {
expect(inferFileExtension({ mimeType: "application/x-unknown", fileName: "payload.exe" })).toBe(
".bin",
);
expect(inferFileExtension({ mimeType: "application/x-unknown", fileName: "notes" })).toBe(
".bin",
);
});
it("defaults dotfile names without an allowlisted mime to .bin", () => {
expect(inferFileExtension({ mimeType: "application/x-unknown", fileName: ".env" })).toBe(
".bin",
);
});
});
+42
View File
@@ -112,6 +112,48 @@ export function parseBase64DataUrl(
return { mimeType, base64 };
}
export const SAFE_FILE_EXTENSIONS = new Set([
".csv",
".diff",
".docx",
".gz",
".json",
".jsonl",
".log",
".md",
".patch",
".pdf",
".pptx",
".tar",
".toml",
".tsv",
".txt",
".xlsx",
".xml",
".yaml",
".yml",
".zip",
]);
export function inferFileExtension(input: { mimeType: string; fileName?: string }): string {
const fileName = input.fileName?.trim() ?? "";
const extensionMatch = /\.([a-z0-9]{1,8})$/i.exec(fileName);
const fileNameExtension = extensionMatch ? `.${extensionMatch[1]!.toLowerCase()}` : "";
if (SAFE_FILE_EXTENSIONS.has(fileNameExtension)) {
return fileNameExtension;
}
// Mime.getExtension returns dot-less extensions ("pdf"), the sets hold
// dotted ones (".pdf").
const fromMimeExtension = Mime.getExtension(input.mimeType);
const dottedMimeExtension = fromMimeExtension ? `.${fromMimeExtension}` : null;
if (dottedMimeExtension && SAFE_FILE_EXTENSIONS.has(dottedMimeExtension)) {
return dottedMimeExtension;
}
return ".bin";
}
export function inferImageExtension(input: { mimeType: string; fileName?: string }): string {
const key = input.mimeType.toLowerCase();
const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key)
@@ -928,6 +928,214 @@ it.layer(
);
});
it.layer(
Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-file-gc-")),
)("OrchestrationProjectionPipeline", (it) => {
it.effect("keeps referenced file attachments and prunes orphans when a thread is reverted", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const { attachmentsDir } = yield* ServerConfig;
const now = "2026-01-01T00:00:00.000Z";
const threadId = ThreadId.make("Thread Revert.Docs");
const keepAttachmentId = "thread-revert-docs-00000000-0000-4000-8000-000000000001";
const removeAttachmentId = "thread-revert-docs-00000000-0000-4000-8000-000000000002";
const orphanAttachmentId = "thread-revert-docs-00000000-0000-4000-8000-000000000003";
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "project.created",
eventId: EventId.make("evt-revert-docs-1"),
aggregateKind: "project",
aggregateId: ProjectId.make("project-revert-docs"),
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-1"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-1"),
metadata: {},
payload: {
projectId: ProjectId.make("project-revert-docs"),
title: "Project Revert Docs",
workspaceRoot: "/tmp/project-revert-docs",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
yield* appendAndProject({
type: "thread.created",
eventId: EventId.make("evt-revert-docs-2"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-2"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-2"),
metadata: {},
payload: {
threadId,
projectId: ProjectId.make("project-revert-docs"),
title: "Thread Revert Docs",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
yield* appendAndProject({
type: "thread.turn-diff-completed",
eventId: EventId.make("evt-revert-docs-3"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-3"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-3"),
metadata: {},
payload: {
threadId,
turnId: TurnId.make("turn-keep"),
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert-docs/turn/1"),
status: "ready",
files: [],
assistantMessageId: MessageId.make("message-keep"),
completedAt: now,
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.make("evt-revert-docs-4"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-4"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-4"),
metadata: {},
payload: {
threadId,
messageId: MessageId.make("message-keep"),
role: "assistant",
text: "Keep",
attachments: [
{
type: "file",
id: keepAttachmentId,
name: "keep.pdf",
mimeType: "application/pdf",
sizeBytes: 5,
},
],
turnId: TurnId.make("turn-keep"),
streaming: false,
createdAt: now,
updatedAt: now,
},
});
yield* appendAndProject({
type: "thread.turn-diff-completed",
eventId: EventId.make("evt-revert-docs-5"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-5"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-5"),
metadata: {},
payload: {
threadId,
turnId: TurnId.make("turn-remove"),
checkpointTurnCount: 2,
checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert-docs/turn/2"),
status: "ready",
files: [],
assistantMessageId: MessageId.make("message-remove"),
completedAt: now,
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.make("evt-revert-docs-6"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-6"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-6"),
metadata: {},
payload: {
threadId,
messageId: MessageId.make("message-remove"),
role: "assistant",
text: "Remove",
attachments: [
{
type: "file",
id: removeAttachmentId,
name: "remove.pdf",
mimeType: "application/pdf",
sizeBytes: 5,
},
],
turnId: TurnId.make("turn-remove"),
streaming: false,
createdAt: now,
updatedAt: now,
},
});
const keepPath = path.join(attachmentsDir, `${keepAttachmentId}.pdf`);
const removePath = path.join(attachmentsDir, `${removeAttachmentId}.pdf`);
const orphanPath = path.join(attachmentsDir, `${orphanAttachmentId}.pdf`);
yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true });
yield* fileSystem.writeFileString(keepPath, "keep");
yield* fileSystem.writeFileString(removePath, "remove");
yield* fileSystem.writeFileString(orphanPath, "orphan");
assert.isTrue(yield* exists(keepPath));
assert.isTrue(yield* exists(removePath));
assert.isTrue(yield* exists(orphanPath));
yield* appendAndProject({
type: "thread.reverted",
eventId: EventId.make("evt-revert-docs-7"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-revert-docs-7"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-docs-7"),
metadata: {},
payload: {
threadId,
turnCount: 1,
},
});
assert.isTrue(yield* exists(keepPath));
assert.isFalse(yield* exists(removePath));
assert.isFalse(yield* exists(orphanPath));
}),
);
});
it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-revert-")))(
"OrchestrationProjectionPipeline",
(it) => {
@@ -338,9 +338,6 @@ function collectThreadAttachmentRelativePaths(
const relativePaths = new Set<string>();
for (const message of messages) {
for (const attachment of message.attachments ?? []) {
if (attachment.type !== "image") {
continue;
}
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachment.id);
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
continue;
@@ -466,6 +466,58 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
effectIt.effect(
"sends only image attachments to the provider and appends file attachment prompt text",
() =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() => createHarness());
const now = "2026-01-01T00:00:00.000Z";
const imageAttachment = {
type: "image" as const,
id: "thread-1-00000000-0000-4000-8000-000000000001",
name: "screen.png",
mimeType: "image/png",
sizeBytes: 4,
};
const fileAttachment = {
type: "file" as const,
id: "thread-1-00000000-0000-4000-8000-000000000002",
name: "notes.txt",
mimeType: "text/plain",
sizeBytes: 5,
};
const attachmentsDir = NodePath.join(harness.stateDir, "attachments");
const fileAttachmentPath = NodePath.join(attachmentsDir, `${fileAttachment.id}.txt`);
NodeFS.mkdirSync(attachmentsDir, { recursive: true });
NodeFS.writeFileSync(fileAttachmentPath, "notes");
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-file-attachments"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-file-attachments"),
role: "user",
text: "hello with attachments",
attachments: [imageAttachment, fileAttachment],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
const request = harness.sendTurn.mock.calls[0]?.[0] as {
readonly input?: string;
readonly attachments?: ReadonlyArray<unknown>;
};
expect(request.attachments).toEqual([imageAttachment]);
expect(request.input).toBe(
`hello with attachments\n\n[Attached file: ${fileAttachmentPath} (notes.txt, text/plain, 5 B). Read it from disk when needed.]`,
);
}),
);
it("generates a thread title on the first turn", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -25,7 +25,9 @@ import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { appendFileAttachmentPromptText } from "../../attachmentPrompt.ts";
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { ServerConfig } from "../../config.ts";
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import type { ProviderServiceError } from "../../provider/Errors.ts";
@@ -196,6 +198,7 @@ const make = Effect.gen(function* () {
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const textGeneration = yield* TextGeneration;
const serverSettingsService = yield* ServerSettingsService;
const serverConfig = yield* ServerConfig;
const serverCommandId = (tag: string) =>
crypto.randomUUIDv4.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));
const serverEventId = () => crypto.randomUUIDv4.pipe(Effect.map(EventId.make));
@@ -605,8 +608,18 @@ const make = Effect.gen(function* () {
if (input.modelSelection !== undefined) {
threadModelSelections.set(input.threadId, input.modelSelection);
}
const normalizedInput = toNonEmptyProviderInput(input.messageText);
const normalizedAttachments = input.attachments ?? [];
const normalizedInput = toNonEmptyProviderInput(
appendFileAttachmentPromptText({
text: input.messageText,
attachmentsDir: serverConfig.attachmentsDir,
attachments: input.attachments ?? [],
}),
);
// Only image attachments go to the provider as content blocks; file
// attachments are delivered by path in the prompt text above.
const normalizedAttachments = (input.attachments ?? []).filter(
(attachment) => attachment.type === "image",
);
const activeSession = yield* providerService
.listSessions()
.pipe(
@@ -1,17 +1,53 @@
import { describe, expect, it } from "vite-plus/test";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
CommandId,
type ClientOrchestrationCommand,
DEFAULT_PROVIDER_INTERACTION_MODE,
MessageId,
ProjectId,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
ProviderInstanceId,
ThreadId,
type ClientOrchestrationCommand,
type UploadChatAttachment,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import { canonicalizeClientCommandTimestamps } from "./Normalizer.ts";
import * as ServerConfig from "../config.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import { canonicalizeClientCommandTimestamps, normalizeDispatchCommand } from "./Normalizer.ts";
const testLayer = Layer.mergeAll(
ServerConfig.ServerConfig.layerTest(process.cwd(), { prefix: "t3-normalizer-test-" }),
WorkspacePaths.layer,
).pipe(Layer.provideMerge(NodeServices.layer));
const clientCreatedAt = "2031-01-01T00:00:00.000Z";
const serverReceivedAt = "2026-07-18T00:00:00.000Z";
const now = "2026-01-01T00:00:00.000Z";
const turnStartCommand = (
attachments: ReadonlyArray<UploadChatAttachment>,
): ClientOrchestrationCommand => ({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: MessageId.make("user-message-1"),
role: "user",
text: "hello normalizer",
attachments,
},
runtimeMode: "full-access",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
createdAt: now,
});
const asDataUrl = (mimeType: string, bytes: Buffer) =>
`data:${mimeType};base64,${bytes.toString("base64")}`;
describe("canonicalizeClientCommandTimestamps", () => {
it("replaces a client command timestamp with the server receipt timestamp", () => {
@@ -71,3 +107,86 @@ describe("canonicalizeClientCommandTimestamps", () => {
expect(result.bootstrap?.createThread?.createdAt).toBe(serverReceivedAt);
});
});
describe("Normalizer", () => {
it.effect("persists file attachments and writes their bytes to the attachments dir", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig.ServerConfig;
const bytes = Buffer.from("hello world");
const normalized = yield* normalizeDispatchCommand(
turnStartCommand([
{
type: "file",
name: "notes.txt",
mimeType: "text/plain",
sizeBytes: bytes.byteLength,
dataUrl: asDataUrl("text/plain", bytes),
},
]),
);
expect(normalized.type).toBe("thread.turn.start");
if (normalized.type !== "thread.turn.start") {
return;
}
const attachment = normalized.message.attachments[0];
expect(attachment).toMatchObject({
type: "file",
name: "notes.txt",
mimeType: "text/plain",
sizeBytes: bytes.byteLength,
});
expect(attachment?.id).toMatch(
/^thread-1-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
);
if (!attachment) {
return;
}
const attachmentPath = path.join(attachmentsDir, `${attachment.id}.txt`);
expect(yield* fileSystem.readFileString(attachmentPath)).toBe("hello world");
}).pipe(Effect.provide(testLayer)),
);
it.effect("rejects image attachments with a non-image data URL mime type", () =>
Effect.gen(function* () {
const error = yield* normalizeDispatchCommand(
turnStartCommand([
{
type: "image",
name: "fake.png",
mimeType: "image/png",
sizeBytes: 5,
dataUrl: asDataUrl("text/plain", Buffer.from("hello")),
},
]),
).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationDispatchCommandError");
expect(error.message).toBe("Invalid image attachment payload for 'fake.png'.");
}).pipe(Effect.provide(testLayer)),
);
it.effect("rejects file attachments over the maximum attachment size", () =>
Effect.gen(function* () {
const bytes = Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1, "a");
const error = yield* normalizeDispatchCommand(
turnStartCommand([
{
type: "file",
name: "big.txt",
mimeType: "text/plain",
sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
dataUrl: asDataUrl("text/plain", bytes),
},
]),
).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationDispatchCommandError");
expect(error.message).toBe("Attachment 'big.txt' is empty or too large.");
}).pipe(Effect.provide(testLayer)),
);
});
+4 -4
View File
@@ -109,16 +109,16 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
(attachment) =>
Effect.gen(function* () {
const parsed = parseBase64DataUrl(attachment.dataUrl);
if (!parsed || !parsed.mimeType.startsWith("image/")) {
if (!parsed || (attachment.type === "image" && !parsed.mimeType.startsWith("image/"))) {
return yield* new OrchestrationDispatchCommandError({
message: `Invalid image attachment payload for '${attachment.name}'.`,
message: `Invalid ${attachment.type} attachment payload for '${attachment.name}'.`,
});
}
const bytes = Buffer.from(parsed.base64, "base64");
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
return yield* new OrchestrationDispatchCommandError({
message: `Image attachment '${attachment.name}' is empty or too large.`,
message: `Attachment '${attachment.name}' is empty or too large.`,
});
}
@@ -130,7 +130,7 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
}
const persistedAttachment = {
type: "image" as const,
type: attachment.type,
id: attachmentId,
name: attachment.name,
mimeType: parsed.mimeType.toLowerCase(),
+81 -2
View File
@@ -6,9 +6,9 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it, vi } from "vite-plus/test";
import type { Thread } from "../types";
import type { ChatMessage, Thread } from "../types";
import {
MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
@@ -20,6 +20,10 @@ import {
hasServerAcknowledgedLocalDispatch,
reconcileMountedTerminalThreadIds,
reconcileRetainedMountedThreadIds,
collectUserMessageBlobPreviewUrls,
normalizeDataUrlMimeType,
resolveComposerAttachmentMimeType,
revokeUserMessagePreviewUrls,
resolveSendEnvMode,
shouldWriteThreadErrorToCurrentServerThread,
} from "./ChatView.logic";
@@ -77,6 +81,81 @@ const readySession = {
updatedAt: "2026-03-29T00:00:10.000Z",
};
function makeAttachmentMessage(): ChatMessage {
return {
id: MessageId.make("message-with-attachments"),
role: "user",
text: "Inspect these files",
turnId: null,
createdAt: now,
updatedAt: now,
streaming: false,
attachments: [
{
type: "image",
id: "image-1",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 10,
previewUrl: "blob:image-preview",
},
{
type: "file",
id: "file-1",
name: "debug.log",
mimeType: "text/plain",
sizeBytes: 20,
previewUrl: "blob:file-preview",
},
],
};
}
describe("attachment preview lifecycle", () => {
it("collects and revokes blob previews for images and files", () => {
const revokeObjectURL = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
const message = makeAttachmentMessage();
expect(collectUserMessageBlobPreviewUrls(message)).toEqual([
"blob:image-preview",
"blob:file-preview",
]);
revokeUserMessagePreviewUrls(message);
expect(revokeObjectURL).toHaveBeenCalledTimes(2);
expect(revokeObjectURL).toHaveBeenNthCalledWith(1, "blob:image-preview");
expect(revokeObjectURL).toHaveBeenNthCalledWith(2, "blob:file-preview");
revokeObjectURL.mockRestore();
});
});
describe("composer attachment MIME types", () => {
it("recovers image MIME types from names when the browser reports a generic type", () => {
expect(resolveComposerAttachmentMimeType({ name: "capture.PNG", type: "" })).toBe("image/png");
expect(
resolveComposerAttachmentMimeType({
name: "capture.webp",
type: "application/octet-stream",
}),
).toBe("image/webp");
});
it("preserves a specific browser MIME type and keeps unknown files generic", () => {
expect(resolveComposerAttachmentMimeType({ name: "capture.png", type: "text/plain" })).toBe(
"text/plain",
);
expect(resolveComposerAttachmentMimeType({ name: "payload.bin", type: "" })).toBe(
"application/octet-stream",
);
});
it("rewrites a FileReader data URL with the resolved attachment MIME type", () => {
expect(
normalizeDataUrlMimeType("data:application/octet-stream;base64,iVBORw0KGgo=", "image/png"),
).toBe("data:image/png;base64,iVBORw0KGgo=");
});
});
describe("buildThreadTurnInterruptInput", () => {
it("targets the session's active running turn", () => {
const activeTurnId = TurnId.make("turn-running");
+55 -12
View File
@@ -10,7 +10,7 @@ import {
type TurnId,
} from "@t3tools/contracts";
import { type ChatMessage, type SessionPhase, type Thread } from "../types";
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
import { type ComposerAttachment, type DraftThreadState } from "../composerDraftStore";
import * as Schema from "effect/Schema";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { environmentThreadDetails } from "../state/threads";
@@ -144,9 +144,6 @@ export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
return;
}
for (const attachment of message.attachments) {
if (attachment.type !== "image") {
continue;
}
revokeBlobPreviewUrl(attachment.previewUrl);
}
}
@@ -157,30 +154,78 @@ export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[
}
const previewUrls: string[] = [];
for (const attachment of message.attachments) {
if (attachment.type !== "image") continue;
if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
previewUrls.push(attachment.previewUrl);
}
return previewUrls;
}
const FALLBACK_IMAGE_MIME_TYPE_BY_EXTENSION: Readonly<Record<string, string>> = {
".avif": "image/avif",
".bmp": "image/bmp",
".gif": "image/gif",
".heic": "image/heic",
".heif": "image/heif",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".png": "image/png",
".svg": "image/svg+xml",
".tif": "image/tiff",
".tiff": "image/tiff",
".webp": "image/webp",
};
const GENERIC_BINARY_MIME_TYPES = new Set([
"",
"application/octet-stream",
"application/unknown",
"application/x-unknown",
"binary/octet-stream",
]);
export function resolveComposerAttachmentMimeType(file: {
readonly name: string;
readonly type: string;
}): string {
const declaredMimeType = file.type.trim().toLowerCase();
if (!GENERIC_BINARY_MIME_TYPES.has(declaredMimeType)) {
return declaredMimeType;
}
const normalizedName = file.name.trim().toLowerCase();
const extensionIndex = normalizedName.lastIndexOf(".");
const extension = extensionIndex >= 0 ? normalizedName.slice(extensionIndex) : "";
return (
FALLBACK_IMAGE_MIME_TYPE_BY_EXTENSION[extension] ||
declaredMimeType ||
"application/octet-stream"
);
}
export function normalizeDataUrlMimeType(dataUrl: string, mimeType: string): string {
const separatorIndex = dataUrl.indexOf(",");
if (!dataUrl.startsWith("data:") || separatorIndex < 0) {
return dataUrl;
}
return `data:${mimeType};base64,${dataUrl.slice(separatorIndex + 1)}`;
}
export interface PullRequestDialogState {
initialReference: string | null;
key: number;
}
export function readFileAsDataUrl(file: File): Promise<string> {
export function readFileAsDataUrl(file: File, mimeType?: string): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener("load", () => {
if (typeof reader.result === "string") {
resolve(reader.result);
resolve(mimeType ? normalizeDataUrlMimeType(reader.result, mimeType) : reader.result);
return;
}
reject(new Error("Could not read image data."));
reject(new Error("Could not read attachment data."));
});
reader.addEventListener("error", () => {
reject(reader.error ?? new Error("Failed to read image."));
reject(reader.error ?? new Error("Failed to read attachment."));
});
reader.readAsDataURL(file);
});
@@ -193,9 +238,7 @@ export function resolveSendEnvMode(input: {
return input.isGitRepo ? input.requestedEnvMode : "local";
}
export function cloneComposerImageForRetry(
image: ComposerImageAttachment,
): ComposerImageAttachment {
export function cloneComposerImageForRetry(image: ComposerAttachment): ComposerAttachment {
if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
return image;
}
+9 -9
View File
@@ -162,7 +162,7 @@ import {
} from "../logicalProject";
import { buildDraftThreadRouteParams } from "../threadRoutes";
import {
type ComposerImageAttachment,
type ComposerAttachment,
type DraftThreadEnvMode,
useComposerDraftStore,
type DraftId,
@@ -261,8 +261,8 @@ import {
} from "../versionSkew";
import { useAssetUrls } from "../assets/assetUrls";
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
const ATTACHMENT_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more files without additional text. Respond using the conversation context and the attached file(s).]";
const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
const EMPTY_PROVIDERS: ServerProvider[] = [];
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
@@ -1190,7 +1190,7 @@ function ChatViewContent(props: ChatViewProps) {
: null,
);
const promptRef = useRef("");
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
const composerImagesRef = useRef<ComposerAttachment[]>([]);
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>([]);
const composerElementContextsRef = useRef<ElementContextDraft[]>([]);
const localComposerRef = useRef<ChatComposerHandle | null>(null);
@@ -4179,19 +4179,19 @@ function ChatViewContent(props: ChatViewProps) {
model: ctxSelectedModel,
models: ctxSelectedProviderModels,
effort: ctxSelectedPromptEffort,
text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT,
text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
});
const turnAttachmentsPromise = Promise.all(
composerImagesSnapshot.map(async (image) => ({
type: "image" as const,
type: image.type,
name: image.name,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
dataUrl: await readFileAsDataUrl(image.file),
dataUrl: await readFileAsDataUrl(image.file, image.mimeType),
})),
);
const optimisticAttachments = composerImagesSnapshot.map((image) => ({
type: "image" as const,
type: image.type,
id: image.id,
name: image.name,
mimeType: image.mimeType,
@@ -4253,7 +4253,7 @@ function ChatViewContent(props: ChatViewProps) {
let titleSeed = trimmed;
if (!titleSeed) {
if (firstComposerImageName) {
titleSeed = `Image: ${firstComposerImageName}`;
titleSeed = `${composerImagesSnapshot[0]?.type === "file" ? "File" : "Image"}: ${firstComposerImageName}`;
} else if (composerTerminalContextsSnapshot.length > 0) {
titleSeed = formatTerminalContextLabel(composerTerminalContextsSnapshot[0]!);
} else if (composerElementContextsSnapshot.length > 0) {
+49 -24
View File
@@ -43,13 +43,17 @@ import {
replaceTextRange,
shouldSubmitComposerOnEnter,
} from "../../composer-logic";
import { deriveComposerSendState, readFileAsDataUrl } from "../ChatView.logic";
import {
deriveComposerSendState,
readFileAsDataUrl,
resolveComposerAttachmentMimeType,
} from "../ChatView.logic";
import {
dataTransferHasComposerMention,
makeComposerMentionDragHandlers,
} from "./composerMentionDrag";
import {
type ComposerImageAttachment,
type ComposerAttachment,
type DraftId,
type PersistedComposerImageAttachment,
useComposerDraftStore,
@@ -101,6 +105,7 @@ import {
BotIcon,
CheckIcon,
CircleAlertIcon,
FileTextIcon,
ListTodoIcon,
PencilRulerIcon,
type LucideIcon,
@@ -130,6 +135,7 @@ import {
import { formatProviderSkillDisplayName } from "../../providerSkillPresentation";
import { searchProviderSkills } from "../../providerSkillSearch";
import { useMediaQuery } from "../../hooks/useMediaQuery";
import { formatAttachmentSizeLabel } from "../../lib/attachmentSize";
import type { ReviewCommentContext } from "../../reviewCommentContext";
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
@@ -425,7 +431,7 @@ export interface ChatComposerHandle {
/** Get the current prompt/effort/model state for use in send. */
getSendContext: () => {
prompt: string;
images: ComposerImageAttachment[];
images: ComposerAttachment[];
terminalContexts: TerminalContextDraft[];
elementContexts: ElementContextDraft[];
previewAnnotations: PreviewAnnotationPayload[];
@@ -516,7 +522,7 @@ export interface ChatComposerProps {
// Refs the parent needs kept in sync
promptRef: React.RefObject<string>;
composerImagesRef: React.RefObject<ComposerImageAttachment[]>;
composerImagesRef: React.RefObject<ComposerAttachment[]>;
composerTerminalContextsRef: React.RefObject<TerminalContextDraft[]>;
composerElementContextsRef: React.RefObject<ElementContextDraft[]>;
composerRef: React.RefObject<ChatComposerHandle | null>;
@@ -1175,14 +1181,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
);
const addComposerImage = useCallback(
(image: ComposerImageAttachment) => {
(image: ComposerAttachment) => {
addComposerDraftImage(composerDraftTarget, image);
},
[composerDraftTarget, addComposerDraftImage],
);
const addComposerImagesToDraft = useCallback(
(images: ComposerImageAttachment[]) => {
(images: ComposerAttachment[]) => {
addComposerDraftImages(composerDraftTarget, images);
},
[composerDraftTarget, addComposerDraftImages],
@@ -1390,8 +1396,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
await Promise.all(
composerImages.map(async (image) => {
try {
const dataUrl = await readFileAsDataUrl(image.file);
const dataUrl = await readFileAsDataUrl(image.file, image.mimeType);
stagedAttachmentById.set(image.id, {
type: image.type,
id: image.id,
name: image.name,
mimeType: image.mimeType,
@@ -1792,32 +1799,30 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
if (pendingUserInputs.length > 0) {
toastManager.add({
type: "error",
title: "Attach images after answering plan questions.",
title: "Attach files after answering plan questions.",
});
return;
}
const nextImages: ComposerImageAttachment[] = [];
const nextImages: ComposerAttachment[] = [];
let nextImageCount = composerImagesRef.current.length;
let error: string | null = null;
for (const file of files) {
if (!file.type.startsWith("image/")) {
error = `Unsupported file type for '${file.name}'. Please attach image files only.`;
continue;
}
if (file.size > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
error = `'${file.name}' exceeds the ${IMAGE_SIZE_LIMIT_LABEL} attachment limit.`;
continue;
}
if (nextImageCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`;
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`;
break;
}
const mimeType = resolveComposerAttachmentMimeType(file);
const isImage = mimeType.startsWith("image/");
const previewUrl = URL.createObjectURL(file);
nextImages.push({
type: "image",
type: isImage ? "image" : "file",
id: randomUUID(),
name: file.name || "image",
mimeType: file.type,
name: file.name || (isImage ? "image" : "file"),
mimeType,
sizeBytes: file.size,
previewUrl,
file,
@@ -1842,10 +1847,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const onComposerPaste = (event: React.ClipboardEvent<HTMLElement>) => {
const files = Array.from(event.clipboardData.files);
if (files.length === 0) return;
const imageFiles = files.filter((file) => file.type.startsWith("image/"));
if (imageFiles.length === 0) return;
event.preventDefault();
addComposerImages(imageFiles);
addComposerImages(files);
};
const onComposerDragEnter = (event: React.DragEvent<HTMLDivElement>) => {
@@ -2352,7 +2355,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
removeComposerDraftPreviewAnnotation(composerDraftTarget, annotationId)
}
onExpandImage={(imageId) => {
const preview = buildExpandedImagePreview(composerImages, imageId);
const preview = buildExpandedImagePreview(
composerImages.filter((attachment) => attachment.type === "image"),
imageId,
);
if (preview) onExpandImage(preview);
}}
className="mb-3"
@@ -2403,15 +2409,34 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
.map((image) => (
<div
key={image.id}
className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
className={
image.type === "file"
? "relative flex h-16 w-40 items-center gap-2 overflow-hidden rounded-lg border border-border/80 bg-background px-2"
: "relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
}
>
{image.previewUrl ? (
{image.type === "file" ? (
<>
<FileTextIcon className="size-5 shrink-0 text-muted-foreground" />
<div className="min-w-0 pr-5">
<div className="truncate text-xs" title={image.name}>
{image.name}
</div>
<div className="text-[10px] text-muted-foreground/70">
{formatAttachmentSizeLabel(image.sizeBytes)}
</div>
</div>
</>
) : image.previewUrl ? (
<button
type="button"
className="h-full w-full cursor-zoom-in"
aria-label={`Preview ${image.name}`}
onClick={() => {
const preview = buildExpandedImagePreview(composerImages, image.id);
const preview = buildExpandedImagePreview(
composerImages.filter((attachment) => attachment.type === "image"),
image.id,
);
if (!preview) return;
onExpandImage(preview);
}}
@@ -2,13 +2,13 @@ import type { PreviewAnnotationPayload } from "@t3tools/contracts";
import { Frame, MousePointerClick, Paintbrush, PenLine, X } from "lucide-react";
import type { ReactNode } from "react";
import type { ComposerImageAttachment } from "~/composerDraftStore";
import type { ComposerAttachment } from "~/composerDraftStore";
import { formatElementContextLabel, normalizeElementContextSelection } from "~/lib/elementContext";
import { cn } from "~/lib/utils";
interface ComposerPreviewAnnotationCardsProps {
annotations: ReadonlyArray<PreviewAnnotationPayload>;
images: ReadonlyArray<ComposerImageAttachment>;
images: ReadonlyArray<ComposerAttachment>;
onRemove: (annotationId: string) => void;
onExpandImage: (imageId: string) => void;
className?: string;
@@ -381,6 +381,88 @@ describe("MessagesTimeline", () => {
expect(onAnchorSizeChanged).toHaveBeenCalledWith(secondEntry.message.id, 240);
});
it("renders file attachments as chips with name and size instead of images", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const entry = {
...buildUserTimelineEntry("Please review the attached report."),
message: {
...buildUserTimelineEntry("Please review the attached report.").message,
attachments: [
{
type: "file" as const,
id: "attachment-file-1",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 2_048,
},
],
},
};
const markup = renderToStaticMarkup(
<MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
);
expect(markup).toContain("report.pdf");
expect(markup).toContain("2.0 KB");
expect(markup).toContain("lucide-file-text");
expect(markup).not.toContain("<img");
});
it("renders downloadable file attachment chips when a preview URL is available", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const entry = {
...buildUserTimelineEntry("Here is the file."),
message: {
...buildUserTimelineEntry("Here is the file.").message,
attachments: [
{
type: "file" as const,
id: "attachment-file-2",
name: "notes.txt",
mimeType: "text/plain",
sizeBytes: 512,
previewUrl: "data:text/plain;base64,aGVsbG8=",
},
],
},
};
const markup = renderToStaticMarkup(
<MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
);
expect(markup).toContain('download="notes.txt"');
expect(markup).toContain('href="data:text/plain;base64,aGVsbG8="');
expect(markup).toContain("512 B");
});
it("renders image attachments in the image grid without file chips", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const entry = {
...buildUserTimelineEntry("Take a look."),
message: {
...buildUserTimelineEntry("Take a look.").message,
attachments: [
{
type: "image" as const,
id: "attachment-image-1",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 1,
previewUrl: "data:image/png;base64,iVBORw0KGgo=",
},
],
},
};
const markup = renderToStaticMarkup(
<MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
);
expect(markup).toContain('src="data:image/png;base64,iVBORw0KGgo="');
expect(markup).toContain('alt="screenshot.png"');
expect(markup).not.toContain("lucide-file-text");
expect(markup).not.toContain("download=");
});
it("renders collapse controls for long user messages", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
@@ -49,6 +49,7 @@ import {
CircleAlertIcon,
EyeIcon,
FileDiffIcon,
FileTextIcon,
GlobeIcon,
HammerIcon,
MessageCircleIcon,
@@ -64,6 +65,7 @@ import {
} from "lucide-react";
import { Button } from "../ui/button";
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
import { formatAttachmentSizeLabel } from "~/lib/attachmentSize";
import { ProposedPlanCard } from "./ProposedPlanCard";
import { ChangedFilesTree } from "./ChangedFilesTree";
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
@@ -881,7 +883,10 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
...elementContextState.contexts,
];
const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));
const regularImages = userImages.filter((image) => !image.name.startsWith("preview-annotation-"));
const regularImages = userImages.filter(
(image) => image.type === "image" && !image.name.startsWith("preview-annotation-"),
);
const fileAttachments = userImages.filter((attachment) => attachment.type === "file");
const canRevertAgentWork = typeof row.revertTurnCount === "number";
return (
@@ -920,6 +925,38 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
))}
</div>
)}
{fileAttachments.length > 0 && (
<div className="mb-2 flex flex-wrap gap-1.5">
{fileAttachments.map((attachment) => {
const chipContent = (
<>
<FileTextIcon className="size-3.5 shrink-0 text-muted-foreground" />
<span className="max-w-48 truncate">{attachment.name}</span>
<span className="text-muted-foreground/70">
{formatAttachmentSizeLabel(attachment.sizeBytes)}
</span>
</>
);
const chipClassName =
"inline-flex items-center gap-1.5 rounded-md border border-border/80 bg-background/70 px-2 py-1 text-[11px]";
return attachment.previewUrl ? (
<a
key={attachment.id}
href={attachment.previewUrl}
download={attachment.name}
className={`${chipClassName} hover:bg-background`}
aria-label={`Download ${attachment.name}`}
>
{chipContent}
</a>
) : (
<span key={attachment.id} className={chipClassName}>
{chipContent}
</span>
);
})}
</div>
)}
{previewAnnotations.map((annotation, index) => (
<UserMessagePreviewAnnotationCard
key={annotation.id}
+145
View File
@@ -65,6 +65,7 @@ import {
markPromotedDraftThreadByRef,
markPromotedDraftThreads,
markPromotedDraftThreadsByRef,
type ComposerFileAttachment,
type ComposerImageAttachment,
useComposerDraftStore,
DraftId,
@@ -104,6 +105,33 @@ function makeImage(input: {
};
}
function makeFile(input: {
id: string;
previewUrl: string;
name?: string;
mimeType?: string;
sizeBytes?: number;
lastModified?: number;
}): ComposerFileAttachment {
const name = input.name ?? "report.pdf";
const mimeType = input.mimeType ?? "application/pdf";
const sizeBytes = input.sizeBytes ?? 4;
const lastModified = input.lastModified ?? 1_700_000_000_000;
const file = new File([new Uint8Array(sizeBytes).fill(1)], name, {
type: mimeType,
lastModified,
});
return {
type: "file",
id: input.id,
name,
mimeType,
sizeBytes: file.size,
previewUrl: input.previewUrl,
file,
};
}
function makeTerminalContext(input: {
id: string;
text?: string;
@@ -345,6 +373,123 @@ describe("composerDraftStore syncPersistedAttachments", () => {
});
});
describe("composerDraftStore file attachments", () => {
const threadId = ThreadId.make("thread-file-attachments");
const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
beforeEach(() => {
removeLocalStorageItem(COMPOSER_DRAFT_STORAGE_KEY);
resetComposerDraftStore();
});
afterEach(() => {
removeLocalStorageItem(COMPOSER_DRAFT_STORAGE_KEY);
});
function mergePersistedDraft(attachment: Record<string, unknown>) {
const persistApi = useComposerDraftStore.persist as unknown as {
getOptions: () => {
merge: (
persistedState: unknown,
currentState: ReturnType<typeof useComposerDraftStore.getState>,
) => ReturnType<typeof useComposerDraftStore.getState>;
};
};
return persistApi.getOptions().merge(
{
draftsByThreadId: {
[threadId]: {
prompt: "",
attachments: [attachment],
},
},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectKey: {},
},
useComposerDraftStore.getInitialState(),
);
}
it("hydrates persisted attachments without a type as images (legacy drafts)", () => {
const mergedState = mergePersistedDraft({
id: "img-legacy",
name: "legacy.png",
mimeType: "image/png",
sizeBytes: 5,
dataUrl: "data:image/png;base64,aGVsbG8=",
});
expect(mergedState.draftsByThreadKey[threadKeyFor(threadId)]?.images).toMatchObject([
{
type: "image",
id: "img-legacy",
name: "legacy.png",
mimeType: "image/png",
sizeBytes: 5,
previewUrl: "data:image/png;base64,aGVsbG8=",
},
]);
});
it("hydrates persisted attachments with type file as file attachments", () => {
const mergedState = mergePersistedDraft({
type: "file",
id: "file-persisted",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 5,
dataUrl: "data:application/pdf;base64,aGVsbG8=",
});
expect(mergedState.draftsByThreadKey[threadKeyFor(threadId)]?.images).toMatchObject([
{
type: "file",
id: "file-persisted",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 5,
previewUrl: "data:application/pdf;base64,aGVsbG8=",
},
]);
});
it("persists the file type for staged file attachments (round trip)", () => {
const attachment = makeFile({
id: "file-round-trip",
previewUrl: "data:application/pdf;base64,aGVsbG8=",
});
useComposerDraftStore.getState().addImage(threadRef, attachment);
useComposerDraftStore.getState().syncPersistedAttachments(threadRef, [
{
type: "file",
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
dataUrl: attachment.previewUrl,
},
]);
const persistApi = useComposerDraftStore.persist as unknown as {
getOptions: () => {
partialize: (state: ReturnType<typeof useComposerDraftStore.getState>) => unknown;
};
};
const persisted = persistApi.getOptions().partialize(useComposerDraftStore.getState()) as {
draftsByThreadKey?: Record<string, { attachments?: Array<Record<string, unknown>> }>;
};
expect(
persisted.draftsByThreadKey?.[threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]?.attachments?.[0],
).toMatchObject({
type: "file",
id: "file-round-trip",
name: "report.pdf",
mimeType: "application/pdf",
});
});
});
describe("composerDraftStore terminal contexts", () => {
const threadId = ThreadId.make("thread-dedupe");
const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
+26 -10
View File
@@ -33,7 +33,12 @@ import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model"
import { useMemo } from "react";
import { getLocalStorageItem } from "./hooks/useLocalStorage";
import { resolveAppModelSelection, resolveAppModelSelectionForInstance } from "./modelSelection";
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type ChatImageAttachment } from "./types";
import {
DEFAULT_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
type ChatFileAttachment,
type ChatImageAttachment,
} from "./types";
import {
type TerminalContextDraft,
ensureInlineTerminalContextPlaceholders,
@@ -79,6 +84,8 @@ if (typeof window !== "undefined" && typeof window.addEventListener === "functio
}
export const PersistedComposerImageAttachment = Schema.Struct({
// Missing on drafts persisted before file attachments existed → "image".
type: Schema.optionalKey(Schema.Literals(["image", "file"])),
id: Schema.String,
name: Schema.String,
mimeType: Schema.String,
@@ -92,6 +99,13 @@ export interface ComposerImageAttachment extends Omit<ChatImageAttachment, "prev
file: File;
}
export interface ComposerFileAttachment extends Omit<ChatFileAttachment, "previewUrl"> {
previewUrl: string;
file: File;
}
export type ComposerAttachment = ComposerImageAttachment | ComposerFileAttachment;
const PersistedTerminalContextDraft = Schema.Struct({
id: Schema.String,
threadId: ThreadId,
@@ -249,7 +263,7 @@ const PersistedComposerDraftStoreStorage = Schema.Struct({
*/
export interface ComposerThreadDraftState {
prompt: string;
images: ComposerImageAttachment[];
images: ComposerAttachment[];
nonPersistedImageIds: string[];
persistedAttachments: PersistedComposerImageAttachment[];
terminalContexts: TerminalContextDraft[];
@@ -434,8 +448,8 @@ interface ComposerDraftStoreState {
threadRef: ComposerThreadTarget,
interactionMode: ProviderInteractionMode | null | undefined,
) => void;
addImage: (threadRef: ComposerThreadTarget, image: ComposerImageAttachment) => void;
addImages: (threadRef: ComposerThreadTarget, images: ComposerImageAttachment[]) => void;
addImage: (threadRef: ComposerThreadTarget, image: ComposerAttachment) => void;
addImages: (threadRef: ComposerThreadTarget, images: ComposerAttachment[]) => void;
removeImage: (threadRef: ComposerThreadTarget, imageId: string) => void;
insertTerminalContext: (
threadRef: ComposerThreadTarget,
@@ -551,7 +565,7 @@ const EMPTY_PERSISTED_DRAFT_STORE_STATE = Object.freeze<PersistedComposerDraftSt
stickyActiveProvider: null,
});
const EMPTY_IMAGES: ComposerImageAttachment[] = [];
const EMPTY_IMAGES: ComposerAttachment[] = [];
const EMPTY_IDS: string[] = [];
const EMPTY_PERSISTED_ATTACHMENTS: PersistedComposerImageAttachment[] = [];
const EMPTY_TERMINAL_CONTEXTS: TerminalContextDraft[] = [];
@@ -609,7 +623,7 @@ export function createEmptyThreadDraft(): ComposerThreadDraftState {
};
}
function composerImageDedupKey(image: ComposerImageAttachment): string {
function composerImageDedupKey(image: ComposerAttachment): string {
// Keep this independent from File.lastModified so dedupe is stable for hydrated
// images reconstructed from localStorage (which get a fresh lastModified value).
return `${image.mimeType}\u0000${image.sizeBytes}\u0000${image.name}`;
@@ -1059,7 +1073,9 @@ function normalizePersistedAttachment(value: unknown): PersistedComposerImageAtt
) {
return null;
}
const type = candidate.type;
return {
...(type === "image" || type === "file" ? { type } : {}),
id,
name,
mimeType,
@@ -2084,21 +2100,21 @@ function hydratePersistedComposerImageAttachment(
function hydrateImagesFromPersisted(
attachments: ReadonlyArray<PersistedComposerImageAttachment>,
): ComposerImageAttachment[] {
): ComposerAttachment[] {
return attachments.flatMap((attachment) => {
const file = hydratePersistedComposerImageAttachment(attachment);
if (!file) return [];
return [
{
type: "image" as const,
type: attachment.type ?? ("image" as const),
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
previewUrl: attachment.dataUrl,
file,
} satisfies ComposerImageAttachment,
} satisfies ComposerAttachment,
];
});
}
@@ -2856,7 +2872,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
existing.images.map((image) => composerImageDedupKey(image)),
);
const acceptedPreviewUrls = new Set(existing.images.map((image) => image.previewUrl));
const dedupedIncoming: ComposerImageAttachment[] = [];
const dedupedIncoming: ComposerAttachment[] = [];
for (const image of images) {
const dedupKey = composerImageDedupKey(image);
if (existingIds.has(image.id) || existingDedupKeys.has(dedupKey)) {
+37
View File
@@ -136,4 +136,41 @@ describe("buildBootstrapInput", () => {
expect(result.text).toContain("Attached image");
expect(result.text).toContain("screenshot.png");
});
it("captures mixed image and file attachment context in transcript blocks", () => {
const result = buildBootstrapInput(
[
{
id: messageId("u-mixed"),
role: "user",
text: "Compare the screenshot with the report.",
attachments: [
{
type: "image",
id: "img-1",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 2_048,
},
{
type: "file",
id: "file-1",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 4_096,
},
],
createdAt: "2026-02-09T00:00:00.000Z",
turnId: null,
updatedAt: "2026-02-09T00:00:00.000Z",
streaming: false,
},
],
"What differs?",
1_500,
);
expect(result.text).toContain("[Attached image: screenshot.png]");
expect(result.text).toContain("[Attached file: report.pdf]");
});
});
+17 -5
View File
@@ -18,18 +18,30 @@ function messageRoleLabel(message: ChatMessage): "USER" | "ASSISTANT" {
return message.role === "assistant" ? "ASSISTANT" : "USER";
}
function attachmentSummary(message: ChatMessage): string | null {
const imageAttachments = message.attachments?.filter((attachment) => attachment.type === "image");
const count = imageAttachments?.length ?? 0;
function attachmentSummaryOfType(
message: ChatMessage,
type: "image" | "file",
label: string,
): string | null {
const typedAttachments = message.attachments?.filter((attachment) => attachment.type === type);
const count = typedAttachments?.length ?? 0;
if (count === 0) {
return null;
}
const names = imageAttachments?.slice(0, 3).map((image) => image.name) ?? [];
const names = typedAttachments?.slice(0, 3).map((attachment) => attachment.name) ?? [];
const namesSummary = names.join(", ");
const extraCount = count - names.length;
const extraSummary = extraCount > 0 ? ` (+${extraCount} more)` : "";
return `[Attached image${count === 1 ? "" : "s"}: ${namesSummary}${extraSummary}]`;
return `[Attached ${label}${count === 1 ? "" : "s"}: ${namesSummary}${extraSummary}]`;
}
function attachmentSummary(message: ChatMessage): string | null {
const summaries = [
attachmentSummaryOfType(message, "image", "image"),
attachmentSummaryOfType(message, "file", "file"),
].filter((summary) => summary !== null);
return summaries.length > 0 ? summaries.join("\n") : null;
}
function buildMessageBlock(message: ChatMessage): string {
+22
View File
@@ -0,0 +1,22 @@
import { describe, expect, it } from "vite-plus/test";
import { formatAttachmentSizeLabel } from "./attachmentSize";
describe("formatAttachmentSizeLabel", () => {
it("formats sub-kilobyte sizes in bytes", () => {
expect(formatAttachmentSizeLabel(0)).toBe("0 B");
expect(formatAttachmentSizeLabel(512)).toBe("512 B");
expect(formatAttachmentSizeLabel(1_023)).toBe("1023 B");
});
it("formats kilobyte sizes with one decimal", () => {
expect(formatAttachmentSizeLabel(1_024)).toBe("1.0 KB");
expect(formatAttachmentSizeLabel(2_048)).toBe("2.0 KB");
expect(formatAttachmentSizeLabel(1_024 * 1_024 - 1)).toBe("1024.0 KB");
});
it("formats megabyte sizes with one decimal", () => {
expect(formatAttachmentSizeLabel(1_024 * 1_024)).toBe("1.0 MB");
expect(formatAttachmentSizeLabel(2_202_010)).toBe("2.1 MB");
});
});
+9
View File
@@ -0,0 +1,9 @@
export function formatAttachmentSizeLabel(sizeBytes: number): string {
if (sizeBytes >= 1024 * 1024) {
return `${(sizeBytes / (1024 * 1024)).toFixed(1)} MB`;
}
if (sizeBytes >= 1024) {
return `${(sizeBytes / 1024).toFixed(1)} KB`;
}
return `${sizeBytes} B`;
}
+6 -1
View File
@@ -1,4 +1,5 @@
import type {
ChatFileAttachment as ContractChatFileAttachment,
ChatImageAttachment as ContractChatImageAttachment,
OrchestrationCheckpointFile,
OrchestrationCheckpointSummary,
@@ -35,7 +36,11 @@ export interface ChatImageAttachment extends ContractChatImageAttachment {
readonly previewUrl?: string;
}
export type ChatAttachment = ChatImageAttachment;
export interface ChatFileAttachment extends ContractChatFileAttachment {
readonly previewUrl?: string;
}
export type ChatAttachment = ChatImageAttachment | ChatFileAttachment;
export interface ChatMessage extends Omit<OrchestrationMessage, "attachments"> {
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
@@ -3,6 +3,9 @@ import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import {
ChatAttachment,
ChatFileAttachment,
ChatImageAttachment,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
ModelSelection,
@@ -743,3 +746,80 @@ it.effect("ModelSelection rejects malformed instance ids", () =>
assert.strictEqual(result._tag, "Failure");
}),
);
// ── ChatAttachment: image/file union ──────────────────────────────────
const decodeChatAttachment = Schema.decodeUnknownEffect(ChatAttachment);
const decodeChatAttachmentArray = Schema.decodeUnknownEffect(Schema.Array(ChatAttachment));
const decodeChatImageAttachment = Schema.decodeUnknownEffect(ChatImageAttachment);
const decodeChatFileAttachment = Schema.decodeUnknownEffect(ChatFileAttachment);
it.effect("ChatAttachment decodes a file attachment with a non-image mime type", () =>
Effect.gen(function* () {
const parsed = yield* decodeChatAttachment({
type: "file",
id: "file-1",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 2_048,
});
assert.strictEqual(parsed.type, "file");
assert.strictEqual(parsed.name, "report.pdf");
assert.strictEqual(parsed.mimeType, "application/pdf");
assert.strictEqual(parsed.sizeBytes, 2_048);
}),
);
it.effect("ChatAttachment arrays still decode legacy image-only attachments", () =>
Effect.gen(function* () {
const parsed = yield* decodeChatAttachmentArray([
{
type: "image",
id: "img-1",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 1_024,
},
{
type: "image",
id: "img-2",
name: "diagram.jpeg",
mimeType: "image/jpeg",
sizeBytes: 4_096,
},
]);
assert.strictEqual(parsed.length, 2);
assert.strictEqual(parsed[0]?.type, "image");
assert.strictEqual(parsed[1]?.type, "image");
}),
);
it.effect("ChatImageAttachment rejects non-image mime types", () =>
Effect.gen(function* () {
const result = yield* Effect.exit(
decodeChatImageAttachment({
type: "image",
id: "img-1",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 2_048,
}),
);
assert.strictEqual(result._tag, "Failure");
}),
);
it.effect("ChatFileAttachment rejects sizeBytes over the 10MB limit", () =>
Effect.gen(function* () {
const result = yield* Effect.exit(
decodeChatFileAttachment({
type: "file",
id: "file-1",
name: "big.bin",
mimeType: "application/octet-stream",
sizeBytes: 10 * 1024 * 1024 + 1,
}),
);
assert.strictEqual(result._tag, "Failure");
}),
);
+22 -2
View File
@@ -173,9 +173,29 @@ const UploadChatImageAttachment = Schema.Struct({
});
export type UploadChatImageAttachment = typeof UploadChatImageAttachment.Type;
export const ChatAttachment = Schema.Union([ChatImageAttachment]);
export const ChatFileAttachment = Schema.Struct({
type: Schema.Literal("file"),
id: ChatAttachmentId,
name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100)),
sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)),
});
export type ChatFileAttachment = typeof ChatFileAttachment.Type;
const UploadChatFileAttachment = Schema.Struct({
type: Schema.Literal("file"),
name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100)),
sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)),
dataUrl: TrimmedNonEmptyString.check(
Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS),
),
});
export type UploadChatFileAttachment = typeof UploadChatFileAttachment.Type;
export const ChatAttachment = Schema.Union([ChatImageAttachment, ChatFileAttachment]);
export type ChatAttachment = typeof ChatAttachment.Type;
const UploadChatAttachment = Schema.Union([UploadChatImageAttachment]);
const UploadChatAttachment = Schema.Union([UploadChatImageAttachment, UploadChatFileAttachment]);
export type UploadChatAttachment = typeof UploadChatAttachment.Type;
export const ProjectScriptIcon = Schema.Literals([