Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

22l: the chat takes audio (MP3, M4A/AAC, WAV, OGG/Opus, FLAC) up to 100 MB (#712)

Oleksandr Ivanchenkoc14fe6b8aa6a
diff --git a/frontend/src/attachments.ts b/frontend/src/attachments.ts
index 9baf7f6a..d15831bd 100644
--- a/frontend/src/attachments.ts
+++ b/frontend/src/attachments.ts
@@ -5,12 +5,14 @@ import { PointMeta, PointPick, parsePointMeta, pointMetaOf } from './point';
export const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;
/** Videos (mp4, mov, webm) may be bigger; the server enforces the same caps by the file's bytes. */
export const MAX_VIDEO_BYTES = 100 * 1024 * 1024;
+/** Audio (mp3, m4a, aac, wav, ogg, opus, flac) may be as big as a video (22l); the server checks the bytes. */
+export const MAX_AUDIO_BYTES = MAX_VIDEO_BYTES;
/** Whole megabytes, as the limits are shown ("20 MB"). */
const wholeMb = (bytes: number) => `${Math.round(bytes / (1024 * 1024))} MB`;
/** The drop card's limits line, built from the caps so it can't drift from them (#478 L2). */
-export const LIMITS_LINE = `Up to ${wholeMb(MAX_ATTACHMENT_BYTES)} each · videos ${wholeMb(MAX_VIDEO_BYTES)}`;
+export const LIMITS_LINE = `Up to ${wholeMb(MAX_ATTACHMENT_BYTES)} each · videos and audio ${wholeMb(MAX_VIDEO_BYTES)}`;
/** The paperclip's tooltip, from the same caps. */
-export const ATTACH_TITLE = `Attach files (or drop / paste them here). Max ${wholeMb(MAX_ATTACHMENT_BYTES)} each, videos ${wholeMb(MAX_VIDEO_BYTES)}.`;
+export const ATTACH_TITLE = `Attach files (or drop / paste them here). Max ${wholeMb(MAX_ATTACHMENT_BYTES)} each, videos and audio ${wholeMb(MAX_VIDEO_BYTES)}.`;
export const MAX_ATTACHMENTS = 10;
/** What a message's `meta.attachments` holds. */
@@ -42,6 +44,9 @@ export const isInlineImage = (mime: string) => INLINE_IMAGES.has(mime.toLowerCas
/** Sent videos the chat tries to play (P2); a browser that can't falls back to the file card. */
export const isVideo = (mime: string | undefined) => VIDEO_MIMES.has((mime || '').toLowerCase().split(';')[0].trim());
+/** Audio the chat takes (22l). It shows as a file tile and downloads: no player. */
+export const isAudio = (mime: string | undefined) => AUDIO_MIMES.has((mime || '').toLowerCase().split(';')[0].trim());
+
export const attachmentUrl = (id: string, download = false) =>
`/api/attachments/${encodeURIComponent(id)}/content${download ? '?download=1' : ''}`;
@@ -60,6 +65,12 @@ export function fileKind(mime: string, name: string): string {
if (m === 'video/quicktime') return 'MOV';
if (m === 'video/mp4') return 'MP4';
if (m === 'video/webm') return 'WebM';
+ if (m === 'audio/mpeg' || m === 'audio/mp3') return 'MP3';
+ if (m === 'audio/mp4' || m === 'audio/x-m4a') return /\.m4b$/i.test(name) ? 'M4B' : 'M4A';
+ if (m === 'audio/aac') return 'AAC';
+ if (m === 'audio/wav' || m === 'audio/x-wav' || m === 'audio/wave') return 'WAV';
+ if (m === 'audio/ogg' || m === 'audio/opus') return /\.opus$/i.test(name) ? 'Opus' : 'OGG';
+ if (m === 'audio/flac' || m === 'audio/x-flac') return 'FLAC';
if (m === 'application/json') return 'JSON';
if (m === 'text/csv') return 'CSV';
if (m === 'text/markdown') return 'Markdown';
@@ -92,6 +103,11 @@ const IMAGE_MIMES = new Set(['image/png', 'image/jpeg', 'image/jpg', 'image/gif'
const VIDEO_MIMES = new Set(['video/mp4', 'video/quicktime', 'video/webm']);
const IMAGE_EXTS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp']);
const VIDEO_EXTS = new Set(['mp4', 'm4v', 'mov', 'webm']);
+/** Audio the server takes by its bytes (22l): MP3, M4A/M4B/AAC, WAV, OGG/Opus, FLAC. AIFF, WMA and MIDI aren't. */
+const AUDIO_MIMES = new Set(
+ 'audio/mpeg audio/mp3 audio/mp4 audio/x-m4a audio/aac audio/wav audio/x-wav audio/wave audio/ogg audio/opus audio/flac audio/x-flac'.split(' '),
+);
+const AUDIO_EXTS = new Set(['mp3', 'm4a', 'm4b', 'aac', 'wav', 'ogg', 'oga', 'opus', 'flac']);
/** Text and code: the server keeps these when the bytes are UTF-8. */
const TEXT_EXTS = new Set(
(
@@ -108,7 +124,7 @@ const TEXT_EXTS = new Set(
const BINARY_EXTS = new Set(
(
'zip 7z rar gz tgz bz2 xz zst tar iso dmg pkg exe msi dll so dylib apk ipa jar class wasm bin ' +
- 'heic heif avif tif tiff bmp ico psd mp3 wav m4a aac flac ogg opus aiff mkv avi wmv flv mpg mpeg 3gp ' +
+ 'heic heif avif tif tiff bmp ico psd aiff aif wma mid midi mkv avi wmv flv mpg mpeg 3gp ' +
'doc docx xls xlsx ppt pptx odt ods odp pages numbers sqlite woff woff2 ttf otf eot'
).split(' '),
);
@@ -125,7 +141,7 @@ const isBinaryMime = (mime: string) => BINARY_MIMES.has(mime) || BINARY_MIME_PRE
const extOf = (name: string) => /\.([a-z0-9]{1,12})$/i.exec(name)?.[1]?.toLowerCase() ?? '';
-export type AttachKind = 'image' | 'pdf' | 'text' | 'video';
+export type AttachKind = 'image' | 'pdf' | 'text' | 'video' | 'audio';
/**
* What kind of file this is, or null when kwant surely can't take it. Extension first: browsers call
@@ -138,10 +154,12 @@ export function attachKind(f: { name: string; type?: string }): AttachKind | nul
if (TEXT_EXTS.has(ext)) return 'text';
if (IMAGE_EXTS.has(ext)) return 'image';
if (VIDEO_EXTS.has(ext)) return 'video';
+ if (AUDIO_EXTS.has(ext)) return 'audio';
if (ext === 'pdf') return 'pdf';
if (BINARY_EXTS.has(ext)) return null;
if (IMAGE_MIMES.has(mime)) return 'image';
if (VIDEO_MIMES.has(mime)) return 'video';
+ if (AUDIO_MIMES.has(mime)) return 'audio';
if (mime === 'application/pdf') return 'pdf';
if (mime.startsWith('text/') || mime === 'application/json') return 'text';
if (isBinaryMime(mime)) return null;
@@ -166,7 +184,7 @@ const PREVIEW_REFUSED_PREFIXES = ['audio/', 'font/', 'application/vnd.ms-', 'app
*/
export function previewRefusesMime(type: string): boolean {
const mime = (type || '').toLowerCase().split(';')[0].trim();
- if (!mime) return false;
+ if (!mime || AUDIO_MIMES.has(mime)) return false;
return BINARY_MIMES.has(mime) || PREVIEW_REFUSED_EXACT.has(mime) || PREVIEW_REFUSED_PREFIXES.some((p) => mime.startsWith(p));
}
@@ -177,9 +195,9 @@ export function isArchiveMime(type: string): boolean {
}
/** The one line shown when a file's type can't be attached. */
-export const SUPPORTED_TYPES_TEXT = 'Images, videos (MP4, MOV, WebM), PDFs and text or code files work.';
+export const SUPPORTED_TYPES_TEXT = 'Images, videos (MP4, MOV, WebM), audio (MP3, M4A, WAV, OGG, FLAC), PDFs and text or code files work.';
-export const capFor = (kind: AttachKind | null) => (kind === 'video' ? MAX_VIDEO_BYTES : MAX_ATTACHMENT_BYTES);
+export const capFor = (kind: AttachKind | null) => (kind === 'video' ? MAX_VIDEO_BYTES : kind === 'audio' ? MAX_AUDIO_BYTES : MAX_ATTACHMENT_BYTES);
/** Checked before uploading, so an unsupported or too-big file never leaves the browser. */
export function preflightFile(f: { name: string; size: number; type?: string }): string | null {
@@ -190,7 +208,9 @@ export function preflightFile(f: { name: string; size: number; type?: string }):
const cap = capFor(kind);
if (f.size > cap) {
const mb = (f.size / (1024 * 1024)).toFixed(1);
- return kind === 'video' ? `${label} is too big (${mb} MB). Videos can be up to 100 MB.` : `${label} is too big (${mb} MB). Max 20 MB (videos 100 MB).`;
+ if (kind === 'video') return `${label} is too big (${mb} MB). Videos can be up to ${wholeMb(MAX_VIDEO_BYTES)}.`;
+ if (kind === 'audio') return `${label} is too big (${mb} MB). Audio files can be up to ${wholeMb(MAX_AUDIO_BYTES)}.`;
+ return `${label} is too big (${mb} MB). Max ${wholeMb(MAX_ATTACHMENT_BYTES)} (videos and audio ${wholeMb(MAX_VIDEO_BYTES)}).`;
}
return null;
}
@@ -199,7 +219,7 @@ export function preflightFile(f: { name: string; size: number; type?: string }):
export function uploadErrorText(status: number, serverMessage?: string): string {
switch (status) {
case 413:
- return serverMessage || 'Too big. Max 20 MB, videos 100 MB.';
+ return serverMessage || 'Too big. Max 20 MB, videos and audio 100 MB.';
case 415:
return `That file type isn't supported. ${SUPPORTED_TYPES_TEXT}`;
case 400:
diff --git a/frontend/src/components/BrowserPopups.tsx b/frontend/src/components/BrowserPopups.tsx
index 60894843..f5a506e2 100644
--- a/frontend/src/components/BrowserPopups.tsx
+++ b/frontend/src/components/BrowserPopups.tsx
@@ -488,7 +488,7 @@ export function FileChooserModal({
{!error && phase === 'picking' && (
<p className="mt-1 text-[13px] text-zinc-400">
From this device<span className="[@media(pointer:coarse)]:hidden">, or drop it here</span>.{' '}
- {kind === 'video' ? 'Up to 100 MB.' : 'Up to 20 MB (videos 100 MB).'}
+ {kind === 'video' ? 'Up to 100 MB.' : 'Up to 20 MB (videos and audio 100 MB).'}
</p>
)}
diff --git a/frontend/src/dragPreview.ts b/frontend/src/dragPreview.ts
index 140aeb2e..7374ba6e 100644
--- a/frontend/src/dragPreview.ts
+++ b/frontend/src/dragPreview.ts
@@ -1,7 +1,7 @@
// 0.8.0 drag and drop into chats (Mira's design, release-080/drag-drop/design.md). What a file drag
// carries, read while it is still in the air; the words the drop card shows; what a drop brought; and
// the window-level watch that knows a file drag is over the window at all.
-import { MAX_ATTACHMENTS, isArchiveMime, previewRefusesMime } from './attachments';
+import { MAX_ATTACHMENTS, isArchiveMime, isAudio, previewRefusesMime } from './attachments';
import { teamNamed } from './botHome';
/** One dragged item as the browser shows it before the drop: its kind and MIME type, never its name. */
@@ -10,7 +10,7 @@ export interface DragItemLike {
type: string;
}
-export type DragKind = 'image' | 'video' | 'pdf' | 'text' | 'file' | 'refused';
+export type DragKind = 'image' | 'video' | 'audio' | 'pdf' | 'text' | 'file' | 'refused';
const IMAGE = new Set(['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/webp']);
const VIDEO = new Set(['video/mp4', 'video/quicktime', 'video/webm']);
@@ -27,6 +27,7 @@ export function dragKind(type: string): DragKind {
if (previewRefusesMime(mime)) return 'refused';
if (IMAGE.has(mime)) return 'image';
if (VIDEO.has(mime)) return 'video';
+ if (isAudio(mime)) return 'audio';
if (mime === 'application/pdf') return 'pdf';
if (mime.startsWith('text/') || mime === 'application/json') return 'text';
return 'file';
@@ -67,7 +68,7 @@ export const dragItemsOf = (items: ArrayLike<DragItemLike> | null | undefined):
export function previewDrag(items: ArrayLike<DragItemLike> | null | undefined, inTray = 0): DragPreview {
const list = dragItemsOf(items);
const slotsLeft = Math.max(0, MAX_ATTACHMENTS - inTray);
- const kinds = { image: 0, video: 0, pdf: 0, text: 0, file: 0 };
+ const kinds = { image: 0, video: 0, audio: 0, pdf: 0, text: 0, file: 0 };
const refused: string[] = [];
let go = 0;
let overBy = 0;
@@ -87,6 +88,7 @@ const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? o
const KIND_WORDS: Record<Exclude<DragKind, 'refused'>, [string, string]> = {
image: ['image', 'images'],
video: ['video', 'videos'],
+ audio: ['audio file', 'audio files'],
pdf: ['PDF', 'PDFs'],
text: ['text file', 'text files'],
file: ['file', 'files'],
@@ -99,7 +101,7 @@ export interface KindPart {
/** The kinds for the what line: at most 3, biggest first; the rest fold into "{n} other". */
export function kindParts(p: DragPreview): KindPart[] {
- const order: Array<Exclude<DragKind, 'refused'>> = ['image', 'video', 'pdf', 'text', 'file'];
+ const order: Array<Exclude<DragKind, 'refused'>> = ['image', 'video', 'audio', 'pdf', 'text', 'file'];
const groups = order.filter((k) => p.kinds[k] > 0).sort((a, b) => p.kinds[b] - p.kinds[a]);
const shown = groups.slice(0, 3).map((k) => ({ kind: k, label: plural(p.kinds[k], ...KIND_WORDS[k]) }));
const rest = groups.slice(3).reduce((n, k) => n + p.kinds[k], 0);
@@ -144,7 +146,7 @@ export function dropHeading(r: DropRecipient, count: number | null, armed = fals
/** The recipient inside a sentence: "Frontend", "General", "the Kitchen team", "the Marketing_Team". */
const nameIn = (r: DropRecipient) => (r.kind === 'team' ? `the ${teamNamed(r.name)}` : r.name);
-const WORKS = 'Images, videos, PDFs and text or code files work.';
+const WORKS = 'Images, videos, audio, PDFs and text or code files work.';
/** How a refused MIME is named when all refused files share it. */
function refusedWords(mime: string): { one: string; many: string; group: string } | null {
diff --git a/frontend/tests/attachments.test.mjs b/frontend/tests/attachments.test.mjs
index 6d80fca4..17eb1848 100644
--- a/frontend/tests/attachments.test.mjs
+++ b/frontend/tests/attachments.test.mjs
@@ -22,7 +22,7 @@ test('the 20 MB limit and empty files are caught before upload', () => {
});
test('server refusals read as plain language', () => {
- assert.match(a.uploadErrorText(413), /Max 20 MB, videos 100 MB/);
+ assert.match(a.uploadErrorText(413), /Max 20 MB, videos and audio 100 MB/);
assert.match(a.uploadErrorText(415), /isn't supported/);
assert.equal(a.uploadErrorText(400, 'bad name'), 'bad name');
assert.match(a.uploadErrorText(0), /interrupted/);
@@ -132,15 +132,15 @@ test('P1: supported types pass, everything else is refused before upload', () =>
assert.match(a.preflightFile({ name: 'main.tf', type: '', size: 21 * MB }), /Max 20 MB/);
const refused = [
['a.zip', 'application/zip'], ['setup.exe', 'application/x-msdownload'], ['r.docx', ''], ['photo.heic', 'image/heic'],
- ['song.mp3', 'audio/mpeg'], ['film.mkv', 'video/x-matroska'], ['clip.avi', 'video/x-msvideo'], ['x.bin', 'application/octet-stream'],
+ ['song.aiff', 'audio/aiff'], ['film.mkv', 'video/x-matroska'], ['clip.avi', 'video/x-msvideo'], ['x.bin', 'application/octet-stream'],
['noext', 'application/zip'],
// a binary mime on an unknown extension, and a known binary extension with no mime
- ['data.foo', 'application/zip'], ['installer.dmg', ''], ['tune.xyz', 'audio/ogg'], ['deck.abc', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'],
+ ['data.foo', 'application/zip'], ['installer.dmg', ''], ['tune.xyz', 'audio/x-aiff'], ['beat.mid', ''], ['old.wma', 'audio/x-ms-wma'], ['deck.abc', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'],
];
for (const [name, type] of refused) {
const why = a.preflightFile({ name, type, size: 1000 });
assert.ok(why, `${name} should be refused`);
- assert.match(why, /can't be attached\. Images, videos \(MP4, MOV, WebM\), PDFs and text or code files work\./);
+ assert.match(why, /can't be attached\. Images, videos \(MP4, MOV, WebM\), audio \(MP3, M4A, WAV, OGG, FLAC\), PDFs and text or code files work\./);
}
assert.equal(a.attachKind({ name: 'main.ts', type: 'video/mp2t' }), 'text');
assert.equal(a.attachKind({ name: 'v.mov', type: 'video/quicktime' }), 'video');
@@ -151,7 +151,7 @@ test('P1: supported types pass, everything else is refused before upload', () =>
test('P1: videos may be 100 MB, everything else 20 MB', () => {
assert.equal(a.preflightFile({ name: 'v.mp4', type: 'video/mp4', size: 100 * MB }), null);
assert.match(a.preflightFile({ name: 'v.mp4', type: 'video/mp4', size: 120 * MB }), /v\.mp4 is too big \(120\.0 MB\)\. Videos can be up to 100 MB\./);
- assert.match(a.preflightFile({ name: 'p.png', type: 'image/png', size: 21 * MB }), /Max 20 MB \(videos 100 MB\)/);
+ assert.match(a.preflightFile({ name: 'p.png', type: 'image/png', size: 21 * MB }), /Max 20 MB \(videos and audio 100 MB\)/);
assert.match(a.preflightFile({ name: 'v.webm', type: 'video/webm', size: 0 }), /empty/);
// the type is checked first: a huge zip says the type, not the size
assert.match(a.preflightFile({ name: 'big.zip', type: 'application/zip', size: 500 * MB }), /can't be attached/);
@@ -317,3 +317,30 @@ test('P3: cancelling while it waits to retry stops it', async () => {
fake.restore();
}
});
+
+test('22l: audio (MP3, M4A, AAC, WAV, OGG/Opus, FLAC) is taken up to 100 MB, like video', () => {
+ const ok = [
+ ['song.mp3', 'audio/mpeg'], ['song.mp3', ''], ['memo.m4a', 'audio/x-m4a'], ['book.m4b', ''], ['raw.aac', 'audio/aac'],
+ ['take.wav', 'audio/wav'], ['voice.opus', 'audio/opus'], ['voice.ogg', 'audio/ogg'], ['old.oga', ''], ['album.flac', 'audio/flac'],
+ // the mime alone, with no or an odd extension
+ ['recording', 'audio/mpeg'], ['clip.xyz', 'audio/wav'],
+ ];
+ for (const [name, type] of ok) {
+ assert.equal(a.attachKind({ name, type }), 'audio', `${name} (${type || 'no type'})`);
+ assert.equal(a.preflightFile({ name, type, size: 60 * MB }), null, `${name}: a 60 MB episode goes`);
+ }
+ assert.equal(a.capFor('audio'), 100 * MB);
+ assert.equal(a.MAX_AUDIO_BYTES, a.MAX_VIDEO_BYTES);
+ assert.equal(a.preflightFile({ name: 'ep.mp3', type: 'audio/mpeg', size: 100 * MB }), null);
+ assert.equal(a.preflightFile({ name: 'ep.mp3', type: 'audio/mpeg', size: 120 * MB }), 'ep.mp3 is too big (120.0 MB). Audio files can be up to 100 MB.');
+ assert.match(a.preflightFile({ name: 'ep.mp3', type: 'audio/mpeg', size: 0 }), /empty/);
+ // The browser only screens: a renamed binary goes up and the server refuses it by its bytes
+ assert.equal(a.uploadErrorText(415), `That file type isn't supported. ${a.SUPPORTED_TYPES_TEXT}`);
+ assert.ok(a.isAudio('audio/mpeg; codecs=mp3') && !a.isAudio('audio/x-aiff') && !a.isAudio('video/mp4'));
+ assert.equal(a.previewRefusesMime('audio/mpeg'), false);
+ assert.equal(a.previewRefusesMime('audio/x-aiff'), true);
+ const kinds = [['audio/mpeg', 'ep.mp3', 'MP3'], ['audio/mp4', 'memo.m4a', 'M4A'], ['audio/mp4', 'book.m4b', 'M4B'], ['audio/aac', 'r.aac', 'AAC'],
+ ['audio/wav', 't.wav', 'WAV'], ['audio/ogg', 'v.ogg', 'OGG'], ['audio/ogg', 'v.opus', 'Opus'], ['audio/flac', 'a.flac', 'FLAC']];
+ for (const [mime, name, label] of kinds) assert.equal(a.fileKind(mime, name), label, `${mime} ${name}`);
+ assert.equal(a.LIMITS_LINE, 'Up to 20 MB each · videos and audio 100 MB');
+});
diff --git a/frontend/tests/dragDropPane.test.mjs b/frontend/tests/dragDropPane.test.mjs
index 6da215d2..80519132 100644
--- a/frontend/tests/dragDropPane.test.mjs
+++ b/frontend/tests/dragDropPane.test.mjs
@@ -330,7 +330,7 @@ test('some won\'t go: the won\'t-go rows, and a dropped folder is left out with
const twelve = [...Array.from({ length: 11 }, (_, i) => mkFile(`p${i}.png`)), mkFile('a.zip', 'application/zip')];
await fire(list, 'dragenter', dataTransfer(twelve));
const rows = [...v.host.querySelectorAll('[data-drop-warning] > div')].map((d) => d.textContent);
- assert.deepEqual(rows, ["1 more won't fit: 10 files per message.", "1 ZIP can't go. Images, videos, PDFs and text or code files work."]);
+ assert.deepEqual(rows, ["1 more won't fit: 10 files per message.", "1 ZIP can't go. Images, videos, audio, PDFs and text or code files work."]);
assert.equal(v.host.querySelector('[data-drop-summary]')?.textContent, '10 files · 10 images');
await endDrag();
@@ -564,9 +564,9 @@ test('the limits line is built from the caps, in the same words (#478 L2)', asyn
const v = ui.mount(props());
try {
await fire(parts(v.host).list, 'dragenter', dataTransfer([mkFile('a.png')]));
- assert.equal(v.host.querySelector('[data-drop-limits]')?.textContent, 'Up to 20 MB each · videos 100 MB');
+ assert.equal(v.host.querySelector('[data-drop-limits]')?.textContent, 'Up to 20 MB each · videos and audio 100 MB');
const clip = v.host.querySelector('button[aria-label="Attach files"]');
- assert.equal(clip.getAttribute('title'), 'Attach files (or drop / paste them here). Max 20 MB each, videos 100 MB.');
+ assert.equal(clip.getAttribute('title'), 'Attach files (or drop / paste them here). Max 20 MB each, videos and audio 100 MB.');
} finally {
v.unmount();
await endDrag();
diff --git a/frontend/tests/dragPreview.test.mjs b/frontend/tests/dragPreview.test.mjs
index 169ce570..ab9f5aa3 100644
--- a/frontend/tests/dragPreview.test.mjs
+++ b/frontend/tests/dragPreview.test.mjs
@@ -30,7 +30,7 @@ test('one image: one file goes, the card gives it to the bot', () => {
test('three mixed files: counted by kind; a dragged link alongside is not a file; no items hides the count', () => {
const p = d.previewDrag([file('image/jpeg'), file('image/webp'), file('application/pdf'), str('text/uri-list')]);
assert.equal(p.count, 3);
- assert.deepEqual(p.kinds, { image: 2, video: 0, pdf: 1, text: 0, file: 0 });
+ assert.deepEqual(p.kinds, { image: 2, video: 0, audio: 0, pdf: 1, text: 0, file: 0 });
assert.equal(d.whatLine(p), '3 files · 2 images, 1 PDF');
const q = d.previewDrag([file('video/mp4'), file('text/markdown'), file('application/json'), file('')]);
assert.deepEqual([q.kinds.video, q.kinds.text, q.kinds.file], [1, 2, 1]);
@@ -83,9 +83,9 @@ test('some won\'t go: over the limit, with the tray already holding files, and r
assert.match(one.wont[0], /1 is already in\.$/);
const mixed = card([file('image/png'), file('application/zip'), file('application/zip')]);
assert.equal(mixed.state, 'over');
- assert.deepEqual(mixed.wont, ["2 ZIPs can't go. Images, videos, PDFs and text or code files work."]);
- const odd = card([file('image/png'), file('application/zip'), file('audio/mpeg')]);
- assert.equal(odd.wont[0], "2 files can't go. Images, videos, PDFs and text or code files work.");
+ assert.deepEqual(mixed.wont, ["2 ZIPs can't go. Images, videos, audio, PDFs and text or code files work."]);
+ const odd = card([file('image/png'), file('application/zip'), file('audio/x-aiff')]);
+ assert.equal(odd.wont[0], "2 files can't go. Images, videos, audio, PDFs and text or code files work.");
// A refused file still takes a slot, as addFiles does.
const slot = d.previewDrag([file('application/zip'), file('image/png')], 9);
assert.deepEqual({ go: slot.go, overBy: slot.overBy, refused: slot.refused.length }, { go: 0, overBy: 1, refused: 1 });
@@ -97,12 +97,12 @@ test('all refused: the neutral card, in the design\'s order', () => {
assert.equal(zip.count, null);
assert.equal(d.headingText(zip.heading), "This can't go to Frontend");
assert.equal(zip.refusal.line1, "ZIP files can't be attached.");
- assert.equal(zip.refusal.line2, 'Images, videos, PDFs and text or code files work. Unzip it and drop the files inside.');
+ assert.equal(zip.refusal.line2, 'Images, videos, audio, PDFs and text or code files work. Unzip it and drop the files inside.');
assert.equal(zip.announce, "This can't go to Frontend. ZIP files can't be attached.");
- const two = d.dropCard({ preview: d.previewDrag([file('audio/mpeg'), file('application/msword')]), recipient: team });
+ const two = d.dropCard({ preview: d.previewDrag([file('audio/x-aiff'), file('application/msword')]), recipient: team });
assert.equal(d.headingText(two.heading), "These can't go to the Kitchen team");
assert.equal(two.refusal.line1, "These files can't be attached.");
- assert.equal(two.refusal.line2, 'Images, videos, PDFs and text or code files work.');
+ assert.equal(two.refusal.line2, 'Images, videos, audio, PDFs and text or code files work.');
const office = card([file('application/vnd.openxmlformats-officedocument.wordprocessingml.document')]);
assert.equal(office.refusal.line1, "Office files can't be attached.");
// Idea mode first, then a disabled composer, then a full tray.
@@ -116,7 +116,7 @@ test('all refused: the neutral card, in the design\'s order', () => {
});
test('the refusal list before the drop matches what the tray refuses after it, and never refuses .ts or SVG', () => {
- const refused = ['application/zip', 'application/x-zip-compressed', 'application/x-7z-compressed', 'audio/mpeg', 'audio/wav', 'font/woff2', 'image/heic', 'image/heif', 'image/avif', 'image/tiff', 'image/bmp',
+ const refused = ['application/zip', 'application/x-zip-compressed', 'application/x-7z-compressed', 'audio/x-aiff', 'audio/midi', 'audio/x-ms-wma', 'font/woff2', 'image/heic', 'image/heif', 'image/avif', 'image/tiff', 'image/bmp',
'image/vnd.adobe.photoshop', 'video/x-matroska', 'video/x-msvideo', 'video/mpeg', 'application/msword', 'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.oasis.opendocument.text'];
for (const t of refused) {
@@ -400,3 +400,16 @@ test('the phone\'s Settings page is not a dialog that keeps the pill away; other
assert.equal(d.modalOpen(doc({ modal: true })), true);
assert.equal(d.modalOpen(doc({ role: 'alertdialog' })), true);
});
+
+test('22l: audio the server takes is never refused before the drop, and counts as audio', () => {
+ for (const t of ['audio/mpeg', 'audio/mp3', 'audio/mp4', 'audio/x-m4a', 'audio/aac', 'audio/wav', 'audio/x-wav', 'audio/wave', 'audio/ogg', 'audio/opus', 'audio/flac', 'audio/x-flac']) {
+ assert.equal(d.previewRefusesMime(t), false, t);
+ assert.equal(d.dragKind(t), 'audio', t);
+ }
+ const p = d.previewDrag([file('audio/mpeg'), file('audio/mpeg'), file('image/png')]);
+ assert.deepEqual({ go: p.go, audio: p.kinds.audio, refused: p.refused.length }, { go: 3, audio: 2, refused: 0 });
+ assert.equal(d.whatLine(p), '3 files · 2 audio files, 1 image');
+ // Audio kwant doesn't take keeps its words
+ const aiff = d.dropCard({ preview: d.previewDrag([file('audio/x-aiff')]), recipient: team });
+ assert.equal(aiff.refusal.line1, "Audio files can't be attached.");
+});
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
index 781c51fc..c75aa889 100644
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@ -492,12 +492,12 @@ pub const BROWSER_SPEED: &str = "\n[Browser speed]\n\
/// the chat, and the bot answers the page's picker with it. A container bot once told the person
/// "my browser can't download or attach files" and handed them the whole page job.
/// The chat takes only some kinds and sizes (see [`crate::server::attachments`]), so the line says
-/// which: an MP3 or a 500 MB file would be refused at the person's end.
+/// which: a Word file or a 500 MB file would be refused at the person's end. Audio counts since 22l.
pub const ASK_FOR_THE_FILE: &str = "If you can't get a file yourself (a download was refused or stopped, or only the person \
has it), ask the person to drop it into this chat, then click the page's upload button and answer its picker with \
browser_upload (the upload above) using that attachment's id. Never tell them you can't attach files, and never hand \
- them the page's upload: all they do is hand over the file. The chat takes images, videos, PDFs and text files, up to \
- 20 MB (videos up to 100 MB); for any other file, say in your Blocked: line which file the page needs and that the chat \
+ them the page's upload: all they do is hand over the file. The chat takes images, videos, audio, PDFs and text files, \
+ up to 20 MB (videos and audio up to 100 MB); for any other file, say in your Blocked: line which file the page needs and that the chat \
can't take it.";
/// Every turn that can read something: look before proposing, retry before giving up, check
@@ -1423,19 +1423,23 @@ pub(crate) mod tests {
assert!(ASK_FOR_THE_FILE.contains(part), "{part}");
}
// The kinds and sizes it names are the ones the chat really takes
- use crate::server::attachments::{MAX_ATTACHMENT_BYTES, MAX_VIDEO_BYTES};
+ use crate::server::attachments::{MAX_ATTACHMENT_BYTES, MAX_AUDIO_BYTES, MAX_VIDEO_BYTES};
let mb = |b: u64| format!("{} MB", b / (1024 * 1024));
+ assert_eq!(MAX_AUDIO_BYTES, MAX_VIDEO_BYTES, "the line names one cap for both");
assert!(ASK_FOR_THE_FILE.contains(&format!("up to {}", mb(MAX_ATTACHMENT_BYTES))), "{ASK_FOR_THE_FILE}");
- assert!(ASK_FOR_THE_FILE.contains(&format!("videos up to {}", mb(MAX_VIDEO_BYTES))), "{ASK_FOR_THE_FILE}");
- let kinds: [(&str, &[u8], bool); 3] = [
+ assert!(ASK_FOR_THE_FILE.contains(&format!("videos and audio up to {}", mb(MAX_AUDIO_BYTES))), "{ASK_FOR_THE_FILE}");
+ let kinds: [(&str, &[u8], bool); 5] = [
("a.png", b"\x89PNG\r\n\x1a\n\0\0\0\0\0\0\0\0", true),
("a.pdf", b"%PDF-1.7\n0000000", true),
- ("ep.mp3", b"ID3\x04\0\0\0\0\0\x23TSSE\0\0\0", false),
+ // 22l: the episode MP3 Oleks hit is taken now; a Word file still isn't
+ ("ep.mp3", b"ID3\x04\0\0\0\0\0\x23TSSE\0\0\0", true),
+ ("ep.mp3", b"MZ\x90\0\x03\0\0\0\x04\0\0\0\xff\xff\0\0", false),
+ ("cv.docx", b"PK\x03\x04\x14\0\x06\0\x08\0\0\0!\0\0\0", false),
];
for (name, head, takes) in kinds {
assert_eq!(crate::server::attachments::sniff(head, false, name).is_some(), takes, "{name}");
}
- assert!(ASK_FOR_THE_FILE.contains("images, videos, PDFs and text files"));
+ assert!(ASK_FOR_THE_FILE.contains("images, videos, audio, PDFs and text files"));
assert!(ASK_FOR_THE_FILE.contains("say in your Blocked: line which file the page needs and that the chat can't take it"));
}
diff --git a/src/sandbox/browser_downloads.rs b/src/sandbox/browser_downloads.rs
index 90e40291..cb43a8d9 100644
--- a/src/sandbox/browser_downloads.rs
+++ b/src/sandbox/browser_downloads.rs
@@ -1197,6 +1197,7 @@ mod tests {
// takes a file that big.
const _: () = assert!(
crate::server::attachments::MAX_VIDEO_BYTES < CONTAINER_MAX_DOWNLOAD_BYTES
+ && crate::server::attachments::MAX_AUDIO_BYTES < CONTAINER_MAX_DOWNLOAD_BYTES
&& crate::server::attachments::MAX_ATTACHMENT_BYTES < CONTAINER_MAX_DOWNLOAD_BYTES
&& REMOTE_UPLOAD_CAP_BYTES < CONTAINER_MAX_DOWNLOAD_BYTES
);
diff --git a/src/server/attachments.rs b/src/server/attachments.rs
index ce191c04..f8a2a417 100644
--- a/src/server/attachments.rs
+++ b/src/server/attachments.rs
@@ -7,9 +7,11 @@
//! served only through the auth guard with `nosniff`, a sandbox CSP and (except raster images and
//! videos) `Content-Disposition: attachment`.
//!
-//! Videos (MP4, MOV, WebM by their bytes) may be up to 100 MB; everything else up to 20 MB. A
-//! file the bytes already rule out is refused after its first 16 bytes, not after the last one
-//! (video-drop-073). `read_attachment` looks inside videos with ffmpeg ([`super::video`]).
+//! Videos (MP4, MOV, WebM by their bytes) and audio (MP3, M4A/AAC, WAV, OGG/Opus, FLAC by their
+//! bytes, 22l) may be up to 100 MB; everything else up to 20 MB. A file the bytes already rule out
+//! is refused after its first 16 bytes, not after the last one (video-drop-073). `read_attachment`
+//! looks inside videos with ffmpeg ([`super::video`]); audio reaches the bot as a file, by its
+//! path, like any other non-text file.
use super::continuity::SelfScope;
use super::AppState;
@@ -32,10 +34,12 @@ use std::path::{Path as FsPath, PathBuf};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tower::ServiceExt;
-/// Largest file a user can upload or an agent can share, unless it is a video.
+/// Largest file a user can upload or an agent can share, unless it is a video or audio.
pub const MAX_ATTACHMENT_BYTES: u64 = 20 * 1024 * 1024;
/// Largest video (MP4, MOV, WebM by its bytes).
pub const MAX_VIDEO_BYTES: u64 = 100 * 1024 * 1024;
+/// Largest audio file (MP3, M4A/AAC, WAV, OGG/Opus, FLAC by its bytes): the same as a video.
+pub const MAX_AUDIO_BYTES: u64 = MAX_VIDEO_BYTES;
/// Bytes of a file's start kept for sniffing; the type is known (or ruled out) once they are in.
const HEAD_BYTES: usize = 16;
/// After an early 413/415 the rest of the body is read and dropped, so the browser gets the
@@ -66,6 +70,14 @@ pub fn is_video_mime(mime: &str) -> bool {
INLINE_VIDEO_TYPES.contains(&mime)
}
+/// Audio the chat takes (22l), each proven by its bytes in [`sniff_magic`]. Served as a download,
+/// never inline, and never put into a model's input: a bot gets it as a file.
+pub(crate) const AUDIO_TYPES: [&str; 6] = ["audio/mpeg", "audio/mp4", "audio/aac", "audio/wav", "audio/ogg", "audio/flac"];
+
+pub fn is_audio_mime(mime: &str) -> bool {
+ AUDIO_TYPES.contains(&mime)
+}
+
pub fn root(state: &AppState) -> PathBuf {
state.config.data_dir.join("attachments")
}
@@ -93,6 +105,8 @@ pub fn clean_name(raw: &str) -> String {
/// ISO-BMFF major brands that are video (MP4 and its relatives). Other `ftyp` files (HEIC/AVIF
/// photos, M4A audio, camera raw) are not videos a browser plays, so they aren't taken as one.
+/// M4A/M4B audio is taken as audio ([`audio_brand`]); an audio-only file whose major brand is a
+/// video one (`mp42`, `isom`) stays a video/mp4, which a `<video>` plays as sound.
fn video_brand(brand: &[u8]) -> Option<&'static str> {
let b = std::str::from_utf8(brand).ok()?;
if b == "qt " {
@@ -105,8 +119,31 @@ fn video_brand(brand: &[u8]) -> Option<&'static str> {
mp4.then_some("video/mp4")
}
-/// The type a file's magic bytes prove: an image, a PDF or a video. `None` for text and for
-/// anything that isn't accepted.
+/// ISO-BMFF major brands that are audio: iTunes AAC/ALAC (`M4A `) and audiobooks (`M4B `).
+fn audio_brand(brand: &[u8]) -> Option<&'static str> {
+ matches!(brand, b"M4A " | b"M4B ").then_some("audio/mp4")
+}
+
+/// An MPEG audio frame header at the start (an MP3 without an ID3 tag, or an MP2), or an ADTS
+/// header (raw AAC). Strict enough that a UTF-16 byte-order mark (`FF FE`) or a run of `FF`
+/// bytes isn't taken: MPEG layer I is left out, as are the reserved version, bitrate and
+/// sampling-rate values.
+fn mpeg_audio(head: &[u8]) -> Option<&'static str> {
+ let [0xFF, b1, b2, ..] = *head else { return None };
+ if (b1 & 0xF6) == 0xF0 {
+ // ADTS: 12 sync bits, layer 00; sampling-frequency index 0..=12
+ return (((b2 >> 2) & 0x0F) <= 12).then_some("audio/aac");
+ }
+ let sync = (b1 & 0xE0) == 0xE0;
+ let version_ok = (b1 >> 3) & 0b11 != 0b01;
+ let layer_2_or_3 = matches!((b1 >> 1) & 0b11, 0b01 | 0b10);
+ let bitrate_ok = !matches!(b2 >> 4, 0x0 | 0xF);
+ let rate_ok = (b2 >> 2) & 0b11 != 0b11;
+ (sync && version_ok && layer_2_or_3 && bitrate_ok && rate_ok).then_some("audio/mpeg")
+}
+
+/// The type a file's magic bytes prove: an image, a PDF, a video or audio. `None` for text and
+/// for anything that isn't accepted.
pub fn sniff_magic(head: &[u8]) -> Option<&'static str> {
if head.starts_with(b"\x89PNG\r\n\x1a\n") {
return Some("image/png");
@@ -120,18 +157,31 @@ pub fn sniff_magic(head: &[u8]) -> Option<&'static str> {
if head.len() >= 12 && &head[..4] == b"RIFF" && &head[8..12] == b"WEBP" {
return Some("image/webp");
}
+ if head.len() >= 12 && &head[..4] == b"RIFF" && &head[8..12] == b"WAVE" {
+ return Some("audio/wav");
+ }
if head.starts_with(b"%PDF-") {
return Some("application/pdf");
}
// ISO-BMFF: a box size, then `ftyp` and the major brand (MP4, MOV)
if head.len() >= 12 && &head[4..8] == b"ftyp" {
- return video_brand(&head[8..12]);
+ return video_brand(&head[8..12]).or_else(|| audio_brand(&head[8..12]));
}
// EBML: WebM (and Matroska, which browsers play the same way)
if head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) {
return Some("video/webm");
}
- None
+ // An ID3v2 tag (v2.2 to v2.4) opens most MP3s
+ if head.len() >= 4 && head.starts_with(b"ID3") && matches!(head[3], 2..=4) {
+ return Some("audio/mpeg");
+ }
+ if head.starts_with(b"OggS") {
+ return Some("audio/ogg");
+ }
+ if head.starts_with(b"fLaC") {
+ return Some("audio/flac");
+ }
+ mpeg_audio(head)
}
/// Extensions that are never text, so a file named so is refused as soon as its first bytes
@@ -217,6 +267,8 @@ impl Utf8Check {
pub enum Cap {
/// A video passed 100 MB.
Video,
+ /// An audio file passed 100 MB.
+ Audio,
/// Anything else passed 20 MB.
Other,
/// The declared length passed 100 MB before the type was known.
@@ -244,8 +296,9 @@ fn store_error(e: StoreError) -> Response {
StoreError::TooLarge(cap) => {
let (text, max) = match cap {
Cap::Video => ("Videos can be at most 100 MB.", MAX_VIDEO_BYTES),
- Cap::Other => ("Files can be at most 20 MB (videos up to 100 MB).", MAX_ATTACHMENT_BYTES),
- Cap::Either => ("Files can be at most 100 MB for videos and 20 MB for everything else.", MAX_VIDEO_BYTES),
+ Cap::Audio => ("Audio files can be at most 100 MB.", MAX_AUDIO_BYTES),
+ Cap::Other => ("Files can be at most 20 MB (videos and audio up to 100 MB).", MAX_ATTACHMENT_BYTES),
+ Cap::Either => ("Files can be at most 100 MB for videos and audio and 20 MB for everything else.", MAX_VIDEO_BYTES),
};
coded(StatusCode::PAYLOAD_TOO_LARGE, "too_large", text, json!({"max_bytes": max}))
}
@@ -253,7 +306,7 @@ fn store_error(e: StoreError) -> Response {
StoreError::Unsupported => coded(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
"unsupported_type",
- "Only images (PNG, JPEG, GIF, WebP), videos (MP4, MOV, WebM), PDFs and text files (UTF-8: txt, md, csv, json, code) can be attached.",
+ "Only images (PNG, JPEG, GIF, WebP), videos (MP4, MOV, WebM), audio (MP3, M4A, AAC, WAV, OGG, Opus, FLAC), PDFs and text files (UTF-8: txt, md, csv, json, code) can be attached.",
json!({}),
),
StoreError::Io => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
@@ -301,18 +354,23 @@ impl Sink {
}
/// Takes the next chunk. Refuses as soon as the file is over its cap (100 MB once the head
- /// sniffed as video, else 20 MB) or its bytes rule it out ([`ruled_out_early`]).
+ /// sniffed as video or audio, else 20 MB) or its bytes rule it out ([`ruled_out_early`]).
async fn push(&mut self, chunk: &[u8]) -> Result<(), StoreError> {
if self.head.len() < HEAD_BYTES {
let take = (HEAD_BYTES - self.head.len()).min(chunk.len());
self.head.extend_from_slice(&chunk[..take]);
}
self.size += chunk.len() as u64;
- let video = sniff_magic(&self.head).is_some_and(is_video_mime);
+ let magic = sniff_magic(&self.head);
+ let video = magic.is_some_and(is_video_mime);
+ let audio = magic.is_some_and(is_audio_mime);
if video && self.size > MAX_VIDEO_BYTES {
return Err(StoreError::TooLarge(Cap::Video));
}
- if !video && self.size > MAX_ATTACHMENT_BYTES {
+ if audio && self.size > MAX_AUDIO_BYTES {
+ return Err(StoreError::TooLarge(Cap::Audio));
+ }
+ if !video && !audio && self.size > MAX_ATTACHMENT_BYTES {
return Err(StoreError::TooLarge(Cap::Other));
}
self.utf8.feed(chunk);
@@ -766,7 +824,7 @@ pub fn tools() -> Vec<Value> {
"name": "share_file",
"description": "Give the user a file as a download card in this chat, posted as you. Either `path` (a file in your workspace) \
or `content` (text you write, e.g. a CSV or markdown report). Images, PDFs and text files up to 20 MB; \
- videos (MP4, MOV, WebM) up to 100 MB. When the person asks to see something (a mockup, a page, a chart), \
+ videos (MP4, MOV, WebM) and audio (MP3, M4A, AAC, WAV, OGG, Opus, FLAC) up to 100 MB. When the person asks to see something (a mockup, a page, a chart), \
share it as an image: describing it isn't enough. Sharing the same file again within a few minutes posts nothing new.",
"inputSchema": {
"type": "object",
@@ -1012,10 +1070,11 @@ pub async fn tool_share(state: &AppState, scope: &SelfScope, args: &Value) -> (S
let stored = match stored {
Ok(s) => s,
Err(StoreError::TooLarge(Cap::Video)) => return ("The video is larger than 100 MB.".into(), true),
- Err(StoreError::TooLarge(_)) => return ("The file is larger than 20 MB (videos up to 100 MB).".into(), true),
+ Err(StoreError::TooLarge(Cap::Audio)) => return ("The audio file is larger than 100 MB.".into(), true),
+ Err(StoreError::TooLarge(_)) => return ("The file is larger than 20 MB (videos and audio up to 100 MB).".into(), true),
Err(StoreError::Empty) => return ("The file is empty.".into(), true),
Err(StoreError::Unsupported) => {
- return ("Only images, videos (MP4, MOV, WebM), PDFs and UTF-8 text files can be shared.".into(), true)
+ return ("Only images, videos (MP4, MOV, WebM), audio (MP3, M4A, AAC, WAV, OGG, Opus, FLAC), PDFs and UTF-8 text files can be shared.".into(), true)
}
Err(StoreError::Io) => return ("Could not read or store the file.".into(), true),
};
@@ -1226,19 +1285,69 @@ mod tests {
assert_eq!(sniff(&ftyp(b"3gp5"), false, "x"), Some("video/mp4"));
assert_eq!(sniff(&ftyp(b"qt "), false, "clip.mp4"), Some("video/quicktime"));
assert_eq!(sniff(b"\x1a\x45\xdf\xa3\x9f\x42\x86\x81\x01webm", false, "clip.mov"), Some("video/webm"));
- // ftyp files that aren't videos a browser plays: an iPhone photo, a voice memo
- for b in [b"heic", b"mif1", b"avif", b"M4A ", b"crx "] {
+ // ftyp files that aren't videos a browser plays: an iPhone photo, camera raw (a voice memo is audio)
+ for b in [b"heic", b"mif1", b"avif", b"crx "] {
assert_eq!(sniff(&ftyp(b), false, "x.mp4"), None, "{}", String::from_utf8_lossy(b));
}
assert_eq!(sniff(b"\0\0\0\x20ftyp", false, "x.mp4"), None, "no brand yet");
assert!(is_video_mime("video/quicktime") && !is_video_mime("image/png") && !is_video_mime("video/x-msvideo"));
}
+ #[test]
+ fn audio_is_sniffed_from_bytes() {
+ let id3 = b"ID3\x04\0\0\0\0\0\x23TSSE\0\0\0";
+ assert_eq!(sniff(id3, false, "song.mp3"), Some("audio/mpeg"));
+ assert_eq!(sniff(id3, false, "x.txt"), Some("audio/mpeg"), "the bytes decide, not the name");
+ // MPEG-1 layer III, 128 kbit/s, 44.1 kHz (no tag); MPEG-2 layer III; MPEG-1 layer II
+ assert_eq!(sniff(&[0xFF, 0xFB, 0x90, 0x64], false, "x"), Some("audio/mpeg"));
+ assert_eq!(sniff(&[0xFF, 0xF3, 0x84, 0xC4], false, "x"), Some("audio/mpeg"));
+ assert_eq!(sniff(&[0xFF, 0xFD, 0x94, 0x00], false, "x"), Some("audio/mpeg"));
+ // ADTS AAC (MPEG-4 and MPEG-2)
+ assert_eq!(sniff(&[0xFF, 0xF1, 0x50, 0x80], false, "x.aac"), Some("audio/aac"));
+ assert_eq!(sniff(&[0xFF, 0xF9, 0x50, 0x80], false, "x.aac"), Some("audio/aac"));
+ assert_eq!(sniff(&ftyp(b"M4A "), false, "memo.m4a"), Some("audio/mp4"));
+ assert_eq!(sniff(&ftyp(b"M4B "), false, "book.m4b"), Some("audio/mp4"));
+ // An audio-only mp42 file stays what video_brand says: a video/mp4 (a <video> plays sound)
+ assert_eq!(sniff(&ftyp(b"mp42"), false, "x.m4a"), Some("video/mp4"));
+ assert_eq!(sniff(b"RIFF\x24\x08\0\0WAVEfmt ", false, "x.wav"), Some("audio/wav"));
+ assert_eq!(sniff(b"OggS\0\x02\0\0", false, "x.opus"), Some("audio/ogg"));
+ assert_eq!(sniff(b"fLaC\0\0\0\x22", false, "x.flac"), Some("audio/flac"));
+ // Not audio: JPEG still wins its FF D8; a UTF-16 mark, FF runs, layer I, reserved values,
+ // another RIFF (AVI), an ID3 that isn't v2.2-2.4
+ assert_eq!(sniff(&[0xFF, 0xD8, 0xFF, 0xE0], false, "x.mp3"), Some("image/jpeg"));
+ let bad: [&[u8]; 12] = [
+ &[0xFF, 0xFE, 0x48, 0x00],
+ &[0xFF, 0xFF, 0xFF, 0xFF],
+ &[0xFF, 0xFF, 0x90, 0x64],
+ &[0xFF, 0xEB, 0x90, 0x64],
+ &[0xFF, 0xF9, 0x3C, 0x80],
+ &[0xFF, 0xFB, 0xF0, 0x64],
+ &[0xFF, 0xFB, 0x00, 0x64],
+ &[0xFF, 0xFB, 0x9C, 0x64],
+ &[0xFF, 0xFB],
+ b"RIFF\x24\x08\0\0AVI LIST",
+ b"ID3\x09\0\0",
+ b"ID3",
+ ];
+ for bad in bad {
+ assert_eq!(sniff(bad, false, "song.mp3"), None, "{bad:02X?}");
+ }
+ for m in AUDIO_TYPES {
+ assert!(is_audio_mime(m) && !is_video_mime(m), "{m}");
+ }
+ assert!(!is_audio_mime("audio/x-aiff") && !is_audio_mime("video/mp4"));
+ assert_eq!(MAX_AUDIO_BYTES, MAX_VIDEO_BYTES);
+ }
+
#[test]
fn first_bytes_rule_out_what_cannot_be_accepted() {
let zip = b"PK\x03\x04\x14\0\0\0\x08\0\0\0\0\0\0\0";
assert!(ruled_out_early(zip, false, "holiday.mp4"), "a zip renamed .mp4");
- assert!(ruled_out_early(b"ID3\x04\0\0\0\0\0\x23TSSE\0\0\0", false, "song.mp3"));
+ // 22l: a real MP3 is taken; an .exe or a zip called song.mp3 isn't
+ assert!(!ruled_out_early(b"ID3\x04\0\0\0\0\0\x23TSSE\0\0\0", false, "song.mp3"));
+ assert!(ruled_out_early(b"MZ\x90\0\x03\0\0\0\x04\0\0\0\xff\xff\0\0", false, "song.mp3"));
+ assert!(ruled_out_early(&zip[..], false, "song.mp3"));
+ assert!(ruled_out_early(b"just ascii bytes here", true, "song.mp3"));
// Text-looking bytes under a binary extension can't become text/plain
assert!(ruled_out_early(b"just ascii bytes here", true, "clip.mp4"));
assert!(ruled_out_early(&ftyp(b"heic"), false, "IMG_1.HEIC"));
diff --git a/tests/attachments_test.rs b/tests/attachments_test.rs
index 4a1b995e..acb4d6a5 100644
--- a/tests/attachments_test.rs
+++ b/tests/attachments_test.rs
@@ -182,6 +182,23 @@ async fn names_and_ids_cannot_traverse() {
assert_eq!(s, StatusCode::BAD_REQUEST, "context_id is required");
}
+/// 22l: a song sent in the chat reaches the bot as a file: its name, type, size and id on the
+/// "[Attached files]" line, never its bytes in the prompt.
+#[tokio::test]
+async fn a_sent_song_reaches_the_agent_as_a_file_by_id() {
+ let env = setup().await;
+ let mut mp3 = b"ID3\x04\0\0\0\0\0\x23TSSE\0\0\0SONG_BYTES_NEVER_IN_PROMPT".to_vec();
+ mp3.resize(4096, 0);
+ let (s, song) = upload(&env, "song.mp3", mp3).await;
+ assert_eq!((s, song["mime"].as_str()), (StatusCode::CREATED, Some("audio/mpeg")), "{song}");
+ let id = song["id"].as_str().unwrap();
+ send_direct(&env, &env.a, "listen REPLYTAG:au1", json!({"attachment_ids": [id]})).await;
+ wait_reply(&env, &env.a, "answer au1").await;
+ let args = invocations_with("REPLYTAG:au1").pop().unwrap();
+ assert!(args.contains("[Attached files]") && args.contains(&format!("song.mp3 (audio/mpeg, 4 KB) id {id}")), "{args}");
+ assert!(!args.contains("SONG_BYTES_NEVER_IN_PROMPT"), "audio is never inlined");
+}
+
#[tokio::test]
async fn sent_files_reach_the_agent_and_only_its_chat() {
let env = setup().await;
diff --git a/tests/video_attachments_test.rs b/tests/video_attachments_test.rs
index f6011215..0340b469 100644
--- a/tests/video_attachments_test.rs
+++ b/tests/video_attachments_test.rs
@@ -113,14 +113,12 @@ async fn videos_are_known_by_their_bytes_and_play_inline() {
assert_eq!(h["content-range"], format!("bytes 100-199/{}", bytes.len()));
}
- // Not videos, whatever the name: a zip, an iPhone photo, an M4A voice memo
+ // Not videos, whatever the name: a zip, an iPhone photo (an M4A voice memo is audio since 22l)
let mut zip = b"PK\x03\x04\x14\0\0\0\x08\0".to_vec();
zip.resize(4096, 7);
let mut heic = b"\0\0\0\x18ftypheic\0\0\0\0mif1heic".to_vec();
heic.resize(4096, 0);
- let mut m4a = b"\0\0\0\x1cftypM4A \0\0\0\0M4A isom".to_vec();
- m4a.resize(4096, 0);
- for (name, bytes) in [("holiday.mp4", zip), ("IMG_0001.mov", heic), ("memo.mp4", m4a)] {
+ for (name, bytes) in [("holiday.mp4", zip), ("IMG_0001.mov", heic)] {
let (s, v) = upload(&env, name, bytes).await;
assert_eq!(s, StatusCode::UNSUPPORTED_MEDIA_TYPE, "{name}");
assert_eq!(v["code"], "unsupported_type");
@@ -138,7 +136,7 @@ async fn videos_may_be_100_mb_and_everything_else_20() {
let (s, v) = upload(&env, "big.txt", vec![b'a'; 25 * 1024 * 1024]).await;
assert_eq!(s, StatusCode::PAYLOAD_TOO_LARGE);
- assert_eq!(v, json!({"error": "Files can be at most 20 MB (videos up to 100 MB).", "code": "too_large", "max_bytes": 20971520}));
+ assert_eq!(v, json!({"error": "Files can be at most 20 MB (videos and audio up to 100 MB).", "code": "too_large", "max_bytes": 20971520}));
let (s, v) = upload(&env, "huge.mp4", fake_mp4(100 * 1024 * 1024 + 1)).await;
assert_eq!(s, StatusCode::PAYLOAD_TOO_LARGE);
@@ -150,7 +148,7 @@ async fn videos_may_be_100_mb_and_everything_else_20() {
let (s, v) = upload_body(&env, "x.mp4", Body::from(fake_mp4(64)), Some(100 * 1024 * 1024 + 1)).await;
assert_eq!(s, StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(v["max_bytes"], 104857600);
- assert_eq!(v["error"], "Files can be at most 100 MB for videos and 20 MB for everything else.");
+ assert_eq!(v["error"], "Files can be at most 100 MB for videos and audio and 20 MB for everything else.");
assert_eq!(tmp_files(&env), 0, "refused uploads leave no temp file");
}
@@ -206,7 +204,7 @@ async fn agents_share_videos_and_see_them_as_frames() {
let r = self_call(&env, "tok-ws", "share_file", json!({"path": "big.mp4", "name": "big.mp4"})).await;
assert_eq!((r["isError"].as_bool(), text_of(&r).as_str()), (Some(true), "The video is larger than 100 MB."));
let r = self_call(&env, "tok-ws", "share_file", json!({"path": "big.bin.txt", "name": "big.txt"})).await;
- assert_eq!((r["isError"].as_bool(), text_of(&r).as_str()), (Some(true), "The file is larger than 20 MB (videos up to 100 MB)."));
+ assert_eq!((r["isError"].as_bool(), text_of(&r).as_str()), (Some(true), "The file is larger than 20 MB (videos and audio up to 100 MB)."));
let r = self_call(&env, "tok-ws", "read_attachment", json!({"id": id})).await;
if kwnt::server::video::tools().is_none() {
@@ -254,3 +252,100 @@ async fn a_damaged_video_reads_as_a_clear_error() {
assert_eq!(r["isError"], true);
assert_eq!(text_of(&r), "Couldn't look inside cut.mp4 (video/mp4, 4 KB): ffmpeg can't read it (it may be cut off or damaged).");
}
+
+/// `head` padded with zeros to `len` bytes.
+fn padded(head: &[u8], len: usize) -> Vec<u8> {
+ let mut v = head.to_vec();
+ v.resize(len, 0);
+ v
+}
+
+/// An MP3 that opens with an ID3v2.4 tag, as most do.
+const MP3_HEAD: &[u8] = b"ID3\x04\0\0\0\0\0\x23TSSE\0\0\0";
+
+/// 22l: the chat takes audio (MP3, M4A/AAC, WAV, OGG/Opus, FLAC) by its bytes, never its name,
+/// up to 100 MB like a video. It downloads (no inline player: no new UI).
+#[tokio::test]
+async fn audio_is_known_by_its_bytes_and_may_be_100_mb() {
+ let env = setup().await;
+ // Names that lie on purpose for some: the bytes decide
+ let cases: [(&str, &[u8], &str); 10] = [
+ ("song.mp3", MP3_HEAD, "audio/mpeg"),
+ ("episode.mp3", &[0xFF, 0xFB, 0x90, 0x64][..], "audio/mpeg"),
+ ("memo.m4a", b"\0\0\0\x1cftypM4A \0\0\0\0M4A isom", "audio/mp4"),
+ ("memo.mp4", b"\0\0\0\x1cftypM4A \0\0\0\0M4A isom", "audio/mp4"),
+ ("book.m4b", b"\0\0\0\x1cftypM4B \0\0\0\0M4B isom", "audio/mp4"),
+ ("raw.aac", &[0xFF, 0xF1, 0x50, 0x80][..], "audio/aac"),
+ ("take.wav", b"RIFF\x24\x08\0\0WAVEfmt ", "audio/wav"),
+ ("voice.opus", b"OggS\0\x02\0\0\0\0\0\0\0\0", "audio/ogg"),
+ ("album.flac", b"fLaC\0\0\0\x22", "audio/flac"),
+ ("notes.txt", MP3_HEAD, "audio/mpeg"),
+ ];
+ for (name, head, mime) in cases {
+ let (s, a) = upload(&env, name, padded(head, 4096)).await;
+ assert_eq!(s, StatusCode::CREATED, "{name}: {a}");
+ assert_eq!(a["mime"], mime, "{name}");
+ let id = a["id"].as_str().unwrap();
+ let (s, h, _) = fetch(&env, &format!("/api/attachments/{id}/content"), &[]).await;
+ assert_eq!(s, StatusCode::OK);
+ assert_eq!(h["content-type"], mime);
+ assert!(h["content-disposition"].to_str().unwrap().starts_with("attachment;"), "{name}: audio downloads");
+ assert_eq!(h["x-content-type-options"], "nosniff");
+ }
+
+ // A renamed binary stays refused, right after its first bytes: an .exe, a zip, plain text and
+ // UTF-16 text (whose FF FE mark must not pass for an MPEG frame) called song.mp3
+ let mut utf16 = vec![0xFF, 0xFE];
+ "Hello there, a song".encode_utf16().for_each(|u| utf16.extend_from_slice(&u.to_le_bytes()));
+ for (name, bytes) in [
+ ("song.mp3", padded(b"MZ\x90\0\x03\0\0\0\x04\0\0\0\xff\xff\0\0", 4096)),
+ ("song.mp3", padded(b"PK\x03\x04\x14\0\0\0\x08\0", 4096)),
+ ("song.mp3", b"just some text pretending to be a song".to_vec()),
+ ("song.mp3", utf16),
+ ("song.wav", padded(b"RIFF\x24\x08\0\0AVI LIST", 4096)),
+ ] {
+ let (s, v) = upload(&env, name, bytes).await;
+ assert_eq!(s, StatusCode::UNSUPPORTED_MEDIA_TYPE, "{name}: {v}");
+ assert_eq!(v["code"], "unsupported_type");
+ assert!(v["error"].as_str().unwrap().contains("audio (MP3, M4A, AAC, WAV, OGG, Opus, FLAC)"), "{v}");
+ }
+
+ // Past 20 MB is fine for audio; past 100 MB isn't
+ let (s, a) = upload(&env, "episode.mp3", padded(MP3_HEAD, 25 * 1024 * 1024)).await;
+ assert_eq!((s, a["mime"].as_str()), (StatusCode::CREATED, Some("audio/mpeg")), "{a}");
+ let (s, v) = upload(&env, "long.mp3", padded(MP3_HEAD, 100 * 1024 * 1024 + 1)).await;
+ assert_eq!(s, StatusCode::PAYLOAD_TOO_LARGE);
+ assert_eq!(v, json!({"error": "Audio files can be at most 100 MB.", "code": "too_large", "max_bytes": 104857600}));
+ assert_eq!(tmp_files(&env), 0, "refused uploads leave no temp file");
+}
+
+/// 22l: a bot gets audio as a file (its id, then a path from read_attachment), never as model
+/// content, and can share audio back up to 100 MB.
+#[tokio::test]
+async fn agents_share_audio_and_read_it_as_a_file() {
+ let env = setup().await;
+ let ws = env.tmp.path().join("audio-ws");
+ std::fs::create_dir_all(&ws).unwrap();
+ std::fs::write(ws.join("ep.mp3"), padded(MP3_HEAD, 4096)).unwrap();
+ std::fs::write(ws.join("long.mp3"), padded(MP3_HEAD, 100 * 1024 * 1024 + 1)).unwrap();
+ direct_turn(&env, "tok-au", &env.a, Some(ws.clone())).await;
+
+ let r = self_call(&env, "tok-au", "share_file", json!({"path": "ep.mp3", "name": "ep.mp3"})).await;
+ assert_eq!(r["isError"], false, "{r}");
+ let card = messages(&env, &env.a).await.into_iter().find(|m| m.text == "Shared a file: ep.mp3").unwrap();
+ let meta: Value = serde_json::from_str(card.meta.as_deref().unwrap()).unwrap();
+ assert_eq!(meta["attachments"][0]["mime"], "audio/mpeg");
+ let id = meta["attachments"][0]["id"].as_str().unwrap().to_string();
+
+ let r = self_call(&env, "tok-au", "share_file", json!({"path": "long.mp3", "name": "long.mp3"})).await;
+ assert_eq!((r["isError"].as_bool(), text_of(&r).as_str()), (Some(true), "The audio file is larger than 100 MB."));
+
+ let r = self_call(&env, "tok-au", "read_attachment", json!({"id": id})).await;
+ assert_eq!(r["isError"], false, "{r}");
+ let blocks = r["content"].as_array().unwrap();
+ assert_eq!(blocks.len(), 1, "one text block, no inline media: {r}");
+ assert_eq!(blocks[0]["type"], "text");
+ let text = blocks[0]["text"].as_str().unwrap();
+ assert!(text.starts_with("ep.mp3 is a audio/mpeg file (4 KB). A read-only copy is at "), "{text}");
+ assert!(text.ends_with("open it with your own file tools."), "{text}");
+}