feat: upload composer images on attach

Attachments used to ride the turn-start command as base64 data URLs:
send carried the bytes, the stash re-encoded them into localStorage,
and a 10MB image meant a 14M-char string in a single ws frame.

Images now upload the moment they are attached. A ws RPC mints a
pending-<uuid> id plus a signed, expiring upload URL (mirroring signed
asset GETs, so it works against any environment); the browser POSTs the
compressed bytes to it with progress and abort; the turn-start command
carries id references only. The Normalizer renames pending files to
their thread segment at send, resolving by uuid so retries after a
partial send are idempotent. Never-sent uploads are deleted on chip
removal and swept after 30 days.

Breaking: the dataUrl upload variant is deleted with no compatibility
path. RN mobile compiles with image attach gated off behind
IMAGE_ATTACH_ENABLED and tells the user an update is needed; drafts and
stash persist id references (v9/v3 storage, old payloads purged).

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 committed 2026-08-13 17:51:12 -07:00
1 parent 5304f3e9d4
commit f695b6f5bf
38 files changed
+2266 -1281

No files matched your search

@@ -0,0 +1,103 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ServerConfig from "../config.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { parseThreadSegmentFromAttachmentId } from "../attachmentStore.ts";
import {
deletePendingAttachment,
issueAttachmentUploadUrl,
storeAttachmentUpload,
validateAttachmentUploadToken,
ATTACHMENT_UPLOAD_ROUTE_PREFIX,
} from "./AttachmentUpload.ts";
const testLayer = ServerSecretStore.layer.pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-attachment-upload-" })),
Layer.provideMerge(NodeServices.layer),
);
const uploadInput = {
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 6,
} as const;
describe("AttachmentUpload", () => {
it.effect("mints a pending id and a token that validates round-trip", () =>
Effect.gen(function* () {
const issued = yield* issueAttachmentUploadUrl(uploadInput);
expect(parseThreadSegmentFromAttachmentId(issued.attachmentId)).toBe("pending");
expect(issued.relativeUrl.startsWith(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`)).toBe(true);
const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
const claims = yield* validateAttachmentUploadToken(token);
expect(claims).toMatchObject({
kind: "attachment-upload",
attachmentId: issued.attachmentId,
mimeType: "image/png",
sizeBytes: 6,
});
}).pipe(Effect.provide(testLayer)),
);
it.effect("rejects a tampered token", () =>
Effect.gen(function* () {
const issued = yield* issueAttachmentUploadUrl(uploadInput);
const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
const [payload, signature] = token.split(".");
const tampered = `${payload}x.${signature}`;
expect(yield* validateAttachmentUploadToken(tampered)).toBeNull();
expect(yield* validateAttachmentUploadToken("garbage")).toBeNull();
}).pipe(Effect.provide(testLayer)),
);
it.effect("stores matching bytes and rejects a size mismatch", () =>
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 claims");
const short = yield* storeAttachmentUpload(claims, new Uint8Array([1, 2, 3]));
expect(short).toMatchObject({ ok: false, status: 400 });
const stored = yield* storeAttachmentUpload(claims, new Uint8Array(6));
expect(stored).toEqual({ ok: true });
const finalPath = NodePath.join(config.attachmentsDir, `${issued.attachmentId}.png`);
expect(NodeFS.existsSync(finalPath)).toBe(true);
// No .part residue after a successful store.
expect(NodeFS.existsSync(`${finalPath}.part`)).toBe(false);
}).pipe(Effect.provide(testLayer)),
);
it.effect("deletes pending uploads idempotently but never thread-scoped files", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
const uuid = "00000000-0000-4000-8000-0000000000dd";
const pendingPath = NodePath.join(config.attachmentsDir, `pending-${uuid}.png`);
NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
yield* deletePendingAttachment(`pending-${uuid}`);
expect(NodeFS.existsSync(pendingPath)).toBe(false);
// Second delete is a no-op, not an error.
yield* deletePendingAttachment(`pending-${uuid}`);
const scopedUuid = "00000000-0000-4000-8000-0000000000ee";
const scopedPath = NodePath.join(config.attachmentsDir, `thread-1-${scopedUuid}.png`);
NodeFS.writeFileSync(scopedPath, Buffer.from("pixels"));
// A delete aimed at a claimed attachment must not remove it.
yield* deletePendingAttachment(`pending-${scopedUuid}`);
yield* deletePendingAttachment(`thread-1-${scopedUuid}`);
expect(NodeFS.existsSync(scopedPath)).toBe(true);
}).pipe(Effect.provide(testLayer)),
);
});
+210
View File
@@ -0,0 +1,210 @@
import {
ATTACHMENT_UPLOAD_URL_TTL_MS,
type AttachmentCreateUploadUrlInput,
AttachmentUploadSigningKeyError,
} from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
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 {
createPendingAttachmentId,
findAttachmentPathByUuid,
parseAttachmentIdFromRelativePath,
parseAttachmentUuid,
parseThreadSegmentFromAttachmentId,
PENDING_ATTACHMENT_THREAD_SEGMENT,
} from "../attachmentStore.ts";
import { resolveAttachmentRelativePath } from "../attachmentPaths.ts";
import {
base64UrlDecodeUtf8,
base64UrlEncode,
signPayload,
timingSafeEqualBase64Url,
} from "../auth/utils.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerConfig from "../config.ts";
import { inferImageExtension } from "../imageMime.ts";
export const ATTACHMENT_UPLOAD_ROUTE_PREFIX = "/api/attachments/upload";
// Shares the asset-access secret: upload and asset claims are distinguished
// by their schema `kind`, so a token minted for one can never validate as
// the other, and one key covers both signing uses.
const SIGNING_SECRET_NAME = "asset-access-signing-key";
const UploadClaimsSchema = Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("attachment-upload"),
attachmentId: Schema.String,
mimeType: Schema.String,
/** Exact byte count the client committed to at mint time. */
sizeBytes: Schema.Number,
expiresAt: Schema.Number,
});
export type AttachmentUploadClaims = typeof UploadClaimsSchema.Type;
const UploadClaimsJson = Schema.fromJsonString(UploadClaimsSchema);
const decodeUploadClaims = Schema.decodeUnknownOption(UploadClaimsJson);
const encodeUploadClaims = Schema.encodeSync(UploadClaimsJson);
const loadSigningSecret = Effect.gen(function* () {
const secretStore = yield* ServerSecretStore.ServerSecretStore;
return yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
});
/**
* Mints the `pending-<uuid>` id and a signed, expiring upload URL for it.
* Called over the authenticated ws; the returned URL itself carries
* authorization (mirroring signed asset GET URLs), which is what lets the
* browser POST bytes to any environment without extra credential plumbing.
*/
export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(function* (
input: AttachmentCreateUploadUrlInput,
) {
const secret = yield* loadSigningSecret.pipe(
Effect.mapError((cause) => new AttachmentUploadSigningKeyError({ cause })),
);
const attachmentId = createPendingAttachmentId();
const expiresAt = (yield* Clock.currentTimeMillis) + ATTACHMENT_UPLOAD_URL_TTL_MS;
const encodedPayload = base64UrlEncode(
encodeUploadClaims({
version: 1,
kind: "attachment-upload",
attachmentId,
mimeType: input.mimeType.toLowerCase(),
sizeBytes: input.sizeBytes,
expiresAt,
}),
);
const token = `${encodedPayload}.${signPayload(encodedPayload, secret)}`;
return {
attachmentId,
relativeUrl: `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/${token}`,
expiresAt,
};
});
/** Verifies signature and expiry; null means "treat as not found". */
export const validateAttachmentUploadToken = Effect.fn("AttachmentUpload.validateToken")(function* (
token: string,
) {
const [encodedPayload, signature] = token.split(".");
if (!encodedPayload || !signature) return null;
const secret = yield* loadSigningSecret.pipe(
Effect.tapError((cause) =>
Effect.logError("Failed to load the attachment upload signing key.", { cause }),
),
Effect.orElseSucceed(() => null),
);
if (!secret) return null;
if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, secret))) return null;
let claims: AttachmentUploadClaims | null;
try {
claims = Option.getOrNull(decodeUploadClaims(base64UrlDecodeUtf8(encodedPayload)));
} catch {
claims = null;
}
if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
return claims;
});
export type StoreUploadResult =
| { readonly ok: true }
| { readonly ok: false; readonly status: number; readonly detail: string };
/**
* Persists validated upload bytes. Writes to `<id>.<ext>.part` first and
* renames on success, so a crashed or aborted upload can never leave a file
* that looks like a complete attachment. Re-running with the same token
* overwrites atomically, which makes client retries safe.
*/
export const storeAttachmentUpload = Effect.fn("AttachmentUpload.store")(function* (
claims: AttachmentUploadClaims,
bytes: Uint8Array,
) {
if (bytes.byteLength !== claims.sizeBytes) {
return {
ok: false,
status: 400,
detail: `Body was ${bytes.byteLength} bytes, expected ${claims.sizeBytes}.`,
} satisfies StoreUploadResult;
}
const config = yield* ServerConfig.ServerConfig;
const extension = inferImageExtension({ mimeType: claims.mimeType });
const relativePath = `${claims.attachmentId}${extension}`;
const finalPath = resolveAttachmentRelativePath({
attachmentsDir: config.attachmentsDir,
relativePath,
});
const partPath = resolveAttachmentRelativePath({
attachmentsDir: config.attachmentsDir,
relativePath: `${relativePath}.part`,
});
if (!finalPath || !partPath) {
return { ok: false, status: 500, detail: "Failed to resolve attachment path." };
}
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const writeResult = yield* Effect.gen(function* () {
yield* fileSystem.makeDirectory(path.dirname(finalPath), { recursive: true });
yield* fileSystem.writeFile(partPath, bytes);
yield* fileSystem.rename(partPath, finalPath);
}).pipe(
Effect.as({ ok: true } satisfies StoreUploadResult),
Effect.tapError((cause) =>
Effect.logError("Failed to persist attachment upload.", {
attachmentId: claims.attachmentId,
cause,
}),
),
Effect.orElseSucceed(
() =>
({
ok: false,
status: 500,
detail: "Failed to persist upload.",
}) satisfies StoreUploadResult,
),
);
return writeResult;
});
/**
* Deletes a never-sent upload. Idempotent, and refuses (as a silent no-op)
* anything already claimed by a thread: those files are owned by their
* message and only die with the thread.
*/
export const deletePendingAttachment = Effect.fn("AttachmentUpload.deletePending")(function* (
attachmentId: string,
) {
if (parseThreadSegmentFromAttachmentId(attachmentId) !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
return;
}
const uuid = parseAttachmentUuid(attachmentId);
if (!uuid) return;
const config = yield* ServerConfig.ServerConfig;
const filePath = findAttachmentPathByUuid({ attachmentsDir: config.attachmentsDir, uuid });
if (!filePath) return;
const path = yield* Path.Path;
const foundId = parseAttachmentIdFromRelativePath(path.basename(filePath));
if (
!foundId ||
parseThreadSegmentFromAttachmentId(foundId) !== PENDING_ATTACHMENT_THREAD_SEGMENT
) {
return;
}
const fileSystem = yield* FileSystem.FileSystem;
yield* fileSystem.remove(filePath).pipe(
Effect.catch(
() =>
// Raced with the sweep or a duplicate delete; idempotent by design.
Effect.void,
),
);
});
+155 -4
View File
@@ -7,10 +7,19 @@ import { describe, expect, it } from "vite-plus/test";
import {
createAttachmentId,
createPendingAttachmentId,
parseThreadSegmentFromAttachmentId,
planAttachmentClaim,
resolveAttachmentPathById,
sweepStalePendingAttachments,
toSafeThreadAttachmentSegment,
PENDING_ATTACHMENT_MAX_AGE_MS,
} from "./attachmentStore.ts";
function makeTempAttachmentsDir(): string {
return NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"));
}
describe("attachmentStore", () => {
it("sanitizes thread ids when creating attachment ids", () => {
const attachmentId = createAttachmentId("thread.folder/unsafe space");
@@ -45,11 +54,9 @@ describe("attachmentStore", () => {
});
it("resolves attachment path by id using the extension that exists on disk", () => {
const attachmentsDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
);
const attachmentsDir = makeTempAttachmentsDir();
try {
const attachmentId = "thread-1-attachment";
const attachmentId = "thread-1-00000000-0000-4000-8000-00000000000a";
const pngPath = NodePath.join(attachmentsDir, `${attachmentId}.png`);
NodeFS.writeFileSync(pngPath, Buffer.from("hello"));
@@ -63,6 +70,150 @@ describe("attachmentStore", () => {
}
});
it("resolves a pending id to the renamed thread-scoped file after claim", () => {
const attachmentsDir = makeTempAttachmentsDir();
try {
const uuid = "00000000-0000-4000-8000-00000000000b";
const scopedPath = NodePath.join(attachmentsDir, `thread-9-${uuid}.png`);
NodeFS.writeFileSync(scopedPath, Buffer.from("pixels"));
// Old signed asset URLs carry the pending id; they must keep resolving.
const resolved = resolveAttachmentPathById({
attachmentsDir,
attachmentId: `pending-${uuid}`,
});
expect(resolved).toBe(scopedPath);
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
it("reserves the pending segment for uploads", () => {
expect(toSafeThreadAttachmentSegment("pending")).toBe("pending_thread");
const pendingId = createPendingAttachmentId();
expect(parseThreadSegmentFromAttachmentId(pendingId)).toBe("pending");
});
describe("planAttachmentClaim", () => {
const uuid = "00000000-0000-4000-8000-00000000000c";
it("plans a rename for a pending attachment", () => {
const attachmentsDir = makeTempAttachmentsDir();
try {
const pendingPath = NodePath.join(attachmentsDir, `pending-${uuid}.webp`);
NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
const claimPlan = planAttachmentClaim({
attachmentsDir,
threadId: "Thread.Foo",
attachmentId: `pending-${uuid}`,
});
expect(claimPlan).toEqual({
ok: true,
finalId: `thread-foo-${uuid}`,
currentPath: pendingPath,
finalPath: NodePath.join(attachmentsDir, `thread-foo-${uuid}.webp`),
alreadyScoped: false,
});
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
it("is idempotent when a retry references an already-renamed file", () => {
const attachmentsDir = makeTempAttachmentsDir();
try {
const scopedPath = NodePath.join(attachmentsDir, `thread-foo-${uuid}.webp`);
NodeFS.writeFileSync(scopedPath, Buffer.from("pixels"));
const claimPlan = planAttachmentClaim({
attachmentsDir,
threadId: "Thread.Foo",
attachmentId: `pending-${uuid}`,
});
expect(claimPlan).toMatchObject({ ok: true, alreadyScoped: true });
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
it("refuses an attachment claimed by another thread", () => {
const attachmentsDir = makeTempAttachmentsDir();
try {
NodeFS.writeFileSync(
NodePath.join(attachmentsDir, `other-thread-${uuid}.png`),
Buffer.from("pixels"),
);
const claimPlan = planAttachmentClaim({
attachmentsDir,
threadId: "Thread.Foo",
attachmentId: `pending-${uuid}`,
});
expect(claimPlan).toMatchObject({ ok: false });
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
it("reports a missing attachment", () => {
const attachmentsDir = makeTempAttachmentsDir();
try {
const claimPlan = planAttachmentClaim({
attachmentsDir,
threadId: "Thread.Foo",
attachmentId: `pending-${uuid}`,
});
expect(claimPlan).toMatchObject({ ok: false });
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
});
describe("sweepStalePendingAttachments", () => {
it("deletes stale pending and partial files, keeps fresh and scoped ones", () => {
const attachmentsDir = makeTempAttachmentsDir();
try {
const stalePending = NodePath.join(
attachmentsDir,
"pending-00000000-0000-4000-8000-000000000001.png",
);
const freshPending = NodePath.join(
attachmentsDir,
"pending-00000000-0000-4000-8000-000000000002.png",
);
const scoped = NodePath.join(
attachmentsDir,
"thread-1-00000000-0000-4000-8000-000000000003.png",
);
const stalePart = NodePath.join(
attachmentsDir,
"pending-00000000-0000-4000-8000-000000000004.png.part",
);
for (const filePath of [stalePending, freshPending, scoped, stalePart]) {
NodeFS.writeFileSync(filePath, Buffer.from("x"));
}
const staleMs = Date.now() - PENDING_ATTACHMENT_MAX_AGE_MS - 60_000;
NodeFS.utimesSync(stalePending, staleMs / 1000, staleMs / 1000);
NodeFS.utimesSync(scoped, staleMs / 1000, staleMs / 1000);
NodeFS.utimesSync(stalePart, staleMs / 1000, staleMs / 1000);
const swept = sweepStalePendingAttachments({
attachmentsDir,
nowMs: Date.now(),
});
expect(swept.deleted).toBe(2);
expect(NodeFS.existsSync(stalePending)).toBe(false);
expect(NodeFS.existsSync(stalePart)).toBe(false);
expect(NodeFS.existsSync(freshPending)).toBe(true);
expect(NodeFS.existsSync(scoped)).toBe(true);
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
});
it("returns null when no attachment file exists for the id", () => {
const attachmentsDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
+175 -10
View File
@@ -1,6 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeCrypto from "node:crypto";
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import type { ChatAttachment } from "@t3tools/contracts";
@@ -8,9 +9,8 @@ import {
normalizeAttachmentRelativePath,
resolveAttachmentRelativePath,
} from "./attachmentPaths.ts";
import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
import { inferImageExtension } from "./imageMime.ts";
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}";
@@ -19,6 +19,13 @@ const ATTACHMENT_ID_PATTERN = new RegExp(
"i",
);
/**
* Segment used for attachments uploaded before their thread exists
* (upload-on-attach). Files named `pending-<uuid>.<ext>` are re-scoped to the
* thread at turn start and swept when stale.
*/
export const PENDING_ATTACHMENT_THREAD_SEGMENT = "pending";
export function toSafeThreadAttachmentSegment(threadId: string): string | null {
const segment = threadId
.trim()
@@ -31,9 +38,65 @@ export function toSafeThreadAttachmentSegment(threadId: string): string | null {
if (segment.length === 0) {
return null;
}
// `pending` is reserved for not-yet-sent uploads; a thread that slugged to
// it would have its attachments swept as orphans.
if (segment === PENDING_ATTACHMENT_THREAD_SEGMENT) {
return `${PENDING_ATTACHMENT_THREAD_SEGMENT}_thread`;
}
return segment;
}
export function createPendingAttachmentId(): string {
return `${PENDING_ATTACHMENT_THREAD_SEGMENT}-${NodeCrypto.randomUUID()}`;
}
/** Extracts the trailing uuid from a `<segment>-<uuid>` attachment id. */
export function parseAttachmentUuid(attachmentId: string): string | null {
const normalizedId = normalizeAttachmentRelativePath(attachmentId);
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
return null;
}
const match = normalizedId.match(ATTACHMENT_ID_PATTERN);
return match?.[2]?.toLowerCase() ?? null;
}
/**
* Finds the on-disk file for an attachment uuid regardless of its current
* segment (`pending-` before send, thread-scoped after). The uuid is the
* stable identity: turn-start renames the file's segment but never the uuid,
* which is what keeps send retries and signed asset URLs working across the
* rename.
*/
export function findAttachmentPathByUuid(input: {
readonly attachmentsDir: string;
readonly uuid: string;
}): string | null {
const uuid = input.uuid.toLowerCase();
if (!new RegExp(`^${ATTACHMENT_ID_UUID_PATTERN}$`, "i").test(uuid)) {
return null;
}
let entries: string[];
try {
entries = NodeFS.readdirSync(input.attachmentsDir);
} catch {
return null;
}
const suffixPattern = new RegExp(`-${uuid}\\.[a-z0-9]{1,8}$`, "i");
for (const entry of entries) {
if (!suffixPattern.test(entry)) {
continue;
}
const resolved = resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
relativePath: entry,
});
if (resolved && NodeFS.existsSync(resolved)) {
return resolved;
}
}
return null;
}
export function createAttachmentId(threadId: string): string | null {
const threadSegment = toSafeThreadAttachmentSegment(threadId);
if (!threadSegment) {
@@ -80,20 +143,122 @@ export function resolveAttachmentPathById(input: {
readonly attachmentsDir: string;
readonly attachmentId: string;
}): string | null {
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
// Resolution is by uuid, not by exact id: a signed asset URL minted for a
// `pending-` id must keep working after turn start renames the file to its
// thread segment (draft previews hold such URLs across a send).
const uuid = parseAttachmentUuid(input.attachmentId);
if (!uuid) {
return null;
}
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
const maybePath = resolveAttachmentRelativePath({
return findAttachmentPathByUuid({ attachmentsDir: input.attachmentsDir, uuid });
}
export type AttachmentClaimPlan =
| {
readonly ok: true;
readonly finalId: string;
readonly currentPath: string;
readonly finalPath: string;
/** True when a prior (possibly failed) send already renamed the file. */
readonly alreadyScoped: boolean;
}
| { readonly ok: false; readonly reason: string };
/**
* Plans the pending-to-thread re-scope for one referenced attachment at turn
* start. Pure path logic; the caller performs the rename. The uuid is matched
* against whatever segment the file currently has so retries after a partial
* send are idempotent, and a file already claimed by a different thread is
* refused rather than stolen.
*/
export function planAttachmentClaim(input: {
readonly attachmentsDir: string;
readonly threadId: string;
readonly attachmentId: string;
}): AttachmentClaimPlan {
const uuid = parseAttachmentUuid(input.attachmentId);
if (!uuid) {
return { ok: false, reason: "invalid attachment id" };
}
const threadSegment = toSafeThreadAttachmentSegment(input.threadId);
if (!threadSegment) {
return { ok: false, reason: "invalid thread id" };
}
const currentPath = findAttachmentPathByUuid({ attachmentsDir: input.attachmentsDir, uuid });
if (!currentPath) {
return { ok: false, reason: "attachment not found (removed or expired)" };
}
const fileName = NodePath.basename(currentPath);
const currentId = parseAttachmentIdFromRelativePath(fileName);
const currentSegment = currentId ? parseThreadSegmentFromAttachmentId(currentId) : null;
if (!currentSegment) {
return { ok: false, reason: "attachment file name is malformed" };
}
const extension = NodePath.extname(fileName);
const finalId = `${threadSegment}-${uuid}`;
if (currentSegment === threadSegment) {
return { ok: true, finalId, currentPath, finalPath: currentPath, alreadyScoped: true };
}
if (currentSegment !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
return { ok: false, reason: "attachment belongs to another thread" };
}
const finalPath = resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
relativePath: `${finalId}${extension}`,
});
if (!finalPath) {
return { ok: false, reason: "failed to resolve attachment path" };
}
return { ok: true, finalId, currentPath, finalPath, alreadyScoped: false };
}
export const PENDING_ATTACHMENT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
export const PARTIAL_UPLOAD_MAX_AGE_MS = 24 * 60 * 60 * 1000;
/**
* Deletes never-sent uploads (`pending-*`) past their retention window and
* half-written `*.part` files left by aborted uploads. Runs at server start;
* chip removal deletes eagerly, this is the backstop.
*/
export function sweepStalePendingAttachments(input: {
readonly attachmentsDir: string;
readonly nowMs: number;
}): { readonly deleted: number } {
let entries: string[];
try {
entries = NodeFS.readdirSync(input.attachmentsDir);
} catch {
return { deleted: 0 };
}
let deleted = 0;
for (const entry of entries) {
const isPartial = entry.endsWith(".part");
const maxAgeMs = isPartial ? PARTIAL_UPLOAD_MAX_AGE_MS : PENDING_ATTACHMENT_MAX_AGE_MS;
if (!isPartial) {
const id = parseAttachmentIdFromRelativePath(entry);
const segment = id ? parseThreadSegmentFromAttachmentId(id) : null;
if (segment !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
continue;
}
}
const resolved = resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
relativePath: `${normalizedId}${extension}`,
relativePath: entry,
});
if (maybePath && NodeFS.existsSync(maybePath)) {
return maybePath;
if (!resolved) {
continue;
}
try {
const stats = NodeFS.statSync(resolved);
if (input.nowMs - stats.mtimeMs > maxAgeMs) {
NodeFS.unlinkSync(resolved);
deleted += 1;
}
} catch {
// Raced with a concurrent delete or an unreadable entry; skip it.
}
}
return null;
return { deleted };
}
export function parseAttachmentIdFromRelativePath(relativePath: string): string | null {
+2
View File
@@ -83,6 +83,8 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope,
[WS_METHODS.filesystemBrowse]: AuthOrchestrationReadScope,
[WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope,
[WS_METHODS.attachmentsCreateUploadUrl]: AuthOrchestrationOperateScope,
[WS_METHODS.attachmentsDelete]: AuthOrchestrationOperateScope,
[WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,
[WS_METHODS.subscribeResourceTelemetry]: AuthOrchestrationReadScope,
[WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,
+15
View File
@@ -6,6 +6,7 @@
*
* @module ServerConfig
*/
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -14,6 +15,8 @@ import * as LogLevel from "effect/LogLevel";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { sweepStalePendingAttachments } from "./attachmentStore.ts";
export const DEFAULT_PORT = 3773;
export const RuntimeMode = Schema.Literals(["web", "desktop"]);
@@ -152,6 +155,18 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
],
{ concurrency: "unbounded" },
);
// Backstop GC for upload-on-attach: never-sent `pending-*` uploads and
// aborted `*.part` files. Eager deletes happen at chip removal; this covers
// crashed clients and abandoned drafts.
const nowMs = yield* Clock.currentTimeMillis;
const swept = sweepStalePendingAttachments({
attachmentsDir: derivedPaths.attachmentsDir,
nowMs,
});
if (swept.deleted > 0) {
yield* Effect.logInfo("Swept stale pending attachments.", { deleted: swept.deleted });
}
});
const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
+45
View File
@@ -28,6 +28,11 @@ import { OtlpTracer } from "effect/unstable/observability";
import * as ServerConfig from "./config.ts";
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
import {
ATTACHMENT_UPLOAD_ROUTE_PREFIX,
storeAttachmentUpload,
validateAttachmentUploadToken,
} from "./assets/AttachmentUpload.ts";
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
@@ -226,6 +231,46 @@ export const assetRouteLayer = HttpRouter.add(
}),
);
export const attachmentUploadRouteLayer = HttpRouter.add(
"POST",
`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/*`,
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const url = HttpServerRequest.toURL(request);
if (Option.isNone(url)) {
return HttpServerResponse.text("Bad Request", { status: 400 });
}
const token = url.value.pathname.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
if (token.length === 0) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
// Invalid, tampered, and expired tokens are indistinguishable from
// missing ones on purpose, matching the signed asset GET route.
const claims = yield* validateAttachmentUploadToken(token);
if (!claims) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
const contentLength = Number(request.headers["content-length"] ?? "");
if (!Number.isInteger(contentLength) || contentLength !== claims.sizeBytes) {
return HttpServerResponse.text("Content-Length must match the minted upload size.", {
status: 400,
});
}
const body = yield* request.arrayBuffer.pipe(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));
return stored.ok
? HttpServerResponse.empty({ status: 204 })
: HttpServerResponse.text(stored.detail, { status: stored.status });
}),
);
export const staticAndDevRouteLayer = HttpRouter.add(
"GET",
"*",
+9 -81
View File
@@ -1,92 +1,20 @@
import { describe, expect, it } from "vite-plus/test";
import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
import { inferImageExtension } from "./imageMime.ts";
describe("imageMime", () => {
it("parses base64 data URL with mime type", () => {
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8=",
});
it("maps known image mime types to extensions", () => {
expect(inferImageExtension({ mimeType: "image/png" })).toBe(".png");
expect(inferImageExtension({ mimeType: "image/jpeg" })).toBe(".jpg");
expect(inferImageExtension({ mimeType: "IMAGE/WEBP" })).toBe(".webp");
});
it("parses base64 data URL with mime parameters", () => {
expect(parseBase64DataUrl("data:image/png;charset=utf-8;base64,SGVsbG8=")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8=",
});
it("falls back to a safe file name extension", () => {
expect(inferImageExtension({ mimeType: "image/unknown", fileName: "shot.PNG" })).toBe(".png");
});
it("rejects non-base64 data URL", () => {
expect(parseBase64DataUrl("data:image/png;charset=utf-8,hello")).toBeNull();
});
it("rejects missing mime type", () => {
expect(parseBase64DataUrl("data:;base64,SGVsbG8=")).toBeNull();
});
it("parses base64 data URL with spaces in payload", () => {
expect(parseBase64DataUrl("data:image/png;base64,SGVs bG8=\n")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8=",
});
});
it("rejects payload with characters outside the base64 alphabet", () => {
expect(parseBase64DataUrl("data:image/png;base64,SGVs!bG8=")).toBeNull();
expect(parseBase64DataUrl("data:image/png;base64,SGVs,bG8=")).toBeNull();
});
it("rejects structurally malformed base64", () => {
// '=' before the trailing padding position
expect(parseBase64DataUrl("data:image/png;base64,AB=CD===")).toBeNull();
expect(parseBase64DataUrl("data:image/png;base64,SGV=bG8=")).toBeNull();
// more than two padding characters
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=====AAA")).toBeNull();
// length not a multiple of 4
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8")).toBeNull();
});
it("accepts base64 with one or two trailing padding characters", () => {
expect(parseBase64DataUrl("data:image/png;base64,SGVsbA==")).toEqual({
mimeType: "image/png",
base64: "SGVsbA==",
});
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8h")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8h",
});
});
it("rejects empty and whitespace-only payloads", () => {
expect(parseBase64DataUrl("data:image/png;base64,")).toBeNull();
expect(parseBase64DataUrl("data:image/png;base64, \r\n")).toBeNull();
});
it("parses a case-insensitive scheme and mime type", () => {
expect(parseBase64DataUrl("DATA:IMAGE/PNG;BASE64,SGVsbG8=")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8=",
});
});
it("parses a multi-megabyte payload from a deep call stack", () => {
// Regression: matching the payload with a regex borrowed the JS call
// stack, so a ~10 MB image parsed inside fiber execution threw
// "RangeError: Maximum call stack size exceeded".
const dataUrl = `data:image/png;base64,${"A".repeat(14_000_000)}`;
const atDepth = (depth: number): ReturnType<typeof parseBase64DataUrl> =>
depth === 0 ? parseBase64DataUrl(dataUrl) : atDepth(depth - 1);
const findMaxDepth = (depth: number): number => {
try {
return findMaxDepth(depth + 1);
} catch {
return depth;
}
};
const result = atDepth(Math.floor(findMaxDepth(0) * 0.85));
expect(result?.mimeType).toBe("image/png");
expect(result?.base64.length).toBe(14_000_000);
it("falls back to .bin when nothing safe matches", () => {
expect(inferImageExtension({ mimeType: "image/unknown", fileName: "shot.exe" })).toBe(".bin");
});
it("does not read inherited keys from mime extension map", () => {
-83
View File
@@ -29,89 +29,6 @@ export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
".webp",
]);
// Whether `code` is a character the base64 payload may contain, aside from
// the whitespace handled separately below.
function isBase64Char(code: number): boolean {
return (
(code >= 0x61 && code <= 0x7a) || // a-z
(code >= 0x41 && code <= 0x5a) || // A-Z
(code >= 0x30 && code <= 0x39) || // 0-9
code === 0x2b || // +
code === 0x2f || // /
code === 0x3d // =
);
}
function isBase64Whitespace(code: number): boolean {
return code === 0x0d || code === 0x0a || code === 0x20; // \r \n space
}
// Data URLs carry the full image payload, so this parser must never run a
// regex across the payload: V8's regex engine borrows the JS call stack, and
// matching a multi-megabyte string from a deep call stack (e.g. inside fiber
// execution) throws "Maximum call stack size exceeded".
export function parseBase64DataUrl(
dataUrl: string,
): { readonly mimeType: string; readonly base64: string } | null {
const trimmed = dataUrl.trim();
if (trimmed.slice(0, 5).toLowerCase() !== "data:") return null;
const commaIndex = trimmed.indexOf(",");
if (commaIndex === -1) return null;
const header = trimmed.slice(5, commaIndex);
if (header.length === 0) return null;
const headerParts: Array<string> = [];
for (const part of header.split(";")) {
const partTrimmed = part.trim();
if (partTrimmed.length > 0) {
headerParts.push(partTrimmed);
}
}
if (headerParts.length < 2) {
return null;
}
const trailingToken = headerParts.at(-1)?.toLowerCase();
if (trailingToken !== "base64") {
return null;
}
const mimeType = headerParts[0]?.toLowerCase();
if (!mimeType) return null;
const payload = trimmed.slice(commaIndex + 1);
const runs: Array<string> = [];
let runStart = -1;
for (let index = 0; index < payload.length; index += 1) {
const code = payload.charCodeAt(index);
if (isBase64Char(code)) {
if (runStart === -1) runStart = index;
continue;
}
if (!isBase64Whitespace(code)) return null;
if (runStart !== -1) {
runs.push(payload.slice(runStart, index));
runStart = -1;
}
}
if (runStart !== -1) {
runs.push(payload.slice(runStart));
}
const base64 = runs.length === 1 ? runs[0]! : runs.join("");
if (base64.length === 0 || base64.length % 4 !== 0) return null;
const firstPad = base64.indexOf("=");
if (firstPad !== -1) {
// '=' is only valid as one or two trailing padding characters; Node's
// decoder would otherwise silently truncate at the first '='.
if (base64.length - firstPad > 2) return null;
for (let index = firstPad; index < base64.length; index += 1) {
if (base64.charCodeAt(index) !== 0x3d) return null;
}
}
return { mimeType, base64 };
}
export function inferImageExtension(input: { mimeType: string; fileName?: string }): string {
const key = input.mimeType.toLowerCase();
const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key)
@@ -0,0 +1,138 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import {
type ClientOrchestrationCommand,
CommandId,
MessageId,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ServerConfig from "../config.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import { normalizeDispatchCommand } from "./Normalizer.ts";
const testLayer = Layer.mergeAll(
WorkspacePaths.layer,
ServerConfig.layerTest(process.cwd(), { prefix: "t3-normalizer-attachments-" }),
).pipe(Layer.provideMerge(NodeServices.layer));
const UUID = "00000000-0000-4000-8000-0000000000aa";
function turnStartCommand(attachment: {
readonly id: string;
readonly sizeBytes: number;
}): ClientOrchestrationCommand {
return {
type: "thread.turn.start",
commandId: CommandId.make("command-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: MessageId.make("message-1"),
role: "user",
text: "look at this",
attachments: [
{
type: "image",
id: attachment.id,
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: attachment.sizeBytes,
},
],
},
runtimeMode: "full-access",
interactionMode: "default",
createdAt: "2026-08-01T00:00:00.000Z",
};
}
describe("normalizeDispatchCommand attachments", () => {
it.effect("claims a pending upload: renames the file and rewrites the id", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const bytes = Buffer.from("pixels");
const pendingPath = NodePath.join(config.attachmentsDir, `pending-${UUID}.png`);
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
NodeFS.writeFileSync(pendingPath, bytes);
const normalized = yield* normalizeDispatchCommand(
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: bytes.byteLength }),
);
if (normalized.type !== "thread.turn.start") {
throw new Error("Expected a thread.turn.start command");
}
expect(normalized.message.attachments).toHaveLength(1);
expect(normalized.message.attachments[0]?.id).toBe(`thread-1-${UUID}`);
expect(NodeFS.existsSync(pendingPath)).toBe(false);
expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `thread-1-${UUID}.png`))).toBe(
true,
);
}).pipe(Effect.provide(testLayer)),
);
it.effect("is idempotent when a retry references an already-claimed file", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const bytes = Buffer.from("pixels");
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `thread-1-${UUID}.png`), bytes);
// The retry still carries the original pending id.
const normalized = yield* normalizeDispatchCommand(
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: bytes.byteLength }),
);
if (normalized.type !== "thread.turn.start") {
throw new Error("Expected a thread.turn.start command");
}
expect(normalized.message.attachments[0]?.id).toBe(`thread-1-${UUID}`);
}).pipe(Effect.provide(testLayer)),
);
it.effect("fails when the referenced upload does not exist", () =>
Effect.gen(function* () {
const error = yield* normalizeDispatchCommand(
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: 6 }),
).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationDispatchCommandError");
expect(error.message).toContain("not found");
}).pipe(Effect.provide(testLayer)),
);
it.effect("fails when the stored size does not match the reference", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
NodeFS.writeFileSync(
NodePath.join(config.attachmentsDir, `pending-${UUID}.png`),
Buffer.from("pixels"),
);
const error = yield* normalizeDispatchCommand(
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: 999 }),
).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationDispatchCommandError");
expect(error.message).toContain("size");
}).pipe(Effect.provide(testLayer)),
);
it.effect("refuses an attachment already claimed by another thread", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const bytes = Buffer.from("pixels");
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `other-thread-${UUID}.png`), bytes);
const error = yield* normalizeDispatchCommand(
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: bytes.byteLength }),
).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationDispatchCommandError");
expect(error.message).toContain("another thread");
}).pipe(Effect.provide(testLayer)),
);
});
+33 -49
View File
@@ -1,18 +1,15 @@
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import {
type ClientOrchestrationCommand,
type IsoDateTime,
type OrchestrationCommand,
OrchestrationDispatchCommandError,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
} from "@t3tools/contracts";
import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore.ts";
import { planAttachmentClaim } from "../attachmentStore.ts";
import { ServerConfig } from "../config.ts";
import { parseBase64DataUrl } from "../imageMime.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
export const canonicalizeClientCommandTimestamps = (
@@ -48,7 +45,6 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
const receivedAt = DateTime.formatIso(yield* DateTime.now);
const canonicalCommand = canonicalizeClientCommandTimestamps(command, receivedAt);
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
@@ -104,67 +100,55 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
return canonicalCommand as OrchestrationCommand;
}
// Attachments arrive as id references to bytes already uploaded via the
// signed upload URL flow. Each `pending-<uuid>` file is renamed to its
// thread segment here; the uuid never changes, so signed asset URLs and
// send retries (which may reference an already-renamed file) keep working.
const normalizedAttachments = yield* Effect.forEach(
canonicalCommand.message.attachments,
(attachment) =>
Effect.gen(function* () {
const parsed = parseBase64DataUrl(attachment.dataUrl);
if (!parsed || !parsed.mimeType.startsWith("image/")) {
return yield* new OrchestrationDispatchCommandError({
message: `Invalid image 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.`,
});
}
const attachmentId = createAttachmentId(canonicalCommand.threadId);
if (!attachmentId) {
return yield* new OrchestrationDispatchCommandError({
message: "Failed to create a safe attachment id.",
});
}
const persistedAttachment = {
type: "image" as const,
id: attachmentId,
name: attachment.name,
mimeType: parsed.mimeType.toLowerCase(),
sizeBytes: bytes.byteLength,
};
const attachmentPath = resolveAttachmentPath({
const claimPlan = planAttachmentClaim({
attachmentsDir: serverConfig.attachmentsDir,
attachment: persistedAttachment,
threadId: canonicalCommand.threadId,
attachmentId: attachment.id,
});
if (!attachmentPath) {
if (!claimPlan.ok) {
return yield* new OrchestrationDispatchCommandError({
message: `Failed to resolve persisted path for '${attachment.name}'.`,
message: `Attachment '${attachment.name}' cannot be sent: ${claimPlan.reason}.`,
});
}
yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
const stats = yield* fileSystem.stat(claimPlan.currentPath).pipe(
Effect.mapError(
() =>
new OrchestrationDispatchCommandError({
message: `Failed to create attachment directory for '${attachment.name}'.`,
}),
),
);
yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
Effect.mapError(
() =>
new OrchestrationDispatchCommandError({
message: `Failed to persist attachment '${attachment.name}'.`,
message: `Attachment '${attachment.name}' cannot be sent: attachment not found (removed or expired).`,
}),
),
);
if (Number(stats.size) !== attachment.sizeBytes) {
return yield* new OrchestrationDispatchCommandError({
message: `Attachment '${attachment.name}' cannot be sent: stored size does not match the reference.`,
});
}
return persistedAttachment;
if (!claimPlan.alreadyScoped) {
yield* fileSystem.rename(claimPlan.currentPath, claimPlan.finalPath).pipe(
Effect.mapError(
() =>
new OrchestrationDispatchCommandError({
message: `Failed to claim attachment '${attachment.name}' for this thread.`,
}),
),
);
}
return {
...attachment,
id: claimPlan.finalId,
mimeType: attachment.mimeType.toLowerCase(),
};
}),
{ concurrency: 1 },
);
+2
View File
@@ -13,6 +13,7 @@ import * as ServerConfig from "./config.ts";
import {
otlpTracesProxyRouteLayer,
assetRouteLayer,
attachmentUploadRouteLayer,
serverEnvironmentHttpApiLayer,
staticAndDevRouteLayer,
browserApiCorsLayer,
@@ -451,6 +452,7 @@ export const makeRoutesLayer = Layer.mergeAll(
),
otlpTracesProxyRouteLayer,
assetRouteLayer,
attachmentUploadRouteLayer,
staticAndDevRouteLayer,
websocketRpcRouteLayer,
),
+11
View File
@@ -88,6 +88,7 @@ import * as TerminalManager from "./terminal/Manager.ts";
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
import * as PreviewManager from "./preview/Manager.ts";
import { issueAssetUrl } from "./assets/AssetAccess.ts";
import { deletePendingAttachment, issueAttachmentUploadUrl } from "./assets/AttachmentUpload.ts";
import * as PortScanner from "./preview/PortScanner.ts";
import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
@@ -1839,6 +1840,16 @@ const makeWsRpcLayer = (
),
{ "rpc.aggregate": "workspace" },
),
[WS_METHODS.attachmentsCreateUploadUrl]: (input) =>
observeRpcEffect(WS_METHODS.attachmentsCreateUploadUrl, issueAttachmentUploadUrl(input), {
"rpc.aggregate": "workspace",
}),
[WS_METHODS.attachmentsDelete]: (input) =>
observeRpcEffect(
WS_METHODS.attachmentsDelete,
deletePendingAttachment(input.attachmentId),
{ "rpc.aggregate": "workspace" },
),
[WS_METHODS.assetsCreateUrl]: (input) =>
observeRpcEffect(
WS_METHODS.assetsCreateUrl,