π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(utils): resolve UTF-16 BOM text as text, not audio/mpeg (#23354)
YuTengjing7c658f6bb130
diff --git a/packages/utils/src/mimeType.test.ts b/packages/utils/src/mimeType.test.tsindex a8d359ac680..809b8a86010 100644--- a/packages/utils/src/mimeType.test.ts+++ b/packages/utils/src/mimeType.test.ts@@ -226,6 +226,77 @@ describe('resolveMimeType', () => {);});+ describe('UTF-16 text with a byte order mark', () => {+ // Windows PowerShell 5.1 `Tee-Object` / `Out-File` write UTF-16LE with a+ // BOM. Its leading 0xFF 0xFE matches file-type's MPEG audio frame sync, so+ // CLI evidence uploads were stored as audio/mpeg and sent to the model as+ // audio.+ const utf16le = (text: string) => Buffer.from(`\uFEFF${text}`, 'utf16le');+ const utf16be = (text: string) => utf16le(text).swap16();+ const output = 'PS C:\\> backup compare: OK\r\nsqlite integrity_check: ok\r\n';++ it('resolves UTF-16LE text as text instead of audio/mpeg', async () => {+ await expect(resolveMimeType('backup_compare.txt', utf16le(output))).resolves.toBe(+ 'text/plain; charset=utf-16le',+ );+ await expect(resolveMimeType('out.txt', utf16le('ok'))).resolves.toBe(+ 'text/plain; charset=utf-16le',+ );+ });++ it('keeps text whose surrogate pair straddles the sniff window', async () => {+ // BOM + 4094 code units fill bytes 0-8189; the emoji's high surrogate takes+ // 8190-8191 and its low surrogate falls outside the 8192-byte sample.+ const text = `${'a'.repeat(4094)}π`;+ await expect(resolveMimeType('emoji.txt', utf16le(text))).resolves.toBe(+ 'text/plain; charset=utf-16le',+ );+ });++ it('resolves UTF-16BE text with its own charset', async () => {+ await expect(resolveMimeType('backup_compare.txt', utf16be(output))).resolves.toBe(+ 'text/plain; charset=utf-16be',+ );+ });++ it('keeps the extension text mime and downgrades binary extension mimes', async () => {+ await expect(resolveMimeType('result.json', utf16le('{"ok":true}'))).resolves.toBe(+ 'application/json; charset=utf-16le',+ );+ await expect(resolveMimeType('module.ts', utf16le('export {};\n'))).resolves.toBe(+ 'text/plain; charset=utf-16le',+ );+ await expect(resolveMimeType('no-extension', utf16le(output))).resolves.toBe(+ 'text/plain; charset=utf-16le',+ );+ });++ it('keeps MPEG audio whose frame header starts with the same bytes', async () => {+ // MPEG-1 Layer I frame header (0xFF 0xFE ...) followed by a silent payload.+ const mpegFrame = Buffer.alloc(1024);+ mpegFrame.set([0xff, 0xfe, 0x90, 0x00]);+ await expect(resolveMimeType('clip.mp1', mpegFrame)).resolves.toBe('audio/mpeg');++ // Non-silent frames: a lenient UTF-16 decode reads compressed audio as+ // mostly printable text, so the strict decode must reject it.+ let seed = 1;+ const noisyMpeg = Buffer.alloc(3 * 384);+ for (let i = 0; i < noisyMpeg.length; i++) {+ seed = (seed * 1_103_515_245 + 12_345) % 2 ** 31;+ noisyMpeg[i] = (seed >> 16) & 0xff;+ }+ for (let frame = 0; frame < 3; frame++) {+ noisyMpeg.set([0xff, 0xfe, 0x90, 0x00], frame * 384);+ }+ await expect(resolveMimeType('clip.mp1', noisyMpeg)).resolves.toBe('audio/mpeg');++ // A regular MP3 frame (Layer III) never starts with a BOM.+ const mp3Frame = Buffer.alloc(1024);+ mp3Frame.set([0xff, 0xfb, 0x90, 0x64]);+ await expect(resolveMimeType('song.mp3', mp3Frame)).resolves.toBe('audio/mpeg');+ });+ });+it('falls back to application/octet-stream when the sniff detects binary data', async () => {// No known extension and no recognisable magic bytes β the sniff sees// embedded null bytes and classifies as binary.diff --git a/packages/utils/src/mimeType.ts b/packages/utils/src/mimeType.tsindex 19add37b126..a32cd0059fd 100644--- a/packages/utils/src/mimeType.ts+++ b/packages/utils/src/mimeType.ts@@ -1,5 +1,7 @@import mime from 'mime';+import { sniffBinaryBuffer } from './isBinaryContent';+// Extensions where mime-db has no entry (or a wrong one) but a specific// text/x-* mime helps downstream language detection.const CUSTOM_MIME_TYPES: Record<string, string> = {@@ -38,9 +40,14 @@ const TEXT_MIME_PATTERN =// keep working for them.const SVG_MIME = 'image/svg+xml';-const withCharset = (mimeType: string): string =>+// A MIME charset label (RFC 2046), not a Node.js encoding name; `utf8` is not+// a registered label, so keep the hyphen.+// oxlint-disable-next-line unicorn/text-encoding-identifier-case+const DEFAULT_CHARSET = 'utf-8';++const withCharset = (mimeType: string, charset: string = DEFAULT_CHARSET): string =>TEXT_MIME_PATTERN.test(mimeType) && !mimeType.includes('charset=')- ? `${mimeType}; charset=utf-8`+ ? `${mimeType}; charset=${charset}`: mimeType;const getExtension = (filePath: string): string => {@@ -65,6 +72,38 @@ const looksBinary = (buffer: Uint8Array): boolean => {return false;};+type Utf16Charset = 'utf-16be' | 'utf-16le';++/**+ * Detect UTF-16 text marked by a byte order mark.+ *+ * The UTF-16LE BOM (0xFF 0xFE) is also a valid MPEG audio frame sync, so+ * file-type reports Windows PowerShell 5.1 output (`Tee-Object`, `Out-File`)+ * as audio/mpeg. The BOM alone is not proof: a real MPEG-1 Layer I frame can+ * start with the same bytes. Decode the bytes after the BOM strictly and+ * require them to read as text: compressed audio contains unpaired surrogates,+ * and a lenient decode would turn them into "printable" characters. `stream`+ * keeps a surrogate pair split by the sample boundary from failing the decode.+ */+const detectUtf16BomText = (buffer: Uint8Array): Utf16Charset | null => {+ if (buffer.byteLength < 2) return null;++ let charset: Utf16Charset;+ if (buffer[0] === 0xff && buffer[1] === 0xfe) charset = 'utf-16le';+ else if (buffer[0] === 0xfe && buffer[1] === 0xff) charset = 'utf-16be';+ else return null;++ const sample = buffer.subarray(2, Math.min(buffer.byteLength, SNIFF_BYTES));+ let text: string;+ try {+ text = new TextDecoder(charset, { fatal: true }).decode(sample, { stream: true });+ } catch {+ return null;+ }++ return sniffBinaryBuffer(new TextEncoder().encode(text)).isBinary ? null : charset;+};+/*** Sync extension-only lookup. Falls back to `application/octet-stream` for* unknown extensions. Use this when a file buffer isn't available (URL input,@@ -94,6 +133,9 @@ export const tryGetMimeType = (filePath: string): string | undefined => {* Trust magic bytes first, then fall back to the extension, and let a text* sniff overrule mime-db when the two disagree.*+ * 0. UTF-16 BOM text β text mime with the matching charset, before the+ * magic-byte check (the UTF-16LE BOM looks like an MPEG audio frame).+ * Keeps a text extension mime, otherwise falls back to text/plain.* 1. `fileTypeFromBuffer()` β magic-byte detection. Authoritative when it* matches: real MPEG-TS media wins here regardless of extension. The one* exception is a generic `application/xml` match, which yields to the@@ -108,9 +150,18 @@ export const tryGetMimeType = (filePath: string): string | undefined => {* 3. No extension mapping β sniff-based fallback.*/export const resolveMimeType = async (filePath: string, buffer: Uint8Array): Promise<string> => {+ const fromExtension = lookupExtensionMime(filePath);++ const utf16Charset = detectUtf16BomText(buffer);+ if (utf16Charset) {+ if (fromExtension === SVG_MIME) return SVG_MIME;+ return fromExtension && TEXT_MIME_PATTERN.test(fromExtension)+ ? withCharset(fromExtension, utf16Charset)+ : `text/plain; charset=${utf16Charset}`;+ }+const { fileTypeFromBuffer } = await import('file-type');const detected = await fileTypeFromBuffer(buffer);- const fromExtension = lookupExtensionMime(filePath);if (detected?.mime) {// file-type fingerprints any `<?xml` prolog as generic application/xml,// which would hide an SVG's image/svg+xml; the extension is more specific.