feat(server): accept PDF, ZIP, and other file uploads up to 50MB (#8235)
Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
88be5631ff
commit
8f49132214
38 files changed
+1042
-89
No files matched your search
@@ -1040,7 +1040,9 @@ function renderFeedEntry(
|
||||
const isUser = message.role === "user";
|
||||
const styles = isUser ? markdownStyles.user : markdownStyles.assistant;
|
||||
const timestampLabel = formatMessageTime(isUser ? message.createdAt : message.updatedAt);
|
||||
const attachments = message.attachments ?? [];
|
||||
const attachments = (message.attachments ?? []).filter(
|
||||
(attachment) => attachment.type === "image",
|
||||
);
|
||||
const hasReviewCommentContext = message.text.includes("<review_comment");
|
||||
// A bubble that sizes itself from its content cannot lay out a block whose
|
||||
// intrinsic width overflows `maxWidth`: Android positions the bubble's
|
||||
|
||||
@@ -37,7 +37,7 @@ import {
|
||||
timingSafeEqualBase64Url,
|
||||
} from "../auth/utils.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import { resolveAttachmentPathById } from "../attachmentStore.ts";
|
||||
import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
@@ -79,6 +79,13 @@ const AssetClaimsSchema = Schema.Union([
|
||||
version: Schema.Literal(1),
|
||||
kind: Schema.Literal("attachment"),
|
||||
attachmentId: Schema.String,
|
||||
/** Decided at mint time. Absent tokens (from before this field) serve
|
||||
inline, which is only ever the image case. */
|
||||
download: Schema.optionalKey(Schema.Boolean),
|
||||
/** Display name and mime the caller supplied at mint time; drive the
|
||||
download filename and Content-Type. */
|
||||
fileName: Schema.optionalKey(Schema.String),
|
||||
mimeType: Schema.optionalKey(Schema.String),
|
||||
expiresAt: Schema.Number,
|
||||
}),
|
||||
Schema.Struct({
|
||||
@@ -101,7 +108,13 @@ 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;
|
||||
readonly fileName?: string;
|
||||
readonly mimeType?: string;
|
||||
};
|
||||
|
||||
function decodeClaims(encodedPayload: string): AssetClaims | null {
|
||||
try {
|
||||
@@ -286,13 +299,20 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
resource: input.resource,
|
||||
});
|
||||
}
|
||||
// Generic files carry their extension inside the attachment id (that
|
||||
// shape resolves the on-disk path); images do not. Only generic files
|
||||
// download, images render inline in chat.
|
||||
const isGenericFile = parseAttachmentFileExtension(input.resource.attachmentId) !== null;
|
||||
claims = {
|
||||
version: 1,
|
||||
kind: "attachment",
|
||||
attachmentId: input.resource.attachmentId,
|
||||
...(isGenericFile ? { download: true } : {}),
|
||||
...(input.resource.fileName !== undefined ? { fileName: input.resource.fileName } : {}),
|
||||
...(input.resource.mimeType !== undefined ? { mimeType: input.resource.mimeType } : {}),
|
||||
expiresAt,
|
||||
};
|
||||
fileName = path.basename(attachmentPath);
|
||||
fileName = input.resource.fileName ?? path.basename(attachmentPath);
|
||||
break;
|
||||
}
|
||||
case "project-favicon": {
|
||||
@@ -464,7 +484,13 @@ 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)
|
||||
? ({
|
||||
kind: "file",
|
||||
path: attachmentPath,
|
||||
...(claims.download ? { download: true } : {}),
|
||||
...(claims.fileName !== undefined ? { fileName: claims.fileName } : {}),
|
||||
...(claims.mimeType !== undefined ? { mimeType: claims.mimeType } : {}),
|
||||
} satisfies ResolvedAsset)
|
||||
: null;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,11 +4,16 @@ import * as NodePath from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import { base64UrlEncode, signPayload } from "../auth/utils.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import { parseThreadSegmentFromAttachmentId } from "../attachmentStore.ts";
|
||||
import {
|
||||
@@ -30,6 +35,19 @@ const uploadInput = {
|
||||
sizeBytes: 6,
|
||||
} as const;
|
||||
|
||||
const LegacyAttachmentUploadClaims = Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
kind: Schema.Literal("attachment-upload"),
|
||||
attachmentId: Schema.String,
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
expiresAt: Schema.Number,
|
||||
});
|
||||
const encodeLegacyAttachmentUploadClaims = Schema.encodeEffect(
|
||||
Schema.fromJsonString(LegacyAttachmentUploadClaims),
|
||||
);
|
||||
|
||||
describe("AttachmentUpload", () => {
|
||||
it.effect("signs the attachment metadata and validates the upload token", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -59,6 +77,31 @@ describe("AttachmentUpload", () => {
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("accepts unexpired image upload tokens issued before file support", () =>
|
||||
Effect.gen(function* () {
|
||||
const issued = yield* issueAttachmentUploadUrl(uploadInput);
|
||||
const secretStore = yield* ServerSecretStore.ServerSecretStore;
|
||||
const secret = yield* secretStore.getOrCreateRandom("asset-access-signing-key", 32);
|
||||
const encodedPayload = base64UrlEncode(
|
||||
yield* encodeLegacyAttachmentUploadClaims({
|
||||
version: 1,
|
||||
kind: "attachment-upload",
|
||||
attachmentId: issued.attachmentId,
|
||||
name: uploadInput.name,
|
||||
mimeType: uploadInput.mimeType,
|
||||
sizeBytes: uploadInput.sizeBytes,
|
||||
expiresAt: issued.expiresAt,
|
||||
}),
|
||||
);
|
||||
const legacyToken = `${encodedPayload}.${signPayload(encodedPayload, secret)}`;
|
||||
|
||||
expect(yield* validateAttachmentUploadToken(legacyToken)).toMatchObject({
|
||||
type: "image",
|
||||
attachmentId: issued.attachmentId,
|
||||
});
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects expired upload tokens", () =>
|
||||
Effect.gen(function* () {
|
||||
const issued = yield* issueAttachmentUploadUrl(uploadInput);
|
||||
@@ -108,6 +151,85 @@ describe("AttachmentUpload", () => {
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("streams generic files to a path with their original extension", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const issued = yield* issueAttachmentUploadUrl({
|
||||
type: "file",
|
||||
name: "report.PDF",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 6,
|
||||
});
|
||||
const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
|
||||
const claims = yield* validateAttachmentUploadToken(token);
|
||||
if (!claims) {
|
||||
throw new Error("Expected valid upload claims.");
|
||||
}
|
||||
|
||||
expect(
|
||||
yield* storeAttachmentUpload(
|
||||
claims,
|
||||
Stream.make(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])),
|
||||
),
|
||||
).toEqual({ ok: true });
|
||||
expect(issued.attachmentId).toMatch(/-pdf$/);
|
||||
expect(
|
||||
NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${issued.attachmentId}.pdf`)),
|
||||
).toEqual(Buffer.from([1, 2, 3, 4, 5, 6]));
|
||||
|
||||
yield* deletePendingAttachment(issued.attachmentId);
|
||||
expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([]);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("removes partial streamed uploads that exceed their signed size", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const issued = yield* issueAttachmentUploadUrl(uploadInput);
|
||||
const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
|
||||
const claims = yield* validateAttachmentUploadToken(token);
|
||||
if (!claims) {
|
||||
throw new Error("Expected valid upload claims.");
|
||||
}
|
||||
|
||||
expect(yield* storeAttachmentUpload(claims, Stream.make(new Uint8Array(7)))).toMatchObject({
|
||||
ok: false,
|
||||
status: 400,
|
||||
});
|
||||
expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([]);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("removes partial streamed uploads when the upload is interrupted", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const issued = yield* issueAttachmentUploadUrl(uploadInput);
|
||||
const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
|
||||
const claims = yield* validateAttachmentUploadToken(token);
|
||||
if (!claims) {
|
||||
throw new Error("Expected valid upload claims.");
|
||||
}
|
||||
|
||||
const nextChunkRequested = yield* Deferred.make<void>();
|
||||
const body = Stream.make(new Uint8Array([1, 2, 3])).pipe(
|
||||
Stream.concat(
|
||||
Stream.fromEffect(
|
||||
Deferred.succeed(nextChunkRequested, undefined).pipe(Effect.andThen(Effect.never)),
|
||||
),
|
||||
),
|
||||
);
|
||||
const upload = yield* storeAttachmentUpload(claims, body).pipe(Effect.forkScoped);
|
||||
|
||||
yield* Deferred.await(nextChunkRequested);
|
||||
expect(
|
||||
NodeFS.readdirSync(config.attachmentsDir).filter((entry) => entry.endsWith(".part")),
|
||||
).toHaveLength(1);
|
||||
|
||||
yield* Fiber.interrupt(upload);
|
||||
expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([]);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("deletes pending uploads without deleting thread-owned copies", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
|
||||
@@ -12,8 +12,11 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
|
||||
import {
|
||||
attachmentFileExtension,
|
||||
createPendingAttachmentId,
|
||||
parseThreadSegmentFromAttachmentId,
|
||||
PENDING_ATTACHMENT_THREAD_SEGMENT,
|
||||
@@ -41,6 +44,9 @@ const lastPendingSweepByDirectory = new Map<string, number>();
|
||||
const AttachmentUploadClaims = Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
kind: Schema.Literal("attachment-upload"),
|
||||
type: Schema.Literals(["image", "file"]).pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed("image" as const)),
|
||||
),
|
||||
attachmentId: Schema.String,
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
@@ -89,12 +95,16 @@ export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(f
|
||||
}
|
||||
}
|
||||
|
||||
const attachmentId = createPendingAttachmentId();
|
||||
const attachmentType = input.type ?? "image";
|
||||
const attachmentId = createPendingAttachmentId(
|
||||
attachmentType === "file" ? attachmentFileExtension(input.name) : undefined,
|
||||
);
|
||||
const expiresAt = nowMs + ATTACHMENT_UPLOAD_URL_TTL_MS;
|
||||
const encodedPayload = base64UrlEncode(
|
||||
encodeAttachmentUploadClaims({
|
||||
version: 1,
|
||||
kind: "attachment-upload",
|
||||
type: attachmentType,
|
||||
attachmentId,
|
||||
name: input.name,
|
||||
mimeType: input.mimeType,
|
||||
@@ -141,18 +151,21 @@ export type StoreAttachmentUploadResult =
|
||||
|
||||
export const storeAttachmentUpload = Effect.fn("AttachmentUpload.store")(function* (
|
||||
claims: AttachmentUploadClaims,
|
||||
bytes: Uint8Array,
|
||||
body: Uint8Array | HttpServerRequest.HttpServerRequest["stream"],
|
||||
) {
|
||||
if (bytes.byteLength !== claims.sizeBytes) {
|
||||
if (body instanceof Uint8Array && body.byteLength !== claims.sizeBytes) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 400,
|
||||
detail: `Body was ${bytes.byteLength} bytes, expected ${claims.sizeBytes}.`,
|
||||
detail: `Body was ${body.byteLength} bytes, expected ${claims.sizeBytes}.`,
|
||||
} satisfies StoreAttachmentUploadResult;
|
||||
}
|
||||
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const extension = inferImageExtension({ mimeType: claims.mimeType, fileName: claims.name });
|
||||
const extension =
|
||||
claims.type === "file"
|
||||
? attachmentFileExtension(claims.name)
|
||||
: inferImageExtension({ mimeType: claims.mimeType, fileName: claims.name });
|
||||
const relativePath = `${claims.attachmentId}${extension}`;
|
||||
const finalPath = resolveAttachmentRelativePath({
|
||||
attachmentsDir: config.attachmentsDir,
|
||||
@@ -168,21 +181,34 @@ export const storeAttachmentUpload = Effect.fn("AttachmentUpload.store")(functio
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
let receivedBytes = 0;
|
||||
const bodyStream = body instanceof Uint8Array ? Stream.make(body) : body;
|
||||
return yield* Effect.gen(function* () {
|
||||
yield* fileSystem.makeDirectory(path.dirname(finalPath), { recursive: true });
|
||||
yield* fileSystem.writeFile(partPath, bytes);
|
||||
yield* Stream.run(
|
||||
bodyStream.pipe(
|
||||
Stream.takeWhile((chunk) => {
|
||||
receivedBytes += chunk.byteLength;
|
||||
return receivedBytes <= claims.sizeBytes;
|
||||
}),
|
||||
),
|
||||
fileSystem.sink(partPath),
|
||||
);
|
||||
if (receivedBytes !== claims.sizeBytes) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 400,
|
||||
detail: `Body was ${receivedBytes} bytes, expected ${claims.sizeBytes}.`,
|
||||
} satisfies StoreAttachmentUploadResult;
|
||||
}
|
||||
yield* fileSystem.rename(partPath, finalPath);
|
||||
return { ok: true } satisfies StoreAttachmentUploadResult;
|
||||
}).pipe(
|
||||
Effect.catch((cause) =>
|
||||
fileSystem.remove(partPath, { force: true }).pipe(
|
||||
Effect.orElseSucceed(() => undefined),
|
||||
Effect.andThen(
|
||||
Effect.logError("Failed to persist attachment upload.", {
|
||||
attachmentId: claims.attachmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.logError("Failed to persist attachment upload.", {
|
||||
attachmentId: claims.attachmentId,
|
||||
cause,
|
||||
}).pipe(
|
||||
Effect.as({
|
||||
ok: false,
|
||||
status: 500,
|
||||
@@ -190,6 +216,9 @@ export const storeAttachmentUpload = Effect.fn("AttachmentUpload.store")(functio
|
||||
} satisfies StoreAttachmentUploadResult),
|
||||
),
|
||||
),
|
||||
Effect.ensuring(
|
||||
fileSystem.remove(partPath, { force: true }).pipe(Effect.orElseSucceed(() => undefined)),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -6,9 +6,11 @@ import * as NodePath from "node:path";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
attachmentFileExtension,
|
||||
createAttachmentId,
|
||||
createPendingAttachmentId,
|
||||
parseAttachmentUuid,
|
||||
parseAttachmentFileExtension,
|
||||
planAttachmentClaim,
|
||||
parseThreadSegmentFromAttachmentId,
|
||||
resolveAttachmentPathById,
|
||||
@@ -58,6 +60,21 @@ describe("attachmentStore", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves safe file extensions in attachment ids and paths", () => {
|
||||
const attachmentId = createPendingAttachmentId(".PDF");
|
||||
|
||||
expect(parseThreadSegmentFromAttachmentId(attachmentId)).toBe("pending");
|
||||
expect(parseAttachmentUuid(attachmentId)).toMatch(/^[a-f0-9-]{36}$/);
|
||||
expect(parseAttachmentFileExtension(attachmentId)).toBe("pdf");
|
||||
expect(attachmentFileExtension("report.PDF")).toBe(".pdf");
|
||||
expect(attachmentFileExtension("report")).toBe(".bin");
|
||||
expect(attachmentFileExtension("report.extensiontoolong")).toBe(".bin");
|
||||
// ".part" is the in-flight upload suffix; storing it would make the file
|
||||
// look like a stale partial to the sweep.
|
||||
expect(attachmentFileExtension("archive.part")).toBe(".bin");
|
||||
expect(createAttachmentId("x".repeat(80), ".abcdefghij")?.length).toBeLessThanOrEqual(128);
|
||||
});
|
||||
|
||||
it("resolves attachment path by id using the extension that exists on disk", () => {
|
||||
const attachmentsDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
|
||||
@@ -92,6 +109,21 @@ describe("attachmentStore", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("resolves generic attachments without scanning the attachment directory", () => {
|
||||
const attachmentsDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3code-file-attachment-"),
|
||||
);
|
||||
try {
|
||||
const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001-zip";
|
||||
const archivePath = NodePath.join(attachmentsDir, `${attachmentId}.zip`);
|
||||
NodeFS.writeFileSync(archivePath, Buffer.from("archive"));
|
||||
|
||||
expect(resolveAttachmentPathById({ attachmentsDir, attachmentId })).toBe(archivePath);
|
||||
} finally {
|
||||
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("plans pending attachment claims with direct filename lookups", () => {
|
||||
const attachmentsDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-claim-"),
|
||||
@@ -147,15 +179,17 @@ describe("attachmentStore", () => {
|
||||
const oldTimeSeconds = (now - 2 * 24 * 60 * 60 * 1000) / 1000;
|
||||
const uuid = "00000000-0000-4000-8000-000000000002";
|
||||
const pendingPath = NodePath.join(attachmentsDir, `pending-${uuid}.png`);
|
||||
const pendingFilePath = NodePath.join(attachmentsDir, `pending-${uuid}-pdf.pdf`);
|
||||
const threadPath = NodePath.join(attachmentsDir, `thread-1-${uuid}.png`);
|
||||
const partialPath = NodePath.join(attachmentsDir, `${uuid}.part`);
|
||||
for (const filePath of [pendingPath, threadPath, partialPath]) {
|
||||
for (const filePath of [pendingPath, pendingFilePath, threadPath, partialPath]) {
|
||||
NodeFS.writeFileSync(filePath, Buffer.from("pixels"));
|
||||
NodeFS.utimesSync(filePath, oldTimeSeconds, oldTimeSeconds);
|
||||
}
|
||||
|
||||
expect(sweepStalePendingAttachments({ attachmentsDir, nowMs: now })).toEqual({ deleted: 2 });
|
||||
expect(sweepStalePendingAttachments({ attachmentsDir, nowMs: now })).toEqual({ deleted: 3 });
|
||||
expect(NodeFS.existsSync(pendingPath)).toBe(false);
|
||||
expect(NodeFS.existsSync(pendingFilePath)).toBe(false);
|
||||
expect(NodeFS.existsSync(partialPath)).toBe(false);
|
||||
expect(NodeFS.existsSync(threadPath)).toBe(true);
|
||||
} finally {
|
||||
|
||||
@@ -15,8 +15,9 @@ const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_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}";
|
||||
const ATTACHMENT_ID_FILE_EXTENSION_PATTERN = "[a-z0-9]{1,10}";
|
||||
const ATTACHMENT_ID_PATTERN = new RegExp(
|
||||
`^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,
|
||||
`^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})(?:-(${ATTACHMENT_ID_FILE_EXTENSION_PATTERN}))?$`,
|
||||
"i",
|
||||
);
|
||||
|
||||
@@ -39,8 +40,28 @@ export function toSafeThreadAttachmentSegment(threadId: string): string | null {
|
||||
return segment === PENDING_ATTACHMENT_THREAD_SEGMENT ? "_pending" : segment;
|
||||
}
|
||||
|
||||
export function createPendingAttachmentId(): string {
|
||||
return `${PENDING_ATTACHMENT_THREAD_SEGMENT}-${NodeCrypto.randomUUID()}`;
|
||||
export function attachmentFileExtension(fileName: string): string {
|
||||
const extension = NodePath.extname(fileName).toLowerCase();
|
||||
// ".part" is reserved for in-flight uploads; a stored "archive.part" would
|
||||
// look stale to sweepStalePendingAttachments and get deleted.
|
||||
if (extension === ".part" || !/^\.[a-z0-9]{1,10}$/.test(extension)) {
|
||||
return ".bin";
|
||||
}
|
||||
return extension;
|
||||
}
|
||||
|
||||
function attachmentIdExtensionSuffix(extension: string | undefined): string {
|
||||
if (!extension) {
|
||||
return "";
|
||||
}
|
||||
const normalized = extension.replace(/^\./, "").toLowerCase();
|
||||
return new RegExp(`^${ATTACHMENT_ID_FILE_EXTENSION_PATTERN}$`).test(normalized)
|
||||
? `-${normalized}`
|
||||
: "-bin";
|
||||
}
|
||||
|
||||
export function createPendingAttachmentId(extension?: string): string {
|
||||
return `${PENDING_ATTACHMENT_THREAD_SEGMENT}-${NodeCrypto.randomUUID()}${attachmentIdExtensionSuffix(extension)}`;
|
||||
}
|
||||
|
||||
export function parseAttachmentUuid(attachmentId: string): string | null {
|
||||
@@ -51,12 +72,20 @@ export function parseAttachmentUuid(attachmentId: string): string | null {
|
||||
return normalizedId.match(ATTACHMENT_ID_PATTERN)?.[2]?.toLowerCase() ?? null;
|
||||
}
|
||||
|
||||
export function createAttachmentId(threadId: string): string | null {
|
||||
export function parseAttachmentFileExtension(attachmentId: string): string | null {
|
||||
const normalizedId = normalizeAttachmentRelativePath(attachmentId);
|
||||
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
|
||||
return null;
|
||||
}
|
||||
return normalizedId.match(ATTACHMENT_ID_PATTERN)?.[3]?.toLowerCase() ?? null;
|
||||
}
|
||||
|
||||
export function createAttachmentId(threadId: string, extension?: string): string | null {
|
||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||
if (!threadSegment) {
|
||||
return null;
|
||||
}
|
||||
return `${threadSegment}-${NodeCrypto.randomUUID()}`;
|
||||
return `${threadSegment}-${NodeCrypto.randomUUID()}${attachmentIdExtensionSuffix(extension)}`;
|
||||
}
|
||||
|
||||
export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
|
||||
@@ -71,7 +100,8 @@ export function parseThreadSegmentFromAttachmentId(attachmentId: string): string
|
||||
return match[1]?.toLowerCase() ?? null;
|
||||
}
|
||||
|
||||
export function attachmentRelativePath(attachment: ChatAttachment): string {
|
||||
/** Null for attachment types this build does not know; callers skip those. */
|
||||
export function attachmentRelativePath(attachment: ChatAttachment): string | null {
|
||||
switch (attachment.type) {
|
||||
case "image": {
|
||||
const extension = inferImageExtension({
|
||||
@@ -80,6 +110,10 @@ export function attachmentRelativePath(attachment: ChatAttachment): string {
|
||||
});
|
||||
return `${attachment.id}${extension}`;
|
||||
}
|
||||
case "file":
|
||||
return `${attachment.id}${attachmentFileExtension(attachment.name)}`;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,9 +121,13 @@ export function resolveAttachmentPath(input: {
|
||||
readonly attachmentsDir: string;
|
||||
readonly attachment: ChatAttachment;
|
||||
}): string | null {
|
||||
const relativePath = attachmentRelativePath(input.attachment);
|
||||
if (!relativePath) {
|
||||
return null;
|
||||
}
|
||||
return resolveAttachmentRelativePath({
|
||||
attachmentsDir: input.attachmentsDir,
|
||||
relativePath: attachmentRelativePath(input.attachment),
|
||||
relativePath,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -101,6 +139,14 @@ export function resolveAttachmentPathById(input: {
|
||||
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
|
||||
return null;
|
||||
}
|
||||
const fileExtension = parseAttachmentFileExtension(normalizedId);
|
||||
if (fileExtension) {
|
||||
const filePath = resolveAttachmentRelativePath({
|
||||
attachmentsDir: input.attachmentsDir,
|
||||
relativePath: `${normalizedId}.${fileExtension.toLowerCase()}`,
|
||||
});
|
||||
return filePath && NodeFS.existsSync(filePath) ? filePath : null;
|
||||
}
|
||||
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
|
||||
const maybePath = resolveAttachmentRelativePath({
|
||||
attachmentsDir: input.attachmentsDir,
|
||||
@@ -147,7 +193,8 @@ export function planAttachmentClaim(input: {
|
||||
if (!currentPath) {
|
||||
return { ok: false, reason: "attachment not found (removed or expired)" };
|
||||
}
|
||||
const finalId = createAttachmentId(input.threadId);
|
||||
const fileExtension = parseAttachmentFileExtension(input.attachmentId) ?? undefined;
|
||||
const finalId = createAttachmentId(input.threadId, fileExtension);
|
||||
if (!finalId) {
|
||||
return { ok: false, reason: "failed to create attachment id" };
|
||||
}
|
||||
|
||||
@@ -91,6 +91,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
|
||||
expect(second.capabilities.repositoryIdentity).toBe(true);
|
||||
expect(second.capabilities.connectionProbe).toBe(true);
|
||||
expect(second.capabilities.attachmentUploads).toBe(true);
|
||||
expect(second.capabilities.fileAttachments).toEqual({ maxUploadBytes: 50 * 1024 * 1024 });
|
||||
expect(second.capabilities.pullRequests).toBe(true);
|
||||
expect(second.capabilities.threadTitleRegeneration).toBe(true);
|
||||
expect(second.capabilities.threadPullRequestLinking).toBe(true);
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
|
||||
import {
|
||||
EnvironmentId,
|
||||
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
|
||||
type ExecutionEnvironmentDescriptor,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
@@ -147,6 +151,7 @@ export const make = Effect.gen(function* () {
|
||||
repositoryIdentity: true,
|
||||
connectionProbe: true,
|
||||
attachmentUploads: true,
|
||||
fileAttachments: { maxUploadBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES },
|
||||
pullRequests: true,
|
||||
threadSettlement: true,
|
||||
threadSnooze: true,
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { describe } from "vite-plus/test";
|
||||
|
||||
import { assetResponseHeaders, isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts";
|
||||
import {
|
||||
assetResponseHeaders,
|
||||
downloadContentDisposition,
|
||||
isLoopbackHostname,
|
||||
resolveDevRedirectUrl,
|
||||
} from "./http.ts";
|
||||
|
||||
describe("http dev routing", () => {
|
||||
it("treats localhost and loopback addresses as local", () => {
|
||||
@@ -55,4 +60,79 @@ describe("assetResponseHeaders", () => {
|
||||
"text/html; charset=utf-8",
|
||||
);
|
||||
});
|
||||
|
||||
it("downloads uploaded documents without executing their content", () => {
|
||||
expect(assetResponseHeaders("/attachments/upload.html", { download: true })).toMatchObject({
|
||||
"Content-Disposition": "attachment",
|
||||
"Content-Security-Policy": "default-src 'none'; sandbox",
|
||||
"Content-Type": "application/octet-stream",
|
||||
});
|
||||
});
|
||||
|
||||
it("serves the real filename and mime type when the claims carry them", () => {
|
||||
expect(
|
||||
assetResponseHeaders("/attachments/thread-1-abc-pdf.pdf", {
|
||||
download: true,
|
||||
fileName: "Q3 report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
}),
|
||||
).toMatchObject({
|
||||
"Content-Disposition": 'attachment; filename="Q3 report.pdf"',
|
||||
"Content-Security-Policy": "default-src 'none'; sandbox",
|
||||
"Content-Type": "application/pdf",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps renderable mime types as octet-stream downloads", () => {
|
||||
for (const mimeType of [
|
||||
"text/html",
|
||||
"text/xml",
|
||||
"image/svg+xml",
|
||||
"application/xhtml+xml",
|
||||
"application/rss+xml",
|
||||
"APPLICATION/XML",
|
||||
"IMAGE/SVG+XML",
|
||||
"application/xml-dtd",
|
||||
"application/xml-external-parsed-entity",
|
||||
"not a mime",
|
||||
]) {
|
||||
expect(
|
||||
assetResponseHeaders("/attachments/upload.bin", { download: true, mimeType }),
|
||||
).toHaveProperty("Content-Type", "application/octet-stream");
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves official Office Open XML mime types", () => {
|
||||
for (const mimeType of [
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||
]) {
|
||||
expect(
|
||||
assetResponseHeaders("/attachments/upload.bin", { download: true, mimeType }),
|
||||
).toHaveProperty("Content-Type", mimeType);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("downloadContentDisposition", () => {
|
||||
it("quotes plain names and strips quotes and control characters", () => {
|
||||
expect(downloadContentDisposition("report.pdf")).toBe('attachment; filename="report.pdf"');
|
||||
expect(downloadContentDisposition('we"ird\n.pdf')).toBe('attachment; filename="we_ird_.pdf"');
|
||||
});
|
||||
|
||||
it("adds an RFC 5987 encoded name for non-ASCII filenames", () => {
|
||||
expect(downloadContentDisposition("répört.pdf")).toBe(
|
||||
`attachment; filename="r_p_rt.pdf"; filename*=UTF-8''r%C3%A9p%C3%B6rt.pdf`,
|
||||
);
|
||||
expect(downloadContentDisposition("résumé'(*).pdf")).toBe(
|
||||
`attachment; filename="r_sum_'(*).pdf"; filename*=UTF-8''r%C3%A9sum%C3%A9%27%28%2A%29.pdf`,
|
||||
);
|
||||
});
|
||||
|
||||
it("does not throw on unpaired surrogates in the filename", () => {
|
||||
expect(downloadContentDisposition("bad\ud800name.pdf")).toBe(
|
||||
`attachment; filename="bad_name.pdf"; filename*=UTF-8''bad%EF%BF%BDname.pdf`,
|
||||
);
|
||||
});
|
||||
});
|
||||
+61
-15
@@ -12,6 +12,7 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { cast } from "effect/Function";
|
||||
import {
|
||||
HttpBody,
|
||||
@@ -50,15 +51,57 @@ const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
|
||||
const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
|
||||
const SVG_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
|
||||
|
||||
export function assetResponseHeaders(filePath: string): Record<string, string> {
|
||||
// Types a browser may render as a document if a proxy strips the disposition
|
||||
// header. Downloads of these fall back to octet-stream.
|
||||
const DOWNLOAD_MIME_TYPE_PATTERN = /^[\w!#$&^.+-]+\/[\w!#$&^.+-]+$/;
|
||||
const isSafeDownloadMimeType = (mimeType: string): boolean =>
|
||||
DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) &&
|
||||
!/(?:^text\/html$|\/xml(?:$|-)|\+xml$)/i.test(mimeType.trim().toLowerCase());
|
||||
|
||||
/** RFC 6266 disposition with an ASCII fallback name plus a UTF-8 `filename*`. */
|
||||
export function downloadContentDisposition(fileName?: string): string {
|
||||
if (fileName === undefined) {
|
||||
return "attachment";
|
||||
}
|
||||
// toWellFormed: encodeURIComponent throws URIError on unpaired surrogates.
|
||||
// eslint-disable-next-line no-control-regex -- Header filenames must strip ASCII controls.
|
||||
const sanitized = fileName.toWellFormed().replace(/[\u0000-\u001f"\\]/g, "_");
|
||||
const asciiFallback = sanitized.replace(/[^\u0020-\u007e]/g, "_");
|
||||
const needsExtended = asciiFallback !== sanitized;
|
||||
const extendedName = encodeURIComponent(sanitized).replace(
|
||||
/['()*]/g,
|
||||
(character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
|
||||
);
|
||||
return `attachment; filename="${asciiFallback}"${
|
||||
needsExtended ? `; filename*=UTF-8''${extendedName}` : ""
|
||||
}`;
|
||||
}
|
||||
|
||||
export function assetResponseHeaders(
|
||||
filePath: string,
|
||||
options?: {
|
||||
readonly download?: boolean;
|
||||
readonly fileName?: string;
|
||||
readonly mimeType?: string;
|
||||
},
|
||||
): Record<string, string> {
|
||||
const lowerPath = filePath.toLowerCase();
|
||||
return {
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
...(lowerPath.endsWith(".html") || lowerPath.endsWith(".htm")
|
||||
? { "Content-Type": "text/html; charset=utf-8" }
|
||||
: {}),
|
||||
...(lowerPath.endsWith(".svg")
|
||||
...(options?.download
|
||||
? {
|
||||
"Content-Disposition": downloadContentDisposition(options.fileName),
|
||||
"Content-Security-Policy": "default-src 'none'; sandbox",
|
||||
"Content-Type":
|
||||
options.mimeType !== undefined && isSafeDownloadMimeType(options.mimeType)
|
||||
? options.mimeType
|
||||
: "application/octet-stream",
|
||||
}
|
||||
: lowerPath.endsWith(".html") || lowerPath.endsWith(".htm")
|
||||
? { "Content-Type": "text/html; charset=utf-8" }
|
||||
: {}),
|
||||
...(!options?.download && lowerPath.endsWith(".svg")
|
||||
? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY }
|
||||
: {}),
|
||||
};
|
||||
@@ -228,7 +271,16 @@ export const assetRouteLayer = HttpRouter.add(
|
||||
}
|
||||
return yield* HttpServerResponse.file(asset.path, {
|
||||
status: 200,
|
||||
headers: assetResponseHeaders(asset.path),
|
||||
headers: assetResponseHeaders(
|
||||
asset.path,
|
||||
asset.download
|
||||
? {
|
||||
download: true,
|
||||
...(asset.fileName !== undefined ? { fileName: asset.fileName } : {}),
|
||||
...(asset.mimeType !== undefined ? { mimeType: asset.mimeType } : {}),
|
||||
}
|
||||
: undefined,
|
||||
),
|
||||
}).pipe(
|
||||
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
||||
);
|
||||
@@ -265,15 +317,9 @@ export const attachmentUploadRouteLayer = HttpRouter.add(
|
||||
});
|
||||
}
|
||||
|
||||
const body = yield* request.arrayBuffer.pipe(
|
||||
Effect.provideService(HttpServerRequest.MaxBodySize, FileSystem.Size(claims.sizeBytes)),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
if (body === null) {
|
||||
return HttpServerResponse.text("Failed to read the upload body.", { status: 400 });
|
||||
}
|
||||
|
||||
const stored = yield* storeAttachmentUpload(claims, new Uint8Array(body));
|
||||
// Keep the request stream in the route scope until the response is sent.
|
||||
const bodyPull = yield* Stream.toPull(request.stream);
|
||||
const stored = yield* storeAttachmentUpload(claims, Stream.fromPull(Effect.succeed(bodyPull)));
|
||||
return stored.ok
|
||||
? HttpServerResponse.empty({ status: 204 })
|
||||
: HttpServerResponse.text(stored.detail, { status: stored.status });
|
||||
|
||||
@@ -882,6 +882,7 @@ it.layer(
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const threadId = ThreadId.make("Thread Revert.Files");
|
||||
const keepAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000001";
|
||||
const keepFileAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000004-pdf";
|
||||
const removeAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000002";
|
||||
const otherThreadAttachmentId =
|
||||
"thread-revert-files-extra-00000000-0000-4000-8000-000000000003";
|
||||
@@ -983,6 +984,13 @@ it.layer(
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
{
|
||||
type: "file",
|
||||
id: keepFileAttachmentId,
|
||||
name: "keep.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
turnId: TurnId.make("turn-keep"),
|
||||
streaming: false,
|
||||
@@ -1045,9 +1053,11 @@ it.layer(
|
||||
});
|
||||
|
||||
const keepPath = path.join(attachmentsDir, `${keepAttachmentId}.png`);
|
||||
const keepFilePath = path.join(attachmentsDir, `${keepFileAttachmentId}.pdf`);
|
||||
const removePath = path.join(attachmentsDir, `${removeAttachmentId}.png`);
|
||||
yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(keepPath, "keep");
|
||||
yield* fileSystem.writeFileString(keepFilePath, "keep");
|
||||
yield* fileSystem.writeFileString(removePath, "remove");
|
||||
const otherThreadPath = path.join(attachmentsDir, `${otherThreadAttachmentId}.png`);
|
||||
yield* fileSystem.writeFileString(otherThreadPath, "other");
|
||||
@@ -1072,6 +1082,7 @@ it.layer(
|
||||
});
|
||||
|
||||
assert.isTrue(yield* exists(keepPath));
|
||||
assert.isTrue(yield* exists(keepFilePath));
|
||||
assert.isFalse(yield* exists(removePath));
|
||||
assert.isTrue(yield* exists(otherThreadPath));
|
||||
}),
|
||||
@@ -1091,6 +1102,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const threadId = ThreadId.make("Thread Delete.Files");
|
||||
const attachmentId = "thread-delete-files-00000000-0000-4000-8000-000000000001";
|
||||
const fileAttachmentId = "thread-delete-files-00000000-0000-4000-8000-000000000003-pdf";
|
||||
const otherThreadAttachmentId =
|
||||
"thread-delete-files-extra-00000000-0000-4000-8000-000000000002";
|
||||
|
||||
@@ -1169,6 +1181,13 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
{
|
||||
type: "file",
|
||||
id: fileAttachmentId,
|
||||
name: "delete.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 6,
|
||||
},
|
||||
],
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
@@ -1178,14 +1197,17 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
|
||||
});
|
||||
|
||||
const threadAttachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||
const threadFileAttachmentPath = path.join(attachmentsDir, `${fileAttachmentId}.pdf`);
|
||||
const otherThreadAttachmentPath = path.join(
|
||||
attachmentsDir,
|
||||
`${otherThreadAttachmentId}.png`,
|
||||
);
|
||||
yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(threadAttachmentPath, "delete");
|
||||
yield* fileSystem.writeFileString(threadFileAttachmentPath, "delete");
|
||||
yield* fileSystem.writeFileString(otherThreadAttachmentPath, "other-thread");
|
||||
assert.isTrue(yield* exists(threadAttachmentPath));
|
||||
assert.isTrue(yield* exists(threadFileAttachmentPath));
|
||||
assert.isTrue(yield* exists(otherThreadAttachmentPath));
|
||||
|
||||
yield* appendAndProject({
|
||||
@@ -1205,6 +1227,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
|
||||
});
|
||||
|
||||
assert.isFalse(yield* exists(threadAttachmentPath));
|
||||
assert.isFalse(yield* exists(threadFileAttachmentPath));
|
||||
assert.isTrue(yield* exists(otherThreadAttachmentPath));
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -361,14 +361,14 @@ 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;
|
||||
}
|
||||
relativePaths.add(attachmentRelativePath(attachment));
|
||||
const relativePath = attachmentRelativePath(attachment);
|
||||
if (relativePath) {
|
||||
relativePaths.add(relativePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
return relativePaths;
|
||||
|
||||
@@ -93,9 +93,12 @@ describe("normalizeDispatchCommand attachments", () => {
|
||||
expect(attachmentId.startsWith("thread-1-")).toBe(true);
|
||||
expect(attachmentId).not.toBe(`thread-1-${attachmentUuid}`);
|
||||
expect(NodeFS.existsSync(pendingPath)).toBe(true);
|
||||
expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${attachmentId}.png`))).toBe(
|
||||
true,
|
||||
);
|
||||
const claimedPngPath = NodePath.join(config.attachmentsDir, `${attachmentId}.png`);
|
||||
expect(NodeFS.existsSync(claimedPngPath)).toBe(true);
|
||||
// A copy, not a hard link: editing the delivered file must not mutate
|
||||
// the retryable pending upload.
|
||||
expect(NodeFS.statSync(claimedPngPath).ino).not.toBe(NodeFS.statSync(pendingPath).ino);
|
||||
expect(NodeFS.readFileSync(claimedPngPath)).toEqual(bytes);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
@@ -124,6 +127,45 @@ describe("normalizeDispatchCommand attachments", () => {
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("claims uploaded documents without changing their original extension", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const pendingId = `pending-${attachmentUuid}-pdf`;
|
||||
const pendingPath = NodePath.join(config.attachmentsDir, `${pendingId}.pdf`);
|
||||
NodeFS.writeFileSync(pendingPath, Buffer.from("report"));
|
||||
|
||||
const imageCommand = turnStartCommand({ attachments: [] });
|
||||
if (imageCommand.type !== "thread.turn.start") {
|
||||
throw new Error("Expected a thread.turn.start command.");
|
||||
}
|
||||
const normalized = yield* normalizeDispatchCommand({
|
||||
...imageCommand,
|
||||
message: {
|
||||
...imageCommand.message,
|
||||
attachments: [
|
||||
{
|
||||
type: "file",
|
||||
id: pendingId,
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 6,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
if (normalized.type !== "thread.turn.start") {
|
||||
throw new Error("Expected a thread.turn.start command.");
|
||||
}
|
||||
|
||||
const attachment = normalized.message.attachments[0]!;
|
||||
expect(attachment.type).toBe("file");
|
||||
expect(attachment.id).toMatch(/^thread-1-.*-pdf$/);
|
||||
const claimedPath = NodePath.join(config.attachmentsDir, `${attachment.id}.pdf`);
|
||||
expect(NodeFS.readFileSync(claimedPath)).toEqual(Buffer.from("report"));
|
||||
expect(NodeFS.statSync(claimedPath).ino).not.toBe(NodeFS.statSync(pendingPath).ino);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("retries a failed bootstrap with a fresh thread id", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
@@ -312,7 +354,7 @@ describe("normalizeDispatchCommand attachments", () => {
|
||||
})),
|
||||
},
|
||||
}).pipe(Effect.flip);
|
||||
expect(mismatchedType.message).toContain("image type");
|
||||
expect(mismatchedType.message).toContain("attachment type");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
});
|
||||
@@ -176,12 +176,14 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
|
||||
});
|
||||
if (expectedPath !== claim.finalPath) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: `Attachment '${attachment.name}' cannot be sent: image type does not match the upload.`,
|
||||
message: `Attachment '${attachment.name}' cannot be sent: attachment type does not match the upload.`,
|
||||
});
|
||||
}
|
||||
|
||||
// Keep the pending copy until the turn succeeds. A failed thread
|
||||
// bootstrap can then retry with a fresh thread id.
|
||||
// bootstrap can then retry with a fresh thread id. A copy, not a
|
||||
// hard link: an agent editing the delivered file in place must not
|
||||
// mutate the retry source.
|
||||
yield* fileSystem.copyFile(claim.currentPath, claim.finalPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -808,7 +808,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 4,
|
||||
};
|
||||
const attachmentPath = NodePath.join(attachmentsDir, attachmentRelativePath(attachment));
|
||||
const attachmentPath = NodePath.join(attachmentsDir, attachmentRelativePath(attachment)!);
|
||||
NodeFS.mkdirSync(NodePath.dirname(attachmentPath), { recursive: true });
|
||||
NodeFS.writeFileSync(attachmentPath, Uint8Array.from([1, 2, 3, 4]));
|
||||
|
||||
|
||||
@@ -1306,6 +1306,8 @@ const buildUserMessageEffect = Effect.fn("buildUserMessageEffect")(function* (
|
||||
}
|
||||
|
||||
for (const attachment of input.attachments ?? []) {
|
||||
// Claude ingests images only. Generic files reach the agent through the
|
||||
// path line ProviderService puts in the prompt.
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1822,8 +1822,11 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
});
|
||||
|
||||
const sendTurn: CodexAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {
|
||||
// Codex ingests images only. Anything else would be base64-encoded as an
|
||||
// image and rejected or misread; generic files reach the agent through the
|
||||
// path line ProviderService puts in the prompt.
|
||||
const codexAttachments = yield* Effect.forEach(
|
||||
input.attachments ?? [],
|
||||
(input.attachments ?? []).filter((attachment) => attachment.type === "image"),
|
||||
(attachment) => resolveAttachment(input, attachment),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
@@ -972,6 +972,11 @@ export function makeCursorAdapter(
|
||||
}
|
||||
if (input.attachments && input.attachments.length > 0) {
|
||||
for (const attachment of input.attachments) {
|
||||
// Cursor ingests images only. Generic files reach the agent
|
||||
// through the path line ProviderService puts in the prompt.
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
|
||||
@@ -1504,8 +1504,10 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
);
|
||||
|
||||
const text = input.input?.trim();
|
||||
// Grok ingests images only. Generic files reach the agent
|
||||
// through the path line ProviderService puts in the prompt.
|
||||
const imagePromptParts = yield* Effect.forEach(
|
||||
input.attachments ?? [],
|
||||
(input.attachments ?? []).filter((attachment) => attachment.type === "image"),
|
||||
(attachment) =>
|
||||
Effect.gen(function* () {
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
|
||||
@@ -1456,6 +1456,8 @@ export function makeOpenCodeAdapter(
|
||||
}
|
||||
|
||||
const text = input.input?.trim();
|
||||
// OpenCode ingests images, text, and PDFs natively; formats its model
|
||||
// paths reject ride only as the prompt's file path line.
|
||||
const fileParts = toOpenCodeFileParts({
|
||||
attachments: input.attachments,
|
||||
resolveAttachmentPath: (attachment) =>
|
||||
|
||||
@@ -14,7 +14,6 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
EventId,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
@@ -1145,6 +1144,33 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
const imageOnlyInput = routing.codex.sendTurn.mock.calls[0]?.[0] as ProviderSendTurnInput;
|
||||
assert.equal(imageOnlyInput.input?.startsWith('[Attached image "screenshot.png"'), true);
|
||||
|
||||
const fileAttachment = {
|
||||
type: "file" as const,
|
||||
id: "thread-attach-12345678-1234-1234-1234-123456789abc-pdf",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 456,
|
||||
};
|
||||
|
||||
routing.codex.sendTurn.mockClear();
|
||||
yield* provider.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "summarize the report",
|
||||
attachments: [attachment, fileAttachment],
|
||||
});
|
||||
const mixedInput = routing.codex.sendTurn.mock.calls[0]?.[0] as ProviderSendTurnInput;
|
||||
assert.include(mixedInput.input ?? "", '[Attached file "report.pdf" is saved at: ');
|
||||
assert.include(mixedInput.input ?? "", `${fileAttachment.id}.pdf]`);
|
||||
// Every attachment reaches the adapter; each adapter decides what its
|
||||
// provider ingests natively.
|
||||
assert.deepEqual(mixedInput.attachments, [attachment, fileAttachment]);
|
||||
|
||||
routing.codex.sendTurn.mockClear();
|
||||
yield* provider.sendTurn({ threadId: session.threadId, attachments: [fileAttachment] });
|
||||
const fileOnlyInput = routing.codex.sendTurn.mock.calls[0]?.[0] as ProviderSendTurnInput;
|
||||
assert.include(fileOnlyInput.input ?? "", '[Attached file "report.pdf" is saved at: ');
|
||||
assert.deepEqual(fileOnlyInput.attachments, [fileAttachment]);
|
||||
|
||||
yield* provider.stopSession({ threadId: session.threadId });
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -729,13 +729,12 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
);
|
||||
}
|
||||
|
||||
// Adapters inline attachment pixels into the model prompt, but the model's
|
||||
// tools cannot dereference pixels. Appending the on-disk path is what lets
|
||||
// a turn like "include this screenshot in the PR" copy the actual file.
|
||||
// This runs after schema decode, so the appended lines are exempt from the
|
||||
// PROVIDER_SEND_TURN_MAX_INPUT_CHARS check; attachment count is capped, so
|
||||
// the overhead is bounded. Unresolvable ids are skipped here and surface
|
||||
// as adapter errors when the file is read for inlining.
|
||||
// Every attachment gets an on-disk path in the prompt so the model's tools
|
||||
// can dereference the actual file. All attachments then go to the adapter,
|
||||
// and each adapter decides what its provider ingests natively: OpenCode
|
||||
// sends generic files as file parts, the others send images only and rely
|
||||
// on the path line for everything else. Unresolvable ids are skipped here
|
||||
// and surface as adapter errors when the file is read.
|
||||
const attachmentPathLines = attachments.flatMap((attachment) => {
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
@@ -757,13 +756,12 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
...(inputTextWithAttachmentPaths !== undefined
|
||||
? { input: inputTextWithAttachmentPaths }
|
||||
: {}),
|
||||
attachments,
|
||||
};
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"provider.operation": "send-turn",
|
||||
"provider.thread_id": input.threadId,
|
||||
"provider.interaction_mode": input.interactionMode,
|
||||
"provider.attachment_count": input.attachments.length,
|
||||
"provider.attachment_count": attachments.length,
|
||||
});
|
||||
let metricProvider = "unknown";
|
||||
let metricModel = input.modelSelection?.model;
|
||||
@@ -807,7 +805,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
// often, since every toggle restarts the session. Recording it per turn
|
||||
// gives a usage-weighted view and lets it cross with interactionMode.
|
||||
runtimeMode: routed.runtimeMode,
|
||||
attachmentCount: input.attachments.length,
|
||||
attachmentCount: attachments.length,
|
||||
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
|
||||
});
|
||||
return turn;
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
parseAgentListCliOutput,
|
||||
parseModelsCliOutput,
|
||||
parseSkillsCliOutput,
|
||||
toOpenCodeFileParts,
|
||||
} from "./opencodeRuntime.ts";
|
||||
|
||||
describe("parseModelsCliOutput", () => {
|
||||
@@ -283,3 +284,38 @@ describe("parseSkillsCliOutput", () => {
|
||||
NodeAssert.deepEqual(parseSkillsCliOutput("not json"), []);
|
||||
});
|
||||
});
|
||||
|
||||
describe("toOpenCodeFileParts", () => {
|
||||
const attachment = (mimeType: string, sizeBytes = 12) => ({
|
||||
type: "file" as const,
|
||||
id: "thread-1-00000000-0000-4000-8000-000000000001-bin",
|
||||
name: "attachment",
|
||||
mimeType,
|
||||
sizeBytes,
|
||||
});
|
||||
|
||||
it("sends supported images, text, and PDFs natively and skips what models reject", () => {
|
||||
const parts = toOpenCodeFileParts({
|
||||
attachments: [
|
||||
attachment("application/pdf"),
|
||||
attachment("text/markdown"),
|
||||
attachment("image/png"),
|
||||
// A ZIP file part makes OpenCode's Anthropic path throw before the
|
||||
// turn starts; it must ride only as the prompt's file path line.
|
||||
attachment("application/zip"),
|
||||
attachment("application/octet-stream"),
|
||||
// Image formats the model APIs reject stay on the fallback path too.
|
||||
attachment("image/bmp"),
|
||||
attachment("image/svg+xml"),
|
||||
// Over the direct-attachment limit: path fallback even for a PDF.
|
||||
attachment("application/pdf", 21 * 1024 * 1024),
|
||||
],
|
||||
resolveAttachmentPath: () => "/tmp/attachment",
|
||||
});
|
||||
|
||||
NodeAssert.deepEqual(
|
||||
parts.map((part) => part.mime),
|
||||
["application/pdf", "text/markdown", "image/png"],
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -345,6 +345,31 @@ export function openCodeQuestionId(
|
||||
return header.length > 0 ? `question-${index}-${header}` : `question-${index}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attachments OpenCode can hand to a model as a native file part. Anything
|
||||
* else (ZIP, binaries, image formats like BMP/AVIF/SVG that model APIs
|
||||
* reject, or files over the direct-attachment size limit) would make the turn
|
||||
* fail before it starts, so those ride only as the file path ProviderService
|
||||
* puts in the prompt.
|
||||
*/
|
||||
const OPENCODE_NATIVE_IMAGE_MIMES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
|
||||
export const OPENCODE_NATIVE_FILE_PART_MAX_BYTES = 20 * 1024 * 1024;
|
||||
|
||||
export function isOpenCodeNativeFilePart(input: {
|
||||
readonly mimeType: string;
|
||||
readonly sizeBytes: number;
|
||||
}): boolean {
|
||||
if (input.sizeBytes > OPENCODE_NATIVE_FILE_PART_MAX_BYTES) {
|
||||
return false;
|
||||
}
|
||||
const normalized = input.mimeType.trim().toLowerCase();
|
||||
return (
|
||||
OPENCODE_NATIVE_IMAGE_MIMES.has(normalized) ||
|
||||
normalized.startsWith("text/") ||
|
||||
normalized === "application/pdf"
|
||||
);
|
||||
}
|
||||
|
||||
export function toOpenCodeFileParts(input: {
|
||||
readonly attachments: ReadonlyArray<ChatAttachment> | undefined;
|
||||
readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null;
|
||||
@@ -352,6 +377,9 @@ export function toOpenCodeFileParts(input: {
|
||||
const parts: Array<FilePartInput> = [];
|
||||
|
||||
for (const attachment of input.attachments ?? []) {
|
||||
if (!isOpenCodeNativeFilePart(attachment)) {
|
||||
continue;
|
||||
}
|
||||
const attachmentPath = input.resolveAttachmentPath(attachment);
|
||||
if (!attachmentPath) {
|
||||
continue;
|
||||
|
||||
@@ -4579,6 +4579,113 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
});
|
||||
assert.equal(streamedResponse.status, 204);
|
||||
yield* client[WS_METHODS.attachmentsDelete]({ attachmentId: streamed.attachmentId });
|
||||
|
||||
const uploadedFile = yield* client[WS_METHODS.attachmentsCreateUploadUrl]({
|
||||
type: "file",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 6,
|
||||
});
|
||||
const fileResponse = yield* HttpClient.post(uploadedFile.relativeUrl, {
|
||||
body: HttpBody.stream(
|
||||
Stream.make(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])),
|
||||
"application/pdf",
|
||||
),
|
||||
});
|
||||
assert.equal(fileResponse.status, 204);
|
||||
const uploadedFilePath = path.join(
|
||||
config.attachmentsDir,
|
||||
`${uploadedFile.attachmentId}.pdf`,
|
||||
);
|
||||
assert.isTrue(yield* fileSystem.exists(uploadedFilePath));
|
||||
|
||||
// A mint that carries the attachment's display name and mime
|
||||
// serves a real download filename and Content-Type.
|
||||
const download = yield* client[WS_METHODS.assetsCreateUrl]({
|
||||
resource: {
|
||||
_tag: "attachment",
|
||||
attachmentId: uploadedFile.attachmentId,
|
||||
fileName: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
},
|
||||
});
|
||||
const downloadResponse = yield* HttpClient.get(download.relativeUrl);
|
||||
assert.equal(downloadResponse.status, 200);
|
||||
assert.equal(
|
||||
downloadResponse.headers["content-disposition"],
|
||||
'attachment; filename="report.pdf"',
|
||||
);
|
||||
assert.equal(downloadResponse.headers["content-type"], "application/pdf");
|
||||
|
||||
// Old clients mint without name or mime and still get a download.
|
||||
const bareDownload = yield* client[WS_METHODS.assetsCreateUrl]({
|
||||
resource: { _tag: "attachment", attachmentId: uploadedFile.attachmentId },
|
||||
});
|
||||
const bareResponse = yield* HttpClient.get(bareDownload.relativeUrl);
|
||||
assert.equal(bareResponse.status, 200);
|
||||
assert.equal(bareResponse.headers["content-disposition"], "attachment");
|
||||
assert.equal(bareResponse.headers["content-type"], "application/octet-stream");
|
||||
|
||||
yield* client[WS_METHODS.attachmentsDelete]({
|
||||
attachmentId: uploadedFile.attachmentId,
|
||||
});
|
||||
assert.isFalse(yield* fileSystem.exists(uploadedFilePath));
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("rejects an over-limit chunked upload through the route without hanging", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* buildAppUnderTest();
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
|
||||
yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
Effect.gen(function* () {
|
||||
const issued = yield* client[WS_METHODS.attachmentsCreateUploadUrl]({
|
||||
type: "file",
|
||||
name: "big.bin",
|
||||
mimeType: "application/octet-stream",
|
||||
sizeBytes: 6,
|
||||
});
|
||||
const NodeHttp = yield* Effect.promise(() => import("node:http"));
|
||||
const uploadUrl = new URL(issued.relativeUrl, yield* getHttpServerUrl());
|
||||
const status = yield* Effect.callback<number, Error>((resume) => {
|
||||
let completed = false;
|
||||
const complete = (result: Effect.Effect<number, Error>) => {
|
||||
if (completed) return;
|
||||
completed = true;
|
||||
resume(result);
|
||||
};
|
||||
const request = NodeHttp.request(
|
||||
uploadUrl,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/octet-stream",
|
||||
"transfer-encoding": "chunked",
|
||||
},
|
||||
},
|
||||
(response) => {
|
||||
request.end();
|
||||
response.resume();
|
||||
response.once("end", () => complete(Effect.succeed(response.statusCode ?? 0)));
|
||||
response.once("error", (error) => complete(Effect.fail(error)));
|
||||
},
|
||||
);
|
||||
request.once("error", (error) => complete(Effect.fail(error)));
|
||||
request.flushHeaders();
|
||||
request.write(new Uint8Array(4), () => {
|
||||
request.write(new Uint8Array(4));
|
||||
});
|
||||
|
||||
return Effect.sync(() => request.destroy());
|
||||
});
|
||||
assert.equal(status, 400);
|
||||
assert.deepEqual(yield* fileSystem.readDirectory(config.attachmentsDir), []);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -18,6 +18,7 @@ const runtimeMock = {
|
||||
state: {
|
||||
startCalls: [] as string[],
|
||||
promptUrls: [] as string[],
|
||||
promptParts: [] as ReadonlyArray<unknown>[],
|
||||
authHeaders: [] as Array<string | null>,
|
||||
closeCalls: [] as string[],
|
||||
sessionCreateError: undefined as unknown,
|
||||
@@ -30,6 +31,7 @@ const runtimeMock = {
|
||||
reset() {
|
||||
this.state.startCalls.length = 0;
|
||||
this.state.promptUrls.length = 0;
|
||||
this.state.promptParts.length = 0;
|
||||
this.state.authHeaders.length = 0;
|
||||
this.state.closeCalls.length = 0;
|
||||
this.state.sessionCreateError = undefined;
|
||||
@@ -73,8 +75,9 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntimeShape = {
|
||||
}
|
||||
return runtimeMock.state.sessionResult ?? { data: { id: `${baseUrl}/session` } };
|
||||
},
|
||||
prompt: async () => {
|
||||
prompt: async (input: { readonly parts: ReadonlyArray<unknown> }) => {
|
||||
runtimeMock.state.promptUrls.push(baseUrl);
|
||||
runtimeMock.state.promptParts.push(input.parts);
|
||||
runtimeMock.state.authHeaders.push(
|
||||
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
|
||||
);
|
||||
@@ -187,6 +190,45 @@ const advanceIdleClock = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
|
||||
it.effect("excludes generic files from thread title generation", () =>
|
||||
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.promptResult = {
|
||||
data: {
|
||||
parts: [{ type: "text", text: '{"title":"Review uploaded report"}' }],
|
||||
},
|
||||
};
|
||||
|
||||
yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Review these attachments.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "thread-image-attachment",
|
||||
name: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 3,
|
||||
},
|
||||
{
|
||||
type: "file",
|
||||
id: "thread-report-attachment-pdf",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 42,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(runtimeMock.state.promptParts[0]).toEqual([
|
||||
expect.objectContaining({ type: "text" }),
|
||||
expect.objectContaining({ type: "file", filename: "screenshot.png" }),
|
||||
]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reuses a warm server across back-to-back requests and closes it after idling", () =>
|
||||
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -375,7 +375,7 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
}
|
||||
|
||||
const fileParts = OpenCodeRuntime.toOpenCodeFileParts({
|
||||
attachments: input.attachments,
|
||||
attachments: input.attachments?.filter((attachment) => attachment.type === "image"),
|
||||
resolveAttachmentPath: (attachment) =>
|
||||
resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }),
|
||||
});
|
||||
|
||||
@@ -11,7 +11,13 @@ import {
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { type ChatMessage, type SessionPhase, type Thread, type ThreadShell } from "../types";
|
||||
import {
|
||||
type ChatMessage,
|
||||
isImageAttachment,
|
||||
type SessionPhase,
|
||||
type Thread,
|
||||
type ThreadShell,
|
||||
} from "../types";
|
||||
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { appAtomRegistry } from "../rpc/atomRegistry";
|
||||
@@ -277,7 +283,7 @@ export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
|
||||
return;
|
||||
}
|
||||
for (const attachment of message.attachments) {
|
||||
if (attachment.type !== "image") {
|
||||
if (!isImageAttachment(attachment)) {
|
||||
continue;
|
||||
}
|
||||
revokeBlobPreviewUrl(attachment.previewUrl);
|
||||
@@ -290,7 +296,7 @@ export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[
|
||||
}
|
||||
const previewUrls: string[] = [];
|
||||
for (const attachment of message.attachments) {
|
||||
if (attachment.type !== "image") continue;
|
||||
if (!isImageAttachment(attachment)) continue;
|
||||
if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
|
||||
previewUrls.push(attachment.previewUrl);
|
||||
}
|
||||
|
||||
@@ -126,6 +126,7 @@ import {
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_TERMINALS_PER_GROUP,
|
||||
type ChatMessage,
|
||||
isImageAttachment,
|
||||
type SessionPhase,
|
||||
type Thread,
|
||||
type TurnDiffSummary,
|
||||
@@ -2560,7 +2561,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
|
||||
const serverPreviewUrls = serverMessage.attachments.flatMap((attachment) =>
|
||||
attachment.type === "image" && attachment.previewUrl ? [attachment.previewUrl] : [],
|
||||
isImageAttachment(attachment) && attachment.previewUrl ? [attachment.previewUrl] : [],
|
||||
);
|
||||
if (
|
||||
serverPreviewUrls.length === 0 ||
|
||||
@@ -2643,7 +2644,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
let changed = false;
|
||||
let imageIndex = 0;
|
||||
const attachments = message.attachments.map((attachment) => {
|
||||
if (attachment.type !== "image") {
|
||||
if (!isImageAttachment(attachment)) {
|
||||
return attachment;
|
||||
}
|
||||
const handoffPreviewUrl = handoffPreviewUrls[imageIndex];
|
||||
|
||||
@@ -38,7 +38,7 @@ import {
|
||||
workEntrySignalsSevereFailure,
|
||||
workLogEntryIsToolLike,
|
||||
} from "../../session-logic";
|
||||
import { type TurnDiffSummary } from "../../types";
|
||||
import { type ChatImageAttachment, isImageAttachment, type TurnDiffSummary } from "../../types";
|
||||
import {
|
||||
getRenderablePatch,
|
||||
resolveDiffThemeName,
|
||||
@@ -925,8 +925,6 @@ function TimelineMinimap({
|
||||
// TimelineRowContent — the actual row component
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
|
||||
type TimelineMessage = Extract<TimelineEntry, { kind: "message" }>["message"];
|
||||
type TimelineWorkEntry = Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"][number];
|
||||
type TimelineRow = MessagesTimelineRow;
|
||||
|
||||
@@ -988,7 +986,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
|
||||
|
||||
function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
|
||||
const ctx = use(TimelineRowCtx);
|
||||
const userImages = row.message.attachments ?? [];
|
||||
const userImages = (row.message.attachments ?? []).filter(isImageAttachment);
|
||||
const displayedUserMessage = deriveDisplayedUserMessageState(row.message.text);
|
||||
const terminalContexts = displayedUserMessage.contexts;
|
||||
const previewAnnotations: ParsedPreviewAnnotation[] = [];
|
||||
@@ -1013,7 +1011,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
|
||||
<div className="relative max-w-[80%] rounded-2xl bg-message p-3 text-message-foreground">
|
||||
{regularImages.length > 0 && (
|
||||
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
|
||||
{regularImages.map((image: NonNullable<TimelineMessage["attachments"]>[number]) => (
|
||||
{regularImages.map((image: ChatImageAttachment) => (
|
||||
<div
|
||||
key={image.id}
|
||||
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
|
||||
@@ -1719,7 +1717,7 @@ const UserMessageElementContextChip = memo(function UserMessageElementContextChi
|
||||
|
||||
function UserMessagePreviewAnnotationCard(props: {
|
||||
annotation: ParsedPreviewAnnotation;
|
||||
image: NonNullable<TimelineMessage["attachments"]>[number] | null;
|
||||
image: ChatImageAttachment | null;
|
||||
}) {
|
||||
const ctx = use(TimelineRowCtx);
|
||||
return (
|
||||
|
||||
+12
-1
@@ -1,4 +1,5 @@
|
||||
import type {
|
||||
ChatAttachment as ContractChatAttachment,
|
||||
ChatImageAttachment as ContractChatImageAttachment,
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationCheckpointSummary,
|
||||
@@ -35,7 +36,17 @@ export interface ChatImageAttachment extends ContractChatImageAttachment {
|
||||
readonly previewUrl?: string;
|
||||
}
|
||||
|
||||
export type ChatAttachment = ChatImageAttachment;
|
||||
// Non-image members pass through with the contract shape. The web UI renders
|
||||
// them once it grows file support; until then they only need to typecheck.
|
||||
export type ChatAttachment =
|
||||
| ChatImageAttachment
|
||||
| Exclude<ContractChatAttachment, ContractChatImageAttachment>;
|
||||
|
||||
// The union has an open member (`type: string`), so a literal comparison does
|
||||
// not narrow. Use this guard wherever image-only fields are read.
|
||||
export function isImageAttachment(attachment: ChatAttachment): attachment is ChatImageAttachment {
|
||||
return attachment.type === "image";
|
||||
}
|
||||
|
||||
export interface ChatMessage extends Omit<OrchestrationMessage, "attachments"> {
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
|
||||
@@ -51,6 +51,34 @@ probes, respect the `enableProviderUpdateChecks` setting, and never fail a provi
|
||||
Codex and Claude drivers apply the classification to every snapshot with `applyModelManifest`;
|
||||
driver kinds absent from the manifest have no legacy concept.
|
||||
|
||||
## Attachment access
|
||||
|
||||
The server stores uploaded attachments in its attachment directory, outside the project workspace.
|
||||
`ProviderService` adds the absolute path of each attachment to the turn text, then passes every
|
||||
attachment to the provider adapter. Each adapter decides what its provider ingests natively:
|
||||
|
||||
- Codex, Claude, Cursor, and Grok send images as native image inputs and skip generic files. For
|
||||
these providers, generic files reach the agent only as file paths in the turn text.
|
||||
- OpenCode sends PNG/JPEG/GIF/WebP images, text files, and PDFs up to 20 MB as native file parts
|
||||
with their real mime type. Everything else (ZIP and other binaries, image formats model APIs
|
||||
reject, oversized files) falls back to the file path in the turn text, like the other providers.
|
||||
|
||||
Claude receives the attachment directory as an allowed additional directory. Codex keeps its
|
||||
configured sandbox policy, so access depends on that policy and the selected runtime mode. OpenCode
|
||||
allows all paths in full-access mode and requests approval for directories outside the workspace in
|
||||
restricted modes. Cursor and Grok use their own provider permission rules.
|
||||
|
||||
The server does not copy attachments into a project or bypass provider approval rules. If an agent
|
||||
cannot read an attachment, the user must approve the access or select a runtime mode that permits it.
|
||||
|
||||
Updated attachment schemas tolerate unknown attachment members, but old image-only clients still
|
||||
cannot decode messages that contain file attachments. Client file-picking rollouts must account for
|
||||
this limit.
|
||||
|
||||
Do not run an old image-only server against state that contains file attachments. Replay decodes
|
||||
each persisted event before projection. A file-bearing event can make `ProjectionPipeline` bootstrap
|
||||
and `OrchestrationEngine` startup fail for the entire environment, not only the affected thread.
|
||||
|
||||
## How provider work is requested
|
||||
|
||||
Clients never call a provider directly. They dispatch orchestration commands over the RPC method
|
||||
|
||||
@@ -2,7 +2,10 @@ import * as Schema from "effect/Schema";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { AttachmentCreateUploadUrlInput } from "./assets.ts";
|
||||
import { PROVIDER_SEND_TURN_MAX_IMAGE_BYTES } from "./orchestration.ts";
|
||||
import {
|
||||
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
} from "./orchestration.ts";
|
||||
|
||||
const isUploadInput = Schema.is(AttachmentCreateUploadUrlInput);
|
||||
|
||||
@@ -21,10 +24,37 @@ describe("AttachmentCreateUploadUrlInput", () => {
|
||||
expect(isUploadInput({ ...uploadInput, mimeType: "image/svg+xml" })).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts generic files without treating them as provider images", () => {
|
||||
expect(
|
||||
isUploadInput({
|
||||
type: "file",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isUploadInput({
|
||||
type: "file",
|
||||
name: "diagram.svg",
|
||||
mimeType: "image/svg+xml",
|
||||
sizeBytes: 3,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects empty and oversized uploads", () => {
|
||||
expect(isUploadInput({ ...uploadInput, sizeBytes: 0 })).toBe(false);
|
||||
expect(
|
||||
isUploadInput({ ...uploadInput, sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1 }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isUploadInput({
|
||||
type: "file",
|
||||
name: "archive.zip",
|
||||
mimeType: "application/zip",
|
||||
sizeBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES + 1,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import { NonNegativeInt, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
import {
|
||||
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES,
|
||||
ProjectFaviconPath,
|
||||
@@ -16,6 +17,12 @@ export const AssetResource = Schema.Union([
|
||||
}),
|
||||
Schema.TaggedStruct("attachment", {
|
||||
attachmentId: TrimmedNonEmptyString.check(Schema.isMaxLength(256)),
|
||||
/** Display name and mime from the `ChatAttachment` the caller holds. The
|
||||
server bakes both into the signed URL so downloads carry the real
|
||||
filename and Content-Type. Absent on older clients, which fall back to
|
||||
an octet-stream download without a filename. */
|
||||
fileName: Schema.optionalKey(TrimmedNonEmptyString.check(Schema.isMaxLength(255))),
|
||||
mimeType: Schema.optionalKey(TrimmedNonEmptyString.check(Schema.isMaxLength(100))),
|
||||
}),
|
||||
Schema.TaggedStruct("project-favicon", {
|
||||
cwd: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
|
||||
@@ -42,7 +49,8 @@ export type AssetCreateUrlResult = typeof AssetCreateUrlResult.Type;
|
||||
|
||||
export const ATTACHMENT_UPLOAD_URL_TTL_MS = 10 * 60_000;
|
||||
|
||||
export const AttachmentCreateUploadUrlInput = Schema.Struct({
|
||||
const ImageAttachmentCreateUploadUrlInput = Schema.Struct({
|
||||
type: Schema.optionalKey(Schema.Literal("image")),
|
||||
name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
|
||||
mimeType: Schema.Literals(PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES),
|
||||
sizeBytes: NonNegativeInt.check(
|
||||
@@ -50,6 +58,21 @@ export const AttachmentCreateUploadUrlInput = Schema.Struct({
|
||||
Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES),
|
||||
),
|
||||
});
|
||||
|
||||
const FileAttachmentCreateUploadUrlInput = Schema.Struct({
|
||||
type: Schema.Literal("file"),
|
||||
name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
|
||||
mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100)),
|
||||
sizeBytes: NonNegativeInt.check(
|
||||
Schema.isGreaterThanOrEqualTo(1),
|
||||
Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_FILE_BYTES),
|
||||
),
|
||||
});
|
||||
|
||||
export const AttachmentCreateUploadUrlInput = Schema.Union([
|
||||
ImageAttachmentCreateUploadUrlInput,
|
||||
FileAttachmentCreateUploadUrlInput,
|
||||
]);
|
||||
export type AttachmentCreateUploadUrlInput = typeof AttachmentCreateUploadUrlInput.Type;
|
||||
|
||||
export const AttachmentCreateUploadUrlResult = Schema.Struct({
|
||||
|
||||
@@ -39,4 +39,16 @@ describe("ExecutionEnvironmentDescriptor", () => {
|
||||
}).capabilities.attachmentUploads,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves the server's generic attachment upload limit", () => {
|
||||
expect(
|
||||
decodeDescriptor({
|
||||
...descriptor,
|
||||
capabilities: {
|
||||
...descriptor.capabilities,
|
||||
fileAttachments: { maxUploadBytes: 50 * 1024 * 1024 },
|
||||
},
|
||||
}).capabilities.fileAttachments,
|
||||
).toEqual({ maxUploadBytes: 50 * 1024 * 1024 });
|
||||
});
|
||||
});
|
||||
@@ -50,6 +50,12 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
|
||||
connectionProbe: Schema.optionalKey(Schema.Boolean),
|
||||
/** Missing on older servers, which still accept inline image attachments. */
|
||||
attachmentUploads: Schema.optionalKey(Schema.Boolean),
|
||||
/** Missing on servers that only accept image attachments. */
|
||||
fileAttachments: Schema.optionalKey(
|
||||
Schema.Struct({
|
||||
maxUploadBytes: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
|
||||
}),
|
||||
),
|
||||
/** Server exposes the pull-request list, detail, activity, diff, and mutation APIs. Absent on
|
||||
servers from before the pull-request workspace shipped, so clients must not probe them. */
|
||||
pullRequests: Schema.optionalKey(Schema.Boolean),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
@@ -20,12 +21,15 @@ import {
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadShell,
|
||||
ProjectCreateCommand,
|
||||
OrchestrationMessage,
|
||||
ThreadMessageSentPayload,
|
||||
ThreadMetaUpdatedPayload,
|
||||
ThreadTurnStartCommand,
|
||||
ThreadCreatedPayload,
|
||||
ThreadTurnDiff,
|
||||
ThreadTurnStartRequestedPayload,
|
||||
isProviderSendTurnSupportedImageMimeType,
|
||||
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
|
||||
} from "./orchestration.ts";
|
||||
import { ProviderInstanceId } from "./providerInstance.ts";
|
||||
|
||||
@@ -37,6 +41,8 @@ const decodeProjectCreatedPayload = Schema.decodeUnknownEffect(ProjectCreatedPay
|
||||
const decodeProjectMetaUpdatedPayload = Schema.decodeUnknownEffect(ProjectMetaUpdatedPayload);
|
||||
const decodeThreadTurnStartCommand = Schema.decodeUnknownEffect(ThreadTurnStartCommand);
|
||||
const decodeClientOrchestrationCommand = Schema.decodeUnknownEffect(ClientOrchestrationCommand);
|
||||
const decodeOrchestrationMessage = Schema.decodeUnknownEffect(OrchestrationMessage);
|
||||
const decodeThreadMessageSentPayload = Schema.decodeUnknownEffect(ThreadMessageSentPayload);
|
||||
const decodeThreadTurnStartRequestedPayload = Schema.decodeUnknownEffect(
|
||||
ThreadTurnStartRequestedPayload,
|
||||
);
|
||||
@@ -243,7 +249,7 @@ it.effect("decodes thread.turn.start defaults for provider and runtime mode", ()
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("accepts both inline and uploaded image attachments from clients", () =>
|
||||
it.effect("accepts inline images, uploaded images, and uploaded files from clients", () =>
|
||||
Effect.gen(function* () {
|
||||
const command = yield* decodeClientOrchestrationCommand({
|
||||
type: "thread.turn.start",
|
||||
@@ -268,6 +274,13 @@ it.effect("accepts both inline and uploaded image attachments from clients", ()
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 3,
|
||||
},
|
||||
{
|
||||
type: "file",
|
||||
id: "pending-00000000-0000-4000-8000-000000000002-pdf",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 3,
|
||||
},
|
||||
],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
@@ -278,9 +291,85 @@ it.effect("accepts both inline and uploaded image attachments from clients", ()
|
||||
if (command.type !== "thread.turn.start") {
|
||||
assert.fail(`Expected thread.turn.start, received ${command.type}.`);
|
||||
}
|
||||
assert.strictEqual(command.message.attachments.length, 2);
|
||||
assert.strictEqual(command.message.attachments.length, 3);
|
||||
assert.strictEqual("dataUrl" in command.message.attachments[0]!, true);
|
||||
assert.strictEqual("id" in command.message.attachments[1]!, true);
|
||||
assert.strictEqual(command.message.attachments[2]!.type, "file");
|
||||
}),
|
||||
);
|
||||
|
||||
// Attachments ride on persisted events and thread streams with no client
|
||||
// version negotiation. A type this build does not know must decode instead of
|
||||
// failing the whole message.
|
||||
it.effect("tolerates attachment types from newer builds when decoding messages", () =>
|
||||
Effect.gen(function* () {
|
||||
const futureAttachment = {
|
||||
type: "somethingnew",
|
||||
id: "thread-1-00000000-0000-4000-8000-000000000003-glb",
|
||||
name: "scene.glb",
|
||||
mimeType: "model/gltf-binary",
|
||||
sizeBytes: 12,
|
||||
};
|
||||
|
||||
const message = yield* decodeOrchestrationMessage({
|
||||
id: "message-1",
|
||||
role: "user",
|
||||
text: "look at this",
|
||||
attachments: [futureAttachment],
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.strictEqual(message.attachments?.length, 1);
|
||||
assert.strictEqual(message.attachments?.[0]!.type, "somethingnew");
|
||||
|
||||
const payload = yield* decodeThreadMessageSentPayload({
|
||||
threadId: "thread-1",
|
||||
messageId: "message-1",
|
||||
role: "user",
|
||||
text: "look at this",
|
||||
attachments: [futureAttachment],
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.strictEqual(payload.attachments?.[0]!.type, "somethingnew");
|
||||
}),
|
||||
);
|
||||
|
||||
// The tolerant member must not catch malformed known attachments: a file over
|
||||
// the size cap or an image with a bad mime has to fail its own schema, not
|
||||
// slide through the open one with those constraints unchecked.
|
||||
it.effect("rejects malformed known attachment types instead of tolerating them", () =>
|
||||
Effect.gen(function* () {
|
||||
const base = {
|
||||
id: "thread-1-00000000-0000-4000-8000-000000000003-pdf",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
};
|
||||
const decode = (attachment: unknown) =>
|
||||
decodeOrchestrationMessage({
|
||||
id: "message-1",
|
||||
role: "user",
|
||||
text: "look at this",
|
||||
attachments: [attachment],
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const oversizedFile = yield* Effect.exit(
|
||||
decode({ ...base, type: "file", sizeBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES + 1 }),
|
||||
);
|
||||
assert.strictEqual(Exit.isFailure(oversizedFile), true);
|
||||
|
||||
const badMimeImage = yield* Effect.exit(
|
||||
decode({ ...base, type: "image", mimeType: "application/pdf", sizeBytes: 12 }),
|
||||
);
|
||||
assert.strictEqual(Exit.isFailure(badMimeImage), true);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -156,6 +156,7 @@ export type ProviderUserInputAnswers = typeof ProviderUserInputAnswers.Type;
|
||||
export const PROVIDER_SEND_TURN_MAX_INPUT_CHARS = 120_000;
|
||||
export const PROVIDER_SEND_TURN_MAX_ATTACHMENTS = 8;
|
||||
export const PROVIDER_SEND_TURN_MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
||||
export const PROVIDER_SEND_TURN_MAX_FILE_BYTES = 50 * 1024 * 1024;
|
||||
export const PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES = [
|
||||
"image/gif",
|
||||
"image/jpeg",
|
||||
@@ -191,6 +192,40 @@ export const ChatImageAttachment = Schema.Struct({
|
||||
});
|
||||
export type ChatImageAttachment = typeof ChatImageAttachment.Type;
|
||||
|
||||
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.isGreaterThanOrEqualTo(1),
|
||||
Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_FILE_BYTES),
|
||||
),
|
||||
});
|
||||
export type ChatFileAttachment = typeof ChatFileAttachment.Type;
|
||||
|
||||
/**
|
||||
* Catch-all for attachment types this build does not know. Attachments ride on
|
||||
* persisted events and thread streams, so a newer server or client must be able
|
||||
* to introduce a type without making older readers fail to decode the whole
|
||||
* message. Decoders keep the shared base fields; consumers skip these or render
|
||||
* them as unsupported. Mirrors how `OrchestrationThreadActivity` keeps `kind`
|
||||
* open. The known discriminators are excluded so a malformed image or file
|
||||
* attachment fails its own schema instead of sliding through here with its
|
||||
* size and mime constraints unchecked.
|
||||
*/
|
||||
export const ChatUnknownAttachment = Schema.Struct({
|
||||
type: TrimmedNonEmptyString.check(
|
||||
Schema.isMaxLength(50),
|
||||
Schema.isPattern(/^(?!(?:image|file)$)/),
|
||||
),
|
||||
id: ChatAttachmentId,
|
||||
name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
|
||||
mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100)),
|
||||
sizeBytes: NonNegativeInt,
|
||||
});
|
||||
export type ChatUnknownAttachment = typeof ChatUnknownAttachment.Type;
|
||||
|
||||
const UploadChatImageAttachment = Schema.Struct({
|
||||
type: Schema.Literal("image"),
|
||||
name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
|
||||
@@ -202,7 +237,11 @@ const UploadChatImageAttachment = Schema.Struct({
|
||||
});
|
||||
export type UploadChatImageAttachment = typeof UploadChatImageAttachment.Type;
|
||||
|
||||
export const ChatAttachment = Schema.Union([ChatImageAttachment]);
|
||||
export const ChatAttachment = Schema.Union([
|
||||
ChatImageAttachment,
|
||||
ChatFileAttachment,
|
||||
ChatUnknownAttachment,
|
||||
]);
|
||||
export type ChatAttachment = typeof ChatAttachment.Type;
|
||||
const UploadChatAttachment = Schema.Union([UploadChatImageAttachment]);
|
||||
export type UploadChatAttachment = typeof UploadChatAttachment.Type;
|
||||
|
||||
Reference in new issue
Block a user