@marimo-team/islands 0.25.3-dev402 → 0.25.3-dev408

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/{ConnectedDataExplorerComponent-1DGGwl88.js → ConnectedDataExplorerComponent-DCW4bXq-.js} +1 -1
  2. package/dist/{ErrorBoundary-DfbzIKA3.js → ErrorBoundary-W6a-7ong.js} +1 -1
  3. package/dist/{chat-ui-r3PPIMn0.js → chat-ui-BGEXB6V4.js} +1354 -1320
  4. package/dist/{code-visibility-CXijswY7.js → code-visibility-0v5rL9iu.js} +1 -1
  5. package/dist/{common-Cm5ENbUw.js → common-B7sS0asw.js} +1 -1
  6. package/dist/{data-grid-overlay-editor-Dv0TkGKt.js → data-grid-overlay-editor-DtWpYC-j.js} +1 -1
  7. package/dist/{feedback-button-Xk-mOev4.js → feedback-button-KVSGwnVr.js} +2 -2
  8. package/dist/{glide-data-editor-DdxBDWAj.js → glide-data-editor-D0dykzDr.js} +3 -3
  9. package/dist/{globals-DR3VVkF6.js → globals-DOi11Nup.js} +1 -1
  10. package/dist/main.js +6160 -6141
  11. package/dist/{number-overlay-editor-Cc5gJryh.js → number-overlay-editor-DoR-BTMn.js} +1 -1
  12. package/dist/{process-output-39KkAXSF.js → process-output-BvCDoG-m.js} +14 -25
  13. package/dist/{reveal-component-Dm5K9KPi.js → reveal-component-Vu8VncD4.js} +2 -2
  14. package/dist/{spec-Ww0JjShW.js → spec-DV8oNpRR.js} +46 -49
  15. package/dist/{semaphore-8KhQouXt.js → useDeepCompareMemoize-C90a6_io.js} +15 -5
  16. package/dist/{vega-component-DQZhTzVQ.js → vega-component-ArEoBGzQ.js} +197 -198
  17. package/package.json +1 -1
  18. package/src/components/chat/__tests__/chat-utils.test.ts +48 -0
  19. package/src/components/chat/__tests__/message-queue.test.tsx +94 -1
  20. package/src/components/chat/__tests__/pending-chat-prompt.test.tsx +568 -0
  21. package/src/components/chat/__tests__/useFileState.test.tsx +176 -15
  22. package/src/components/chat/chat-components.tsx +3 -2
  23. package/src/components/chat/chat-panel.tsx +199 -74
  24. package/src/components/chat/chat-utils.ts +148 -34
  25. package/src/components/chat/user-message.tsx +15 -6
  26. package/src/components/data-table/charts/__tests__/altair-generator.test.ts +42 -27
  27. package/src/components/data-table/charts/chart-spec/altair-generator.ts +2 -6
  28. package/src/core/ai/__tests__/attachments.test.ts +153 -0
  29. package/src/core/ai/attachments.ts +80 -0
  30. package/src/utils/python-poet/poet.ts +12 -2
  31. package/dist/useDeepCompareMemoize-Bvrue1iy.js +0 -11
@@ -12,43 +12,58 @@ import {
12
12
  } from "ai";
13
13
  import { useRef, useState } from "react";
14
14
  import useEvent from "react-use-event-hook";
15
- import type { ProviderId } from "@/core/ai/ids/ids";
15
+ import {
16
+ getAttachmentMediaType,
17
+ isSupportedAttachmentType,
18
+ normalizeAttachment,
19
+ } from "@/core/ai/attachments";
16
20
  import type { ToolNotebookContext } from "@/core/ai/tools/base";
17
21
  import { FRONTEND_TOOL_REGISTRY } from "@/core/ai/tools/registry";
18
22
  import type {
19
23
  InvokeAiToolRequest,
20
24
  InvokeAiToolResponse,
21
25
  } from "@/core/network/types";
22
- import { blobToString } from "@/utils/fileToBase64";
26
+ import { serializeBlob } from "@/utils/blob";
23
27
  import { Logger } from "@/utils/Logger";
24
28
  import { generateUUID } from "@/utils/uuid";
25
29
  import { getAICompletionBodyWithAttachments } from "../editor/ai/completion-utils";
26
30
  import { toast } from "../ui/use-toast";
27
31
 
28
- // We need to modify the backend to support attachments for other providers
29
- // And other types
30
- export const PROVIDERS_THAT_SUPPORT_ATTACHMENTS = new Set<ProviderId>([
31
- "openai",
32
- "google",
33
- "anthropic",
34
- ]);
35
- export const SUPPORTED_ATTACHMENT_TYPES = ["image/*", "text/*"];
36
32
  const MAX_ATTACHMENT_SIZE = 1024 * 1024 * 50; // 50MB
37
33
 
38
34
  export function generateChatTitle(message: string): string {
39
35
  return message.length > 50 ? `${message.slice(0, 50)}...` : message;
40
36
  }
41
37
 
38
+ export function hasAssistantProgress(messages: UIMessage[]): boolean {
39
+ const lastMessage = messages.at(-1);
40
+ return (
41
+ lastMessage?.role === "assistant" &&
42
+ lastMessage.parts.some((part) => {
43
+ switch (part.type) {
44
+ case "step-start":
45
+ return false;
46
+ case "text":
47
+ case "reasoning":
48
+ return part.text.trim().length > 0;
49
+ default:
50
+ return true;
51
+ }
52
+ })
53
+ );
54
+ }
55
+
42
56
  export async function convertToFileUIPart(
43
57
  files: File[],
44
58
  ): Promise<FileUIPart[]> {
45
59
  const fileUIParts = await Promise.all(
46
60
  files.map(async (file) => {
61
+ const normalizedFile = await normalizeAttachment(file);
47
62
  const part: FileUIPart = {
48
63
  type: "file" as const,
49
- mediaType: file.type,
64
+ mediaType: normalizedFile.type,
50
65
  filename: file.name,
51
- url: await blobToString(file, "dataUrl"),
66
+ url: await serializeBlob(normalizedFile),
52
67
  };
53
68
  return part;
54
69
  }),
@@ -219,10 +234,63 @@ function isUnresolvedToolState(state: ToolUIPart["state"]): boolean {
219
234
  }
220
235
  }
221
236
 
222
- export function useFileState() {
237
+ export function validateChatAttachments(
238
+ parts: ChatMessagePart[],
239
+ supportedTypes: readonly string[],
240
+ ): boolean {
241
+ return validateAttachments(
242
+ parts.filter((part): part is FileUIPart => part.type === "file"),
243
+ supportedTypes,
244
+ );
245
+ }
246
+
247
+ function validateAttachments(
248
+ files: { mediaType: string; filename?: string }[],
249
+ supportedTypes: readonly string[],
250
+ ): boolean {
251
+ const unsupported = files.filter(
252
+ (file) =>
253
+ !isSupportedAttachmentType(
254
+ getAttachmentMediaType(file.mediaType),
255
+ supportedTypes,
256
+ ),
257
+ );
258
+ if (unsupported.length > 0) {
259
+ toast({
260
+ title: "Unsupported attachment",
261
+ description: `These files are not supported by the selected model: ${unsupported.map((part) => part.filename || part.mediaType).join(", ")}`,
262
+ variant: "danger",
263
+ });
264
+ return false;
265
+ }
266
+ return true;
267
+ }
268
+
269
+ export function useFileState(supportedTypes?: readonly string[]) {
223
270
  const [files, setFiles] = useState<File[]>([]);
271
+ const generation = useRef(0);
272
+ const pendingReads = useRef(0);
273
+ const [isReadingFiles, setIsReadingFiles] = useState(false);
274
+
275
+ const validateFileTypes = useEvent((filesToValidate: File[]): boolean => {
276
+ return (
277
+ !supportedTypes ||
278
+ validateAttachments(
279
+ filesToValidate.map((file) => ({
280
+ mediaType: file.type,
281
+ filename: file.name,
282
+ })),
283
+ supportedTypes,
284
+ )
285
+ );
286
+ });
224
287
 
225
- const addFiles = useEvent((newFiles: File[]) => {
288
+ const validateFiles = useEvent(
289
+ (filesToValidate: File[]): boolean =>
290
+ pendingReads.current === 0 && validateFileTypes(filesToValidate),
291
+ );
292
+
293
+ const addFiles = useEvent(async (newFiles: File[]) => {
226
294
  if (newFiles.length === 0) {
227
295
  return;
228
296
  }
@@ -237,14 +305,49 @@ export function useFileState() {
237
305
  return;
238
306
  }
239
307
 
240
- setFiles((prev) => [...prev, ...newFiles]);
308
+ const currentGeneration = generation.current;
309
+ pendingReads.current += 1;
310
+ setIsReadingFiles(true);
311
+ try {
312
+ const normalizedFiles = supportedTypes
313
+ ? await Promise.all(newFiles.map(normalizeAttachment))
314
+ : newFiles;
315
+ if (
316
+ currentGeneration === generation.current &&
317
+ validateFileTypes(normalizedFiles)
318
+ ) {
319
+ setFiles((prev) => [...prev, ...normalizedFiles]);
320
+ }
321
+ } catch {
322
+ toast({
323
+ title: "Could not read attachments",
324
+ description: "Try selecting the files again.",
325
+ variant: "danger",
326
+ });
327
+ }
328
+ if (currentGeneration === generation.current) {
329
+ pendingReads.current -= 1;
330
+ setIsReadingFiles(pendingReads.current > 0);
331
+ }
241
332
  });
242
333
 
243
- const clearFiles = () => setFiles([]);
334
+ const clearFiles = () => {
335
+ generation.current += 1;
336
+ pendingReads.current = 0;
337
+ setIsReadingFiles(false);
338
+ setFiles([]);
339
+ };
244
340
  const removeFile = (fileToRemove: File) =>
245
341
  setFiles((prev) => prev.filter((f) => f !== fileToRemove));
246
342
 
247
- return { files, addFiles, clearFiles, removeFile };
343
+ return {
344
+ files,
345
+ addFiles,
346
+ clearFiles,
347
+ removeFile,
348
+ validateFiles,
349
+ isReadingFiles,
350
+ };
248
351
  }
249
352
 
250
353
  export type ChatMessagePart = UIMessage["parts"][number];
@@ -288,30 +391,41 @@ export function useMessageQueue() {
288
391
  const messagesRef = useRef<QueuedUserMessage[]>([]);
289
392
  const hasQueuedRef = useRef(false);
290
393
 
291
- const enqueue = useEvent((parts: ChatMessagePart[]) => {
292
- const next = [...messagesRef.current, { id: generateUUID(), parts }];
394
+ const updateQueue = useEvent((next: QueuedUserMessage[]) => {
293
395
  messagesRef.current = next;
294
- hasQueuedRef.current = true;
396
+ hasQueuedRef.current = next.length > 0;
295
397
  setMessages(next);
296
398
  });
297
399
 
298
- const flushNext = useEvent((send: (parts: ChatMessagePart[]) => void) => {
299
- const queue = messagesRef.current;
300
- if (queue.length === 0) {
301
- return;
302
- }
303
- const [next, ...rest] = queue;
304
- messagesRef.current = rest;
305
- hasQueuedRef.current = rest.length > 0;
306
- setMessages(rest);
307
- send(next.parts);
400
+ const enqueue = useEvent((parts: ChatMessagePart[]) => {
401
+ updateQueue([...messagesRef.current, { id: generateUUID(), parts }]);
308
402
  });
309
403
 
404
+ const flushNext = useEvent(
405
+ (
406
+ send: (parts: ChatMessagePart[]) => void,
407
+ canSend?: (parts: ChatMessagePart[]) => boolean,
408
+ ) => {
409
+ const queue = messagesRef.current;
410
+ if (queue.length === 0) {
411
+ return;
412
+ }
413
+ const [next, ...rest] = queue;
414
+ if (canSend && !canSend(next.parts)) {
415
+ return;
416
+ }
417
+ updateQueue(rest);
418
+ send(next.parts);
419
+ },
420
+ );
421
+
310
422
  const clear = useEvent(() => {
311
- messagesRef.current = [];
312
- hasQueuedRef.current = false;
313
- setMessages([]);
423
+ updateQueue([]);
424
+ });
425
+
426
+ const remove = useEvent((id: string) => {
427
+ updateQueue(messagesRef.current.filter((message) => message.id !== id));
314
428
  });
315
429
 
316
- return { messages, enqueue, flushNext, clear, hasQueuedRef };
430
+ return { messages, enqueue, flushNext, clear, remove, hasQueuedRef };
317
431
  }
@@ -14,7 +14,7 @@ import { AttachmentRenderer } from "./chat-components";
14
14
  interface UserMessageProps {
15
15
  message: UIMessage;
16
16
  canEdit: boolean;
17
- onEdit: (newValue: string) => void;
17
+ onEdit: (newValue: string) => Promise<boolean>;
18
18
  }
19
19
 
20
20
  export const UserMessage: React.FC<UserMessageProps> = ({
@@ -35,6 +35,7 @@ export const UserMessage: React.FC<UserMessageProps> = ({
35
35
  ));
36
36
 
37
37
  const [draft, setDraft] = React.useState<string | null>(null);
38
+ const [isSubmitting, setIsSubmitting] = React.useState(false);
38
39
  const inputRef = React.useRef<ReactCodeMirrorRef>(null);
39
40
  const editButtonRef = React.useRef<HTMLButtonElement>(null);
40
41
  const editing = draft != null;
@@ -49,12 +50,20 @@ export const UserMessage: React.FC<UserMessageProps> = ({
49
50
  requestAnimationFrame(() => editButtonRef.current?.focus());
50
51
  };
51
52
 
52
- const submit = (value: string) => {
53
- if (!canEdit || !value.trim()) {
53
+ const submit = async (value: string) => {
54
+ if (!canEdit || isSubmitting || !value.trim()) {
54
55
  return;
55
56
  }
56
- onEdit(value);
57
- setDraft(null);
57
+ setIsSubmitting(true);
58
+ try {
59
+ if (await onEdit(value)) {
60
+ setDraft((current) => (current === value ? null : current));
61
+ }
62
+ } catch (error) {
63
+ setIsSubmitting(false);
64
+ throw error;
65
+ }
66
+ setIsSubmitting(false);
58
67
  };
59
68
 
60
69
  if (editing) {
@@ -81,7 +90,7 @@ export const UserMessage: React.FC<UserMessageProps> = ({
81
90
  </Button>
82
91
  <Button
83
92
  size="xs"
84
- disabled={!canEdit || !draft.trim()}
93
+ disabled={!canEdit || isSubmitting || !draft.trim()}
85
94
  onClick={() => submit(draft)}
86
95
  >
87
96
  Send
@@ -447,12 +447,12 @@ describe("generateAltairChart", () => {
447
447
  `);
448
448
  });
449
449
 
450
- it("should escape dots in field names", () => {
450
+ it("should keep escaped dots in field names", () => {
451
451
  const spec = createSpec({
452
452
  mark: "bar",
453
453
  encoding: {
454
- x: { field: "name.field" },
455
- y: { field: "value.data" },
454
+ x: { field: String.raw`name\.field` },
455
+ y: { field: String.raw`value\.data` },
456
456
  },
457
457
  });
458
458
  const datasource = "df";
@@ -463,18 +463,18 @@ describe("generateAltairChart", () => {
463
463
  "alt.Chart(df)
464
464
  .mark_bar()
465
465
  .encode(
466
- x=alt.X(field='name\\.field'),
467
- y=alt.Y(field='value\\.data')
466
+ x=alt.X(field='name\\\\.field'),
467
+ y=alt.Y(field='value\\\\.data')
468
468
  )"
469
469
  `);
470
470
  });
471
471
 
472
- it("should escape brackets in field names", () => {
472
+ it("should keep escaped brackets in field names", () => {
473
473
  const spec = createSpec({
474
474
  mark: "bar",
475
475
  encoding: {
476
- x: { field: "data[0]" },
477
- y: { field: "values[key]" },
476
+ x: { field: String.raw`data\[0\]` },
477
+ y: { field: String.raw`values\[key\]` },
478
478
  },
479
479
  });
480
480
  const datasource = "df";
@@ -485,17 +485,17 @@ describe("generateAltairChart", () => {
485
485
  "alt.Chart(df)
486
486
  .mark_bar()
487
487
  .encode(
488
- x=alt.X(field='data\\[0\\]'),
489
- y=alt.Y(field='values\\[key\\]')
488
+ x=alt.X(field='data\\\\[0\\\\]'),
489
+ y=alt.Y(field='values\\\\[key\\\\]')
490
490
  )"
491
491
  `);
492
492
  });
493
493
 
494
- it("should escape colons in field names", () => {
494
+ it("should keep escaped colons in field names", () => {
495
495
  const spec = createSpec({
496
496
  mark: "bar",
497
497
  encoding: {
498
- x: { field: "time:stamp" },
498
+ x: { field: String.raw`time\:stamp` },
499
499
  y: { field: "value" },
500
500
  },
501
501
  });
@@ -507,17 +507,17 @@ describe("generateAltairChart", () => {
507
507
  "alt.Chart(df)
508
508
  .mark_bar()
509
509
  .encode(
510
- x=alt.X(field='time\\:stamp'),
510
+ x=alt.X(field='time\\\\:stamp'),
511
511
  y=alt.Y(field='value')
512
512
  )"
513
513
  `);
514
514
  });
515
515
 
516
- it("should escape multiple special characters in field names", () => {
516
+ it("should keep multiple escaped characters in field names", () => {
517
517
  const spec = createSpec({
518
518
  mark: "bar",
519
519
  encoding: {
520
- x: { field: "data[0].name:value" },
520
+ x: { field: String.raw`data\[0\]\.name\:value` },
521
521
  y: { field: "result" },
522
522
  },
523
523
  });
@@ -529,19 +529,19 @@ describe("generateAltairChart", () => {
529
529
  "alt.Chart(df)
530
530
  .mark_bar()
531
531
  .encode(
532
- x=alt.X(field='data\\[0\\]\\.name\\:value'),
532
+ x=alt.X(field='data\\\\[0\\\\]\\\\.name\\\\:value'),
533
533
  y=alt.Y(field='result')
534
534
  )"
535
535
  `);
536
536
  });
537
537
 
538
- it("should escape special characters in color encoding", () => {
538
+ it("should keep escaped characters in color encoding", () => {
539
539
  const spec = createSpec({
540
540
  mark: "bar",
541
541
  encoding: {
542
542
  x: { field: "category" },
543
543
  y: { field: "value" },
544
- color: { field: "group.name" },
544
+ color: { field: String.raw`group\.name` },
545
545
  },
546
546
  });
547
547
  const datasource = "df";
@@ -554,18 +554,18 @@ describe("generateAltairChart", () => {
554
554
  .encode(
555
555
  x=alt.X(field='category'),
556
556
  y=alt.Y(field='value'),
557
- color=alt.Color(field='group\\.name')
557
+ color=alt.Color(field='group\\\\.name')
558
558
  )"
559
559
  `);
560
560
  });
561
561
 
562
- it("should escape special characters in tooltip", () => {
562
+ it("should keep escaped characters in tooltip", () => {
563
563
  const spec = createSpec({
564
564
  mark: "bar",
565
565
  encoding: {
566
566
  x: { field: "category" },
567
567
  y: { field: "value" },
568
- tooltip: { field: "info.details" },
568
+ tooltip: { field: String.raw`info\.details` },
569
569
  },
570
570
  });
571
571
  const datasource = "df";
@@ -578,19 +578,19 @@ describe("generateAltairChart", () => {
578
578
  .encode(
579
579
  x=alt.X(field='category'),
580
580
  y=alt.Y(field='value'),
581
- tooltip=alt.Tooltip(field='info\\.details')
581
+ tooltip=alt.Tooltip(field='info\\\\.details')
582
582
  )"
583
583
  `);
584
584
  });
585
585
 
586
- it("should escape special characters in facet encodings", () => {
586
+ it("should keep escaped characters in facet encodings", () => {
587
587
  const spec = createSpec({
588
588
  mark: "bar",
589
589
  encoding: {
590
590
  x: { field: "category" },
591
591
  y: { field: "value" },
592
- row: { field: "row.label" },
593
- column: { field: "col[0]" },
592
+ row: { field: String.raw`row\.label` },
593
+ column: { field: String.raw`col\[0\]` },
594
594
  },
595
595
  });
596
596
  const datasource = "df";
@@ -603,9 +603,24 @@ describe("generateAltairChart", () => {
603
603
  .encode(
604
604
  x=alt.X(field='category'),
605
605
  y=alt.Y(field='value'),
606
- row=alt.Row(field='row\\.label'),
607
- column=alt.Column(field='col\\[0\\]')
606
+ row=alt.Row(field='row\\\\.label'),
607
+ column=alt.Column(field='col\\\\[0\\\\]')
608
608
  )"
609
609
  `);
610
610
  });
611
+
612
+ it("should emit column names as Python string literals", () => {
613
+ const field = "a'b\"c{d}\ne\\\u2028";
614
+ const spec = createSpec({
615
+ mark: "bar",
616
+ encoding: { x: { field } },
617
+ title: field,
618
+ });
619
+
620
+ const result = generateAltairChart(spec, "df").toCode();
621
+
622
+ const literal = String.raw`'a\'b"c{d}\ne\\\u2028'`;
623
+ expect(result).toContain(`x=alt.X(field=${literal})`);
624
+ expect(result).toContain(`title=${literal}`);
625
+ });
611
626
  });
@@ -8,7 +8,6 @@ import {
8
8
  Variable,
9
9
  VariableDeclaration,
10
10
  } from "@/utils/python-poet/poet";
11
- import { escapeFieldName } from "./utils";
12
11
 
13
12
  /**
14
13
  * Generates Python code for an Altair chart.
@@ -158,11 +157,8 @@ function makeKwargs<T extends Record<string, any>>(obj: T) {
158
157
 
159
158
  for (const [key, value] of Object.entries(obj)) {
160
159
  if (value !== undefined) {
161
- // Escape special characters in field names
162
- result[key] =
163
- key === "field" && typeof value === "string"
164
- ? new Literal(escapeFieldName(value))
165
- : new Literal(value);
160
+ // Field names in the spec are already escaped for Vega-Lite
161
+ result[key] = new Literal(value);
166
162
  }
167
163
  }
168
164
 
@@ -0,0 +1,153 @@
1
+ /* Copyright 2026 Marimo. All rights reserved. */
2
+
3
+ import { describe, expect, it, vi } from "vitest";
4
+ import {
5
+ getAttachmentMediaType,
6
+ getSupportedAttachmentTypes,
7
+ isSupportedAttachmentType,
8
+ normalizeAttachment,
9
+ } from "../attachments";
10
+
11
+ vi.mock("../model-registry", () => ({
12
+ getKnownModelMaps: () => ({
13
+ modelMap: new Map([
14
+ ["openai/text-only", { input_types: ["text"] }],
15
+ ["ollama/vision", { input_types: ["text", "image"] }],
16
+ ["bedrock/multimodal", { input_types: ["text", "image", "pdf"] }],
17
+ ["azure/unknown", { input_types: [] }],
18
+ ]),
19
+ }),
20
+ }));
21
+
22
+ describe("getSupportedAttachmentTypes", () => {
23
+ it("allows text files for text-only models", () => {
24
+ expect(getSupportedAttachmentTypes("openai/text-only")).toEqual(["text/*"]);
25
+ });
26
+
27
+ it("allows images for vision models on other providers", () => {
28
+ expect(getSupportedAttachmentTypes("ollama/vision")).toEqual([
29
+ ...getSupportedAttachmentTypes("openai/text-only"),
30
+ "image/png",
31
+ "image/jpeg",
32
+ "image/gif",
33
+ "image/webp",
34
+ ]);
35
+ });
36
+
37
+ it("includes PDFs only when the model accepts them", () => {
38
+ expect(getSupportedAttachmentTypes("bedrock/multimodal")).toContain(
39
+ "application/pdf",
40
+ );
41
+ expect(getSupportedAttachmentTypes("ollama/vision")).not.toContain(
42
+ "application/pdf",
43
+ );
44
+ });
45
+
46
+ it.each(["custom/my-model", "openrouter/vendor/model", "azure/unknown"])(
47
+ "allows supported file formats when metadata is unknown: %s",
48
+ (model) => {
49
+ expect(getSupportedAttachmentTypes(model)).toEqual(
50
+ getSupportedAttachmentTypes("bedrock/multimodal"),
51
+ );
52
+ },
53
+ );
54
+ });
55
+
56
+ describe("getAttachmentMediaType", () => {
57
+ it.each([
58
+ "application/toml",
59
+ "application/yaml",
60
+ "application/x-yaml",
61
+ "application/xml",
62
+ "application/vnd.example+json",
63
+ "application/vnd.example+xml",
64
+ "Text/Plain; charset=utf-8",
65
+ ])("normalizes %s", (mediaType) => {
66
+ expect(getAttachmentMediaType(mediaType)).toBe("text/plain");
67
+ });
68
+
69
+ it("does not treat a declared binary file as text based on its filename", () => {
70
+ expect(getAttachmentMediaType("application/pdf")).toBe("application/pdf");
71
+ });
72
+ });
73
+
74
+ describe("normalizeAttachment", () => {
75
+ it.each([
76
+ ["", "README"],
77
+ ["application/octet-stream", "script.unlisted-extension"],
78
+ ["application/javascript", "script.js"],
79
+ ])("recognizes text by contents for %s, %s", async (type, name) => {
80
+ const file = new File(["Hello, 世界!\t\n\f\r"], name, {
81
+ type,
82
+ lastModified: 42,
83
+ });
84
+ const normalized = await normalizeAttachment(file);
85
+ expect({
86
+ name: normalized.name,
87
+ type: normalized.type,
88
+ lastModified: normalized.lastModified,
89
+ text: await normalized.text(),
90
+ }).toEqual({
91
+ name,
92
+ type: "text/plain",
93
+ lastModified: 42,
94
+ text: "Hello, 世界!\t\n\f\r",
95
+ });
96
+ });
97
+
98
+ it.each([
99
+ new Uint8Array([0xff, 0xfe]),
100
+ new Uint8Array([65, 0, 66]),
101
+ new Uint8Array([65, 1, 66]),
102
+ new Uint8Array([65, 8, 66]),
103
+ new Uint8Array([65, 11, 66]),
104
+ new Uint8Array([65, 31, 66]),
105
+ ])("preserves binary data despite a text filename", async (bytes) => {
106
+ const file = new File([bytes], "script.py", {
107
+ type: "application/octet-stream",
108
+ });
109
+ expect(await normalizeAttachment(file)).toBe(file);
110
+ });
111
+
112
+ it.each([
113
+ "image/png",
114
+ "image/svg+xml",
115
+ "application/pdf",
116
+ "audio/wav",
117
+ "video/mp4",
118
+ ])(
119
+ "preserves declared %s files even if their contents are valid UTF-8",
120
+ async (type) => {
121
+ const file = new File(["ASCII payload"], "file.txt", { type });
122
+ expect(await normalizeAttachment(file)).toBe(file);
123
+ },
124
+ );
125
+ });
126
+
127
+ describe("isSupportedAttachmentType", () => {
128
+ it.each([
129
+ ["text/plain", true],
130
+ ["text/markdown", true],
131
+ ["application/json", true],
132
+ ["image/png", false],
133
+ ["application/pdf", false],
134
+ ["application/octet-stream", false],
135
+ ["", false],
136
+ ])("checks %s against text-only inputs", (mediaType, expected) => {
137
+ expect(
138
+ isSupportedAttachmentType(
139
+ getAttachmentMediaType(mediaType),
140
+ getSupportedAttachmentTypes("openai/text-only"),
141
+ ),
142
+ ).toBe(expected);
143
+ });
144
+
145
+ it("rejects unsupported image formats even for vision models", () => {
146
+ expect(
147
+ isSupportedAttachmentType(
148
+ getAttachmentMediaType("image/svg+xml"),
149
+ getSupportedAttachmentTypes("ollama/vision"),
150
+ ),
151
+ ).toBe(false);
152
+ });
153
+ });