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:
1 parent
5304f3e9d4
commit
f695b6f5bf
38 files changed
+2266
-1281
No files matched your search
@@ -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)),
|
||||
);
|
||||
});
|
||||
@@ -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 },
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user