History

test(contracts,web): cover file attachment variant, drafts, and rendering

Andrei Drăgan Răduleț committed 4 months ago

Commit f8da3b51 parent 4050afe5 files · +366 −0Browse files

Unified · Split

5 files
  1. apps/web/src/components/chat/MessagesTimeline.test.tsx +82 −0
  2. apps/web/src/composerDraftStore.test.ts +145 −0
  3. apps/web/src/historyBootstrap.test.ts +37 −0
  4. apps/web/src/lib/attachmentSize.test.ts +22 −0
  5. packages/contracts/src/orchestration.test.ts +80 −0
apps/web/src/components/chat/MessagesTimeline.test.tsx+82−0
@@ -381,6 +381,88 @@ describe("MessagesTimeline", () => { · 380 unmodified lines
381 expect(onAnchorSizeChanged).toHaveBeenCalledWith(secondEntry.message.id, 240);381 expect(onAnchorSizeChanged).toHaveBeenCalledWith(secondEntry.message.id, 240);
382 });382 });
383 383
384 it("renders file attachments as chips with name and size instead of images", async () => {
385 const { MessagesTimeline } = await import("./MessagesTimeline");
386 const entry = {
387 ...buildUserTimelineEntry("Please review the attached report."),
388 message: {
389 ...buildUserTimelineEntry("Please review the attached report.").message,
390 attachments: [
391 {
392 type: "file" as const,
393 id: "attachment-file-1",
394 name: "report.pdf",
395 mimeType: "application/pdf",
396 sizeBytes: 2_048,
397 },
398 ],
399 },
400 };
401 const markup = renderToStaticMarkup(
402 <MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
403 );
404
405 expect(markup).toContain("report.pdf");
406 expect(markup).toContain("2.0 KB");
407 expect(markup).toContain("lucide-file-text");
408 expect(markup).not.toContain("<img");
409 });
410
411 it("renders downloadable file attachment chips when a preview URL is available", async () => {
412 const { MessagesTimeline } = await import("./MessagesTimeline");
413 const entry = {
414 ...buildUserTimelineEntry("Here is the file."),
415 message: {
416 ...buildUserTimelineEntry("Here is the file.").message,
417 attachments: [
418 {
419 type: "file" as const,
420 id: "attachment-file-2",
421 name: "notes.txt",
422 mimeType: "text/plain",
423 sizeBytes: 512,
424 previewUrl: "data:text/plain;base64,aGVsbG8=",
425 },
426 ],
427 },
428 };
429 const markup = renderToStaticMarkup(
430 <MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
431 );
432
433 expect(markup).toContain('download="notes.txt"');
434 expect(markup).toContain('href="data:text/plain;base64,aGVsbG8="');
435 expect(markup).toContain("512 B");
436 });
437
438 it("renders image attachments in the image grid without file chips", async () => {
439 const { MessagesTimeline } = await import("./MessagesTimeline");
440 const entry = {
441 ...buildUserTimelineEntry("Take a look."),
442 message: {
443 ...buildUserTimelineEntry("Take a look.").message,
444 attachments: [
445 {
446 type: "image" as const,
447 id: "attachment-image-1",
448 name: "screenshot.png",
449 mimeType: "image/png",
450 sizeBytes: 1,
451 previewUrl: "data:image/png;base64,iVBORw0KGgo=",
452 },
453 ],
454 },
455 };
456 const markup = renderToStaticMarkup(
457 <MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
458 );
459
460 expect(markup).toContain('src="data:image/png;base64,iVBORw0KGgo="');
461 expect(markup).toContain('alt="screenshot.png"');
462 expect(markup).not.toContain("lucide-file-text");
463 expect(markup).not.toContain("download=");
464 });
465
384 it("renders collapse controls for long user messages", async () => {466 it("renders collapse controls for long user messages", async () => {
385 const { MessagesTimeline } = await import("./MessagesTimeline");467 const { MessagesTimeline } = await import("./MessagesTimeline");
386 const markup = renderToStaticMarkup(468 const markup = renderToStaticMarkup(
apps/web/src/composerDraftStore.test.ts+145−0
@@ -65,6 +65,7 @@ import { · 64 unmodified lines
65 markPromotedDraftThreadByRef,65 markPromotedDraftThreadByRef,
66 markPromotedDraftThreads,66 markPromotedDraftThreads,
67 markPromotedDraftThreadsByRef,67 markPromotedDraftThreadsByRef,
68 type ComposerFileAttachment,
68 type ComposerImageAttachment,69 type ComposerImageAttachment,
69 useComposerDraftStore,70 useComposerDraftStore,
70 DraftId,71 DraftId,
@@ -104,6 +105,33 @@ function makeImage(input: { · 33 unmodified lines
104 };105 };
105}106}
106 107
108function makeFile(input: {
109 id: string;
110 previewUrl: string;
111 name?: string;
112 mimeType?: string;
113 sizeBytes?: number;
114 lastModified?: number;
115}): ComposerFileAttachment {
116 const name = input.name ?? "report.pdf";
117 const mimeType = input.mimeType ?? "application/pdf";
118 const sizeBytes = input.sizeBytes ?? 4;
119 const lastModified = input.lastModified ?? 1_700_000_000_000;
120 const file = new File([new Uint8Array(sizeBytes).fill(1)], name, {
121 type: mimeType,
122 lastModified,
123 });
124 return {
125 type: "file",
126 id: input.id,
127 name,
128 mimeType,
129 sizeBytes: file.size,
130 previewUrl: input.previewUrl,
131 file,
132 };
133}
134
107function makeTerminalContext(input: {135function makeTerminalContext(input: {
108 id: string;136 id: string;
109 text?: string;137 text?: string;
@@ -345,6 +373,123 @@ describe("composerDraftStore syncPersistedAttachments", () => { · 235 unmodified lines
345 });373 });
346});374});
347 375
376describe("composerDraftStore file attachments", () => {
377 const threadId = ThreadId.make("thread-file-attachments");
378 const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
379
380 beforeEach(() => {
381 removeLocalStorageItem(COMPOSER_DRAFT_STORAGE_KEY);
382 resetComposerDraftStore();
383 });
384
385 afterEach(() => {
386 removeLocalStorageItem(COMPOSER_DRAFT_STORAGE_KEY);
387 });
388
389 function mergePersistedDraft(attachment: Record<string, unknown>) {
390 const persistApi = useComposerDraftStore.persist as unknown as {
391 getOptions: () => {
392 merge: (
393 persistedState: unknown,
394 currentState: ReturnType<typeof useComposerDraftStore.getState>,
395 ) => ReturnType<typeof useComposerDraftStore.getState>;
396 };
397 };
398 return persistApi.getOptions().merge(
399 {
400 draftsByThreadId: {
401 [threadId]: {
402 prompt: "",
403 attachments: [attachment],
404 },
405 },
406 draftThreadsByThreadId: {},
407 projectDraftThreadIdByProjectKey: {},
408 },
409 useComposerDraftStore.getInitialState(),
410 );
411 }
412
413 it("hydrates persisted attachments without a type as images (legacy drafts)", () => {
414 const mergedState = mergePersistedDraft({
415 id: "img-legacy",
416 name: "legacy.png",
417 mimeType: "image/png",
418 sizeBytes: 5,
419 dataUrl: "data:image/png;base64,aGVsbG8=",
420 });
421
422 expect(mergedState.draftsByThreadKey[threadKeyFor(threadId)]?.images).toMatchObject([
423 {
424 type: "image",
425 id: "img-legacy",
426 name: "legacy.png",
427 mimeType: "image/png",
428 sizeBytes: 5,
429 previewUrl: "data:image/png;base64,aGVsbG8=",
430 },
431 ]);
432 });
433
434 it("hydrates persisted attachments with type file as file attachments", () => {
435 const mergedState = mergePersistedDraft({
436 type: "file",
437 id: "file-persisted",
438 name: "report.pdf",
439 mimeType: "application/pdf",
440 sizeBytes: 5,
441 dataUrl: "data:application/pdf;base64,aGVsbG8=",
442 });
443
444 expect(mergedState.draftsByThreadKey[threadKeyFor(threadId)]?.images).toMatchObject([
445 {
446 type: "file",
447 id: "file-persisted",
448 name: "report.pdf",
449 mimeType: "application/pdf",
450 sizeBytes: 5,
451 previewUrl: "data:application/pdf;base64,aGVsbG8=",
452 },
453 ]);
454 });
455
456 it("persists the file type for staged file attachments (round trip)", () => {
457 const attachment = makeFile({
458 id: "file-round-trip",
459 previewUrl: "data:application/pdf;base64,aGVsbG8=",
460 });
461 useComposerDraftStore.getState().addImage(threadRef, attachment);
462 useComposerDraftStore.getState().syncPersistedAttachments(threadRef, [
463 {
464 type: "file",
465 id: attachment.id,
466 name: attachment.name,
467 mimeType: attachment.mimeType,
468 sizeBytes: attachment.sizeBytes,
469 dataUrl: attachment.previewUrl,
470 },
471 ]);
472
473 const persistApi = useComposerDraftStore.persist as unknown as {
474 getOptions: () => {
475 partialize: (state: ReturnType<typeof useComposerDraftStore.getState>) => unknown;
476 };
477 };
478 const persisted = persistApi.getOptions().partialize(useComposerDraftStore.getState()) as {
479 draftsByThreadKey?: Record<string, { attachments?: Array<Record<string, unknown>> }>;
480 };
481
482 expect(
483 persisted.draftsByThreadKey?.[threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]?.attachments?.[0],
484 ).toMatchObject({
485 type: "file",
486 id: "file-round-trip",
487 name: "report.pdf",
488 mimeType: "application/pdf",
489 });
490 });
491});
492
348describe("composerDraftStore terminal contexts", () => {493describe("composerDraftStore terminal contexts", () => {
349 const threadId = ThreadId.make("thread-dedupe");494 const threadId = ThreadId.make("thread-dedupe");
350 const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);495 const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
apps/web/src/historyBootstrap.test.ts+37−0
@@ -136,4 +136,41 @@ describe("buildBootstrapInput", () => { · 135 unmodified lines
136 expect(result.text).toContain("Attached image");136 expect(result.text).toContain("Attached image");
137 expect(result.text).toContain("screenshot.png");137 expect(result.text).toContain("screenshot.png");
138 });138 });
139
140 it("captures mixed image and file attachment context in transcript blocks", () => {
141 const result = buildBootstrapInput(
142 [
143 {
144 id: messageId("u-mixed"),
145 role: "user",
146 text: "Compare the screenshot with the report.",
147 attachments: [
148 {
149 type: "image",
150 id: "img-1",
151 name: "screenshot.png",
152 mimeType: "image/png",
153 sizeBytes: 2_048,
154 },
155 {
156 type: "file",
157 id: "file-1",
158 name: "report.pdf",
159 mimeType: "application/pdf",
160 sizeBytes: 4_096,
161 },
162 ],
163 createdAt: "2026-02-09T00:00:00.000Z",
164 turnId: null,
165 updatedAt: "2026-02-09T00:00:00.000Z",
166 streaming: false,
167 },
168 ],
169 "What differs?",
170 1_500,
171 );
172
173 expect(result.text).toContain("[Attached image: screenshot.png]");
174 expect(result.text).toContain("[Attached file: report.pdf]");
175 });
139});176});
apps/web/src/lib/attachmentSize.test.ts+22−0
@@ -0,0 +1,22 @@
1import { describe, expect, it } from "vite-plus/test";
2
3import { formatAttachmentSizeLabel } from "./attachmentSize";
4
5describe("formatAttachmentSizeLabel", () => {
6 it("formats sub-kilobyte sizes in bytes", () => {
7 expect(formatAttachmentSizeLabel(0)).toBe("0 B");
8 expect(formatAttachmentSizeLabel(512)).toBe("512 B");
9 expect(formatAttachmentSizeLabel(1_023)).toBe("1023 B");
10 });
11
12 it("formats kilobyte sizes with one decimal", () => {
13 expect(formatAttachmentSizeLabel(1_024)).toBe("1.0 KB");
14 expect(formatAttachmentSizeLabel(2_048)).toBe("2.0 KB");
15 expect(formatAttachmentSizeLabel(1_024 * 1_024 - 1)).toBe("1024.0 KB");
16 });
17
18 it("formats megabyte sizes with one decimal", () => {
19 expect(formatAttachmentSizeLabel(1_024 * 1_024)).toBe("1.0 MB");
20 expect(formatAttachmentSizeLabel(2_202_010)).toBe("2.1 MB");
21 });
22});
packages/contracts/src/orchestration.test.ts+80−0
@@ -3,6 +3,9 @@ import * as Effect from "effect/Effect"; · 2 unmodified lines
3import * as Schema from "effect/Schema";3import * as Schema from "effect/Schema";
4 4
5import {5import {
6 ChatAttachment,
7 ChatFileAttachment,
8 ChatImageAttachment,
6 DEFAULT_PROVIDER_INTERACTION_MODE,9 DEFAULT_PROVIDER_INTERACTION_MODE,
7 DEFAULT_RUNTIME_MODE,10 DEFAULT_RUNTIME_MODE,
8 ModelSelection,11 ModelSelection,
@@ -743,3 +746,80 @@ it.effect("ModelSelection rejects malformed instance ids", () => · 734 unmodified lines
743 assert.strictEqual(result._tag, "Failure");746 assert.strictEqual(result._tag, "Failure");
744 }),747 }),
745);748);
749
750// ── ChatAttachment: image/file union ──────────────────────────────────
751
752const decodeChatAttachment = Schema.decodeUnknownEffect(ChatAttachment);
753const decodeChatAttachmentArray = Schema.decodeUnknownEffect(Schema.Array(ChatAttachment));
754const decodeChatImageAttachment = Schema.decodeUnknownEffect(ChatImageAttachment);
755const decodeChatFileAttachment = Schema.decodeUnknownEffect(ChatFileAttachment);
756
757it.effect("ChatAttachment decodes a file attachment with a non-image mime type", () =>
758 Effect.gen(function* () {
759 const parsed = yield* decodeChatAttachment({
760 type: "file",
761 id: "file-1",
762 name: "report.pdf",
763 mimeType: "application/pdf",
764 sizeBytes: 2_048,
765 });
766 assert.strictEqual(parsed.type, "file");
767 assert.strictEqual(parsed.name, "report.pdf");
768 assert.strictEqual(parsed.mimeType, "application/pdf");
769 assert.strictEqual(parsed.sizeBytes, 2_048);
770 }),
771);
772
773it.effect("ChatAttachment arrays still decode legacy image-only attachments", () =>
774 Effect.gen(function* () {
775 const parsed = yield* decodeChatAttachmentArray([
776 {
777 type: "image",
778 id: "img-1",
779 name: "screenshot.png",
780 mimeType: "image/png",
781 sizeBytes: 1_024,
782 },
783 {
784 type: "image",
785 id: "img-2",
786 name: "diagram.jpeg",
787 mimeType: "image/jpeg",
788 sizeBytes: 4_096,
789 },
790 ]);
791 assert.strictEqual(parsed.length, 2);
792 assert.strictEqual(parsed[0]?.type, "image");
793 assert.strictEqual(parsed[1]?.type, "image");
794 }),
795);
796
797it.effect("ChatImageAttachment rejects non-image mime types", () =>
798 Effect.gen(function* () {
799 const result = yield* Effect.exit(
800 decodeChatImageAttachment({
801 type: "image",
802 id: "img-1",
803 name: "report.pdf",
804 mimeType: "application/pdf",
805 sizeBytes: 2_048,
806 }),
807 );
808 assert.strictEqual(result._tag, "Failure");
809 }),
810);
811
812it.effect("ChatFileAttachment rejects sizeBytes over the 10MB limit", () =>
813 Effect.gen(function* () {
814 const result = yield* Effect.exit(
815 decodeChatFileAttachment({
816 type: "file",
817 id: "file-1",
818 name: "big.bin",
819 mimeType: "application/octet-stream",
820 sizeBytes: 10 * 1024 * 1024 + 1,
821 }),
822 );
823 assert.strictEqual(result._tag, "Failure");
824 }),
825);

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t