Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodePath from "node:path";
4
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import { describe, expect, it } from "@effect/vitest";
7import {
8 type ClientOrchestrationCommand,
9 CommandId,
10 MessageId,
11 ThreadId,
12} from "@t3tools/contracts";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15
16import * as ServerConfig from "../config.ts";
17import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
18import { cleanupFailedUploadedAttachments, normalizeDispatchCommand } from "./Normalizer.ts";
19
20const testLayer = Layer.mergeAll(
21 WorkspacePaths.layer,
22 ServerConfig.layerTest(process.cwd(), { prefix: "t3-normalizer-attachments-" }),
23).pipe(Layer.provideMerge(NodeServices.layer));
24
25const attachmentUuid = "00000000-0000-4000-8000-0000000000aa";
26
27function turnStartCommand(input: {
28 readonly threadId?: string;
29 readonly attachments: ReadonlyArray<
30 | { readonly id: string; readonly sizeBytes: number }
31 | { readonly dataUrl: string; readonly sizeBytes: number }
32 >;
33}): ClientOrchestrationCommand {
34 return {
35 type: "thread.turn.start",
36 commandId: CommandId.make("command-1"),
37 threadId: ThreadId.make(input.threadId ?? "thread-1"),
38 message: {
39 messageId: MessageId.make("message-1"),
40 role: "user",
41 text: "look at this",
42 attachments: input.attachments.map((attachment) => ({
43 type: "image" as const,
44 name: "screenshot.png",
45 mimeType: "image/png",
46 ...attachment,
47 })),
48 },
49 runtimeMode: "full-access",
50 interactionMode: "default",
51 createdAt: "2026-08-01T00:00:00.000Z",
52 };
53}
54
55describe("normalizeDispatchCommand attachments", () => {
56 it.effect("preserves inline image attachments from existing mobile clients", () =>
57 Effect.gen(function* () {
58 const config = yield* ServerConfig.ServerConfig;
59 const normalized = yield* normalizeDispatchCommand(
60 turnStartCommand({
61 attachments: [{ dataUrl: "data:image/png;base64,cGl4ZWxz", sizeBytes: 6 }],
62 }),
63 );
64 if (normalized.type !== "thread.turn.start") {
65 throw new Error("Expected a thread.turn.start command.");
66 }
67
68 const attachment = normalized.message.attachments[0]!;
69 expect(attachment.id.startsWith("thread-1-")).toBe(true);
70 expect(
71 NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${attachment.id}.png`)),
72 ).toEqual(Buffer.from("pixels"));
73 }).pipe(Effect.provide(testLayer)),
74 );
75
76 it.effect("claims uploaded attachments while retaining a retryable pending copy", () =>
77 Effect.gen(function* () {
78 const config = yield* ServerConfig.ServerConfig;
79 const bytes = Buffer.from("pixels");
80 const pendingPath = NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`);
81 NodeFS.writeFileSync(pendingPath, bytes);
82
83 const normalized = yield* normalizeDispatchCommand(
84 turnStartCommand({
85 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: bytes.byteLength }],
86 }),
87 );
88 if (normalized.type !== "thread.turn.start") {
89 throw new Error("Expected a thread.turn.start command.");
90 }
91
92 const attachmentId = normalized.message.attachments[0]!.id;
93 expect(attachmentId.startsWith("thread-1-")).toBe(true);
94 expect(attachmentId).not.toBe(`thread-1-${attachmentUuid}`);
95 expect(NodeFS.existsSync(pendingPath)).toBe(true);
96 expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${attachmentId}.png`))).toBe(
97 true,
98 );
99 }).pipe(Effect.provide(testLayer)),
100 );
101
102 it.effect("normalizes inline and uploaded attachments in the same turn", () =>
103 Effect.gen(function* () {
104 const config = yield* ServerConfig.ServerConfig;
105 NodeFS.writeFileSync(
106 NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`),
107 Buffer.from("pixels"),
108 );
109
110 const normalized = yield* normalizeDispatchCommand(
111 turnStartCommand({
112 attachments: [
113 { dataUrl: "data:image/png;base64,cGl4ZWxz", sizeBytes: 6 },
114 { id: `pending-${attachmentUuid}`, sizeBytes: 6 },
115 ],
116 }),
117 );
118 if (normalized.type !== "thread.turn.start") {
119 throw new Error("Expected a thread.turn.start command.");
120 }
121
122 expect(normalized.message.attachments).toHaveLength(2);
123 expect(normalized.message.attachments[1]?.id.startsWith("thread-1-")).toBe(true);
124 }).pipe(Effect.provide(testLayer)),
125 );
126
127 it.effect("retries a failed bootstrap with a fresh thread id", () =>
128 Effect.gen(function* () {
129 const config = yield* ServerConfig.ServerConfig;
130 const bytes = Buffer.from("pixels");
131 NodeFS.writeFileSync(
132 NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`),
133 bytes,
134 );
135
136 const first = yield* normalizeDispatchCommand(
137 turnStartCommand({
138 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: bytes.byteLength }],
139 }),
140 );
141 if (first.type !== "thread.turn.start") {
142 throw new Error("Expected a thread.turn.start command.");
143 }
144 NodeFS.rmSync(
145 NodePath.join(config.attachmentsDir, `${first.message.attachments[0]!.id}.png`),
146 );
147
148 const retried = yield* normalizeDispatchCommand(
149 turnStartCommand({
150 threadId: "thread-retry",
151 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: bytes.byteLength }],
152 }),
153 );
154 if (retried.type !== "thread.turn.start") {
155 throw new Error("Expected a thread.turn.start command.");
156 }
157 expect(retried.message.attachments[0]?.id.startsWith("thread-retry-")).toBe(true);
158 }).pipe(Effect.provide(testLayer)),
159 );
160
161 it.effect("removes failed attachment claims without deleting their pending uploads", () =>
162 Effect.gen(function* () {
163 const config = yield* ServerConfig.ServerConfig;
164 const pendingPath = NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`);
165 NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
166 const command = turnStartCommand({
167 attachments: [
168 { dataUrl: "data:image/png;base64,cGl4ZWxz", sizeBytes: 6 },
169 { id: `pending-${attachmentUuid}`, sizeBytes: 6 },
170 ],
171 });
172 const normalized = yield* normalizeDispatchCommand(command);
173 if (normalized.type !== "thread.turn.start") {
174 throw new Error("Expected a thread.turn.start command.");
175 }
176
177 const inlinePath = NodePath.join(
178 config.attachmentsDir,
179 `${normalized.message.attachments[0]!.id}.png`,
180 );
181 const claimedPath = NodePath.join(
182 config.attachmentsDir,
183 `${normalized.message.attachments[1]!.id}.png`,
184 );
185 yield* cleanupFailedUploadedAttachments(command, normalized);
186
187 expect(NodeFS.existsSync(pendingPath)).toBe(true);
188 expect(NodeFS.existsSync(claimedPath)).toBe(false);
189 expect(NodeFS.existsSync(inlinePath)).toBe(true);
190 }).pipe(Effect.provide(testLayer)),
191 );
192
193 it.effect("removes a failed claimed copy after its pending original was removed", () =>
194 Effect.gen(function* () {
195 const config = yield* ServerConfig.ServerConfig;
196 const pendingPath = NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`);
197 NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
198 const command = turnStartCommand({
199 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: 6 }],
200 });
201 const normalized = yield* normalizeDispatchCommand(command);
202 if (normalized.type !== "thread.turn.start") {
203 throw new Error("Expected a thread.turn.start command.");
204 }
205
206 const claimedPath = NodePath.join(
207 config.attachmentsDir,
208 `${normalized.message.attachments[0]!.id}.png`,
209 );
210 NodeFS.rmSync(pendingPath);
211
212 yield* cleanupFailedUploadedAttachments(command, normalized);
213
214 expect(NodeFS.existsSync(claimedPath)).toBe(false);
215 }).pipe(Effect.provide(testLayer)),
216 );
217
218 it.effect("keeps concurrent claims independent when one dispatch fails", () =>
219 Effect.gen(function* () {
220 const config = yield* ServerConfig.ServerConfig;
221 const pendingPath = NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`);
222 NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
223 const command = turnStartCommand({
224 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: 6 }],
225 });
226
227 const [failed, succeeded] = yield* Effect.all(
228 [normalizeDispatchCommand(command), normalizeDispatchCommand(command)],
229 { concurrency: 2 },
230 );
231 if (failed.type !== "thread.turn.start" || succeeded.type !== "thread.turn.start") {
232 throw new Error("Expected thread.turn.start commands.");
233 }
234
235 const failedPath = NodePath.join(
236 config.attachmentsDir,
237 `${failed.message.attachments[0]!.id}.png`,
238 );
239 const succeededPath = NodePath.join(
240 config.attachmentsDir,
241 `${succeeded.message.attachments[0]!.id}.png`,
242 );
243 expect(failedPath).not.toBe(succeededPath);
244
245 yield* cleanupFailedUploadedAttachments(command, failed);
246
247 expect(NodeFS.existsSync(pendingPath)).toBe(true);
248 expect(NodeFS.existsSync(failedPath)).toBe(false);
249 expect(NodeFS.existsSync(succeededPath)).toBe(true);
250 }).pipe(Effect.provide(testLayer)),
251 );
252
253 it.effect("removes earlier claimed copies when a later attachment cannot be normalized", () =>
254 Effect.gen(function* () {
255 const config = yield* ServerConfig.ServerConfig;
256 const pendingId = `pending-${attachmentUuid}`;
257 const pendingPath = NodePath.join(config.attachmentsDir, `${pendingId}.png`);
258 NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
259
260 const failure = yield* normalizeDispatchCommand(
261 turnStartCommand({
262 attachments: [
263 { id: pendingId, sizeBytes: 6 },
264 {
265 id: "pending-00000000-0000-4000-8000-0000000000ff",
266 sizeBytes: 6,
267 },
268 ],
269 }),
270 ).pipe(Effect.flip);
271
272 expect(failure.message).toContain("not found");
273 expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([`${pendingId}.png`]);
274 }).pipe(Effect.provide(testLayer)),
275 );
276
277 it.effect("rejects uploaded attachments with the wrong size or thread", () =>
278 Effect.gen(function* () {
279 const config = yield* ServerConfig.ServerConfig;
280 NodeFS.writeFileSync(
281 NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`),
282 Buffer.from("pixels"),
283 );
284
285 const wrongSize = yield* normalizeDispatchCommand(
286 turnStartCommand({
287 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: 999 }],
288 }),
289 ).pipe(Effect.flip);
290 expect(wrongSize.message).toContain("size");
291
292 const wrongThread = yield* normalizeDispatchCommand(
293 turnStartCommand({
294 attachments: [{ id: `another-thread-${attachmentUuid}`, sizeBytes: 6 }],
295 }),
296 ).pipe(Effect.flip);
297 expect(wrongThread.message).toContain("pending upload");
298
299 const mismatchedTypeCommand = turnStartCommand({
300 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: 6 }],
301 });
302 if (mismatchedTypeCommand.type !== "thread.turn.start") {
303 throw new Error("Expected a thread.turn.start command.");
304 }
305 const mismatchedType = yield* normalizeDispatchCommand({
306 ...mismatchedTypeCommand,
307 message: {
308 ...mismatchedTypeCommand.message,
309 attachments: mismatchedTypeCommand.message.attachments.map((attachment) => ({
310 ...attachment,
311 mimeType: "image/jpeg",
312 })),
313 },
314 }).pipe(Effect.flip);
315 expect(mismatchedType.message).toContain("image type");
316 }).pipe(Effect.provide(testLayer)),
317 );
318});