From cff5b896f442d787d95579dbe119a8e885cdebcd Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:46:22 +0800 Subject: [PATCH 01/13] feat(chat): extract text from document attachments and infer image MIME types --- components/ChatInput.tsx | 29 +- lib/chat-attachments.test.mjs | 449 +++++++++++++ lib/chat-attachments.ts | 1197 ++++++++++++++++++++++++++++++++- 3 files changed, 1663 insertions(+), 12 deletions(-) diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index dacc49fc8..2f5ca89d7 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -51,7 +51,10 @@ import { composeMessageWithTextAttachments, describeTextAttachmentSkip, formatAttachmentBytes, + inferImageMimeType, + isImageAttachmentFile, MAX_ATTACHED_TEXT_FILES, + readAttachmentText, selectTextAttachments, } from "@/lib/chat-attachments"; import { @@ -569,7 +572,7 @@ export const ChatInput = memo(forwardRef(function ChatIn MAX_ATTACHED_IMAGES - attachedImagesRef.current.length - pendingImageCountRef.current, ); const imageFiles = files - .filter((file) => file.type.startsWith("image/") && file.size <= MAX_ATTACHED_IMAGE_BYTES) + .filter((file) => isImageAttachmentFile(file) && file.size <= MAX_ATTACHED_IMAGE_BYTES) .slice(0, remaining); if (!imageFiles.length) { if (files.length > 0) { @@ -595,7 +598,7 @@ export const ChatInput = memo(forwardRef(function ChatIn const result = reader.result as string; // result is "data:;base64," const base64 = result.split(",")[1]; - const image = { data: base64, mimeType: file.type, previewUrl: URL.createObjectURL(file) }; + const image = { data: base64, mimeType: inferImageMimeType(file), previewUrl: URL.createObjectURL(file) }; created.push(image); resolve(image); }; @@ -655,12 +658,16 @@ export const ChatInput = memo(forwardRef(function ChatIn pendingTextFileBytesRef.current += textFiles.reduce((total, file) => total + file.size, 0); try { const readFiles = await Promise.all( - textFiles.map(async (file): Promise => ({ - name: file.name, - mimeType: file.type, - content: await file.text(), - size: file.size, - })), + textFiles.map(async (file): Promise => { + const content = await readAttachmentText(file); + if (content === null) return null; + return { + name: file.name, + mimeType: file.type, + content, + size: file.size, + }; + }) ); // The composer was cleared/sent while the reads were in flight — // drop the batch instead of re-appending stale attachments. @@ -669,7 +676,7 @@ export const ChatInput = memo(forwardRef(function ChatIn // U+FFFD replacement characters left by mis-decoded binary (e.g. // UTF-16 text read as UTF-8). const newFiles = readFiles.filter( - (file) => !file.content.includes("\u0000") && !file.content.includes("\uFFFD"), + (file): file is AttachedTextFile => file !== null && !file.content.includes("\u0000") && !file.content.includes("\uFFFD"), ); const skipped = textFiles.length - newFiles.length; setAttachedTextFiles((prev) => [ @@ -691,8 +698,8 @@ export const ChatInput = memo(forwardRef(function ChatIn }, []); const processFiles = useCallback((files: File[]) => { - const imageFiles = files.filter((file) => file.type.startsWith("image/")); - const otherFiles = files.filter((file) => !file.type.startsWith("image/")); + const imageFiles = files.filter((file) => isImageAttachmentFile(file)); + const otherFiles = files.filter((file) => !isImageAttachmentFile(file)); void processImageFiles(imageFiles); void processTextFiles(otherFiles); }, [processImageFiles, processTextFiles]); diff --git a/lib/chat-attachments.test.mjs b/lib/chat-attachments.test.mjs index 575553b93..6c7cc900f 100644 --- a/lib/chat-attachments.test.mjs +++ b/lib/chat-attachments.test.mjs @@ -1,5 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; +import { deflateRawSync, deflateSync } from "node:zlib"; async function loadSubject() { return import("./chat-attachments.ts"); @@ -9,6 +10,263 @@ function textFile(name, type = "") { return { name, type }; } +function mockFile(name, type, buffer) { + return { + name, + type, + text: async () => new TextDecoder("utf-8").decode(buffer), + arrayBuffer: async () => buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength), + }; +} + +function createZip(entries) { + function crc32(buf) { + let crc = ~0; + for (let i = 0; i < buf.length; i++) { + crc ^= buf[i]; + for (let j = 0; j < 8; j++) { + crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0); + } + } + return ~crc >>> 0; + } + + const localHeaders = []; + const cdHeaders = []; + let offset = 0; + + for (const entry of entries) { + const nameBuf = Buffer.from(entry.name, "utf-8"); + const dataBuf = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(entry.data, "utf-8"); + const crc = crc32(dataBuf); + const uncompressedSize = dataBuf.length; + + let method = 8; + let compressedBuf = deflateRawSync(dataBuf); + if (entry.store) { + method = 0; + compressedBuf = dataBuf; + } + const compressedSize = compressedBuf.length; + + const localHeader = Buffer.alloc(30 + nameBuf.length + compressedBuf.length); + localHeader.writeUInt32LE(0x04034b50, 0); + localHeader.writeUInt16LE(20, 4); + localHeader.writeUInt16LE(0, 6); + localHeader.writeUInt16LE(method, 8); + localHeader.writeUInt16LE(0, 10); + localHeader.writeUInt16LE(0, 12); + localHeader.writeUInt32LE(crc, 14); + localHeader.writeUInt32LE(compressedSize, 18); + localHeader.writeUInt32LE(uncompressedSize, 22); + localHeader.writeUInt16LE(nameBuf.length, 26); + localHeader.writeUInt16LE(0, 28); + nameBuf.copy(localHeader, 30); + compressedBuf.copy(localHeader, 30 + nameBuf.length); + + localHeaders.push(localHeader); + + const cdHeader = Buffer.alloc(46 + nameBuf.length); + cdHeader.writeUInt32LE(0x02014b50, 0); + cdHeader.writeUInt16LE(20, 4); + cdHeader.writeUInt16LE(20, 6); + cdHeader.writeUInt16LE(0, 8); + cdHeader.writeUInt16LE(method, 10); + cdHeader.writeUInt16LE(0, 12); + cdHeader.writeUInt16LE(0, 14); + cdHeader.writeUInt32LE(crc, 16); + cdHeader.writeUInt32LE(compressedSize, 20); + cdHeader.writeUInt32LE(uncompressedSize, 24); + cdHeader.writeUInt16LE(nameBuf.length, 28); + cdHeader.writeUInt16LE(0, 30); + cdHeader.writeUInt16LE(0, 32); + cdHeader.writeUInt16LE(0, 34); + cdHeader.writeUInt16LE(0, 36); + cdHeader.writeUInt32LE(0, 38); + cdHeader.writeUInt32LE(offset, 42); + nameBuf.copy(cdHeader, 46); + + cdHeaders.push(cdHeader); + offset += localHeader.length; + } + + const cdOffset = offset; + const cdSize = cdHeaders.reduce((sum, h) => sum + h.length, 0); + + const eocd = Buffer.alloc(22); + eocd.writeUInt32LE(0x06054b50, 0); + eocd.writeUInt16LE(0, 4); + eocd.writeUInt16LE(0, 6); + eocd.writeUInt16LE(entries.length, 8); + eocd.writeUInt16LE(entries.length, 10); + eocd.writeUInt32LE(cdSize, 12); + eocd.writeUInt32LE(cdOffset, 16); + eocd.writeUInt16LE(0, 20); + + return Buffer.concat([...localHeaders, ...cdHeaders, eocd]); +} + +function createPdf({ text = "", withToUnicode = false, useFlate = true, withLargeImageBeforeText = false } = {}) { + const chunks = []; + chunks.push(Buffer.from("%PDF-1.4\n%\xE2\xE3\xCF\xD3\n", "binary")); + + const offsets = []; + + function addObj(num, headerStr, streamBuf = null) { + offsets[num] = Buffer.concat(chunks).length; + chunks.push(Buffer.from(`${num} 0 obj\n${headerStr}\n`, "binary")); + if (streamBuf) { + chunks.push(Buffer.from("stream\n", "binary")); + chunks.push(streamBuf); + chunks.push(Buffer.from("\nendstream\n", "binary")); + } + chunks.push(Buffer.from("endobj\n", "binary")); + } + + addObj(1, `<< /Type /Catalog /Pages 2 0 R >>`); + addObj(2, `<< /Type /Pages /Kids [3 0 R] /Count 1 >>`); + + if (withLargeImageBeforeText) { + // 18 MiB of zeros compresses to ~18 KB; if inflated, it would blow past the 16 MiB text budget. + const bigImageRaw = deflateSync(Buffer.alloc(18 * 1024 * 1024)); + addObj(7, `<< /Type /XObject /Subtype /Image /Width 2000 /Height 3000 /BitsPerComponent 8 /Filter /FlateDecode /Length ${bigImageRaw.length} >>`, bigImageRaw); + addObj(8, `<< /Length1 ${18 * 1024 * 1024} /Filter /FlateDecode /Length ${bigImageRaw.length} >>`, bigImageRaw); + } + + let fontObj = `<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>`; + if (withToUnicode) { + fontObj = `<< /Type /Font /Subtype /Type0 /BaseFont /TestFont /Encoding /Identity-H /ToUnicode 5 0 R >>`; + } + addObj(4, fontObj); + if (withToUnicode) { + const cmapStream = `/CIDInit /ProcSet findresource begin +12 dict begin +begincmap +/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def +/CMapName /Custom-ToUnicode def +/CMapType 2 def +1 begincodespacerange +<0000> +endcodespacerange +1 beginbfchar +<0001> <4f60> +<0002> <597d> +endbfchar +endcmap +CMapName currentdict /CMap defineresource pop +end +end`; + const cmapBuf = Buffer.from(cmapStream, "utf-8"); + const cmapDeflated = useFlate ? deflateSync(cmapBuf) : cmapBuf; + const filter = useFlate ? `/Filter /FlateDecode ` : ""; + addObj(5, `<< /Length ${cmapDeflated.length} ${filter}>>`, cmapDeflated); + } else { + addObj(5, `<< >>`); + } + + addObj(3, `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 4 0 R >> >> /Contents 6 0 R >>`); + + const contentText = text ? `BT\n/F1 12 Tf\n10 700 Td\n${text}\nET` : ""; + const contentBuf = Buffer.from(contentText, "utf-8"); + const compressedContent = useFlate && contentBuf.length > 0 ? deflateSync(contentBuf) : contentBuf; + const filter = useFlate && contentBuf.length > 0 ? `/Filter /FlateDecode ` : ""; + addObj(6, `<< /Length ${compressedContent.length} ${filter}>>`, compressedContent); + + const startXref = Buffer.concat(chunks).length; + let xref = `xref\n0 7\n0000000000 65535 f \n`; + for (let i = 1; i <= 6; i++) { + xref += String(offsets[i]).padStart(10, "0") + " 00000 n \n"; + } + xref += `trailer\n<< /Size 7 /Root 1 0 R >>\nstartxref\n${startXref}\n%%EOF\n`; + chunks.push(Buffer.from(xref, "binary")); + + return Buffer.concat(chunks); +} + +function createOleDoc(text) { + const sectorSize = 512; + const header = Buffer.alloc(512); + header.set([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1], 0); + header.writeUInt16LE(0xFFFE, 28); + header.writeUInt16LE(9, 30); + header.writeUInt16LE(6, 32); + header.writeUInt32LE(1, 44); + header.writeInt32LE(1, 48); + header.writeUInt32LE(0x1000, 56); + header.writeInt32LE(-2, 60); + header.writeUInt32LE(0, 64); + header.writeInt32LE(-2, 68); + header.writeUInt32LE(0, 72); + header.writeInt32LE(0, 76); + for (let i = 1; i < 109; i++) { + header.writeInt32LE(-1, 76 + i * 4); + } + + const textBuf = Buffer.from(text, "utf16le"); + const wordDocSize = 512 + textBuf.length; + const wordDocBuf = Buffer.alloc(Math.ceil(wordDocSize / sectorSize) * sectorSize); + wordDocBuf.writeUInt16LE(0xA5EC, 0); + wordDocBuf.writeUInt16LE(0x0200, 0x000A); + textBuf.copy(wordDocBuf, 0x200); + + const pcdBuf = Buffer.alloc(8); + pcdBuf.writeUInt32LE(0x0200, 2); + + const clxPart = Buffer.alloc(1 + 4 + 4 * 2 + 8); + clxPart[0] = 2; + const pcdtSize = 4 * 2 + 8; + clxPart.writeUInt32LE(pcdtSize, 1); + clxPart.writeUInt32LE(0, 5); + clxPart.writeUInt32LE(text.length, 9); + pcdBuf.copy(clxPart, 13); + + const tableSize = clxPart.length; + const tableBuf = Buffer.alloc(Math.ceil(tableSize / sectorSize) * sectorSize); + clxPart.copy(tableBuf, 0); + + wordDocBuf.writeUInt32LE(0, 0x01A2); + wordDocBuf.writeUInt32LE(clxPart.length, 0x01A6); + + const dirBuf = Buffer.alloc(sectorSize); + function writeDirEntry(offset, name, type, startSect, size, childId = -1, leftId = -1, rightId = -1) { + const nameBuf = Buffer.from(name, "utf16le"); + nameBuf.copy(dirBuf, offset); + dirBuf.writeUInt16LE(nameBuf.length + 2, offset + 64); + dirBuf.writeUInt8(type, offset + 66); + dirBuf.writeUInt8(1, offset + 67); + dirBuf.writeInt32LE(leftId, offset + 68); + dirBuf.writeInt32LE(rightId, offset + 72); + dirBuf.writeInt32LE(childId, offset + 76); + dirBuf.writeInt32LE(startSect, offset + 116); + dirBuf.writeUInt32LE(size, offset + 120); + } + + writeDirEntry(0, "Root Entry", 5, -2, 0, 1); + const wordDocSectCount = wordDocBuf.length / sectorSize; + const tableSectCount = tableBuf.length / sectorSize; + const wordDocStartSect = 2; + const tableStartSect = wordDocStartSect + wordDocSectCount; + + writeDirEntry(128, "WordDocument", 2, wordDocStartSect, wordDocBuf.length, -1, -1, 2); + writeDirEntry(256, "1Table", 2, tableStartSect, tableBuf.length, -1, -1, -1); + + const fatBuf = Buffer.alloc(sectorSize, 0xFF); + fatBuf.writeInt32LE(-3, 0); + fatBuf.writeInt32LE(-2, 4); + for (let i = 0; i < wordDocSectCount; i++) { + const sect = wordDocStartSect + i; + const next = (i === wordDocSectCount - 1) ? -2 : sect + 1; + fatBuf.writeInt32LE(next, sect * 4); + } + for (let i = 0; i < tableSectCount; i++) { + const sect = tableStartSect + i; + const next = (i === tableSectCount - 1) ? -2 : sect + 1; + fatBuf.writeInt32LE(next, sect * 4); + } + + return Buffer.concat([header, fatBuf, dirBuf, wordDocBuf, tableBuf]); +} + test("recognizes text and markdown attachments by mime or extension", async () => { const { isTextAttachmentFile } = await loadSubject(); @@ -107,3 +365,194 @@ test("skip banners name the limit the batch actually hit", async () => { "3 file(s) skipped: attachments are limited to 4 MB per message.", ); }); + +test("isImageAttachmentFile and inferImageMimeType handle raster images and MIME inference", async () => { + const { isImageAttachmentFile, inferImageMimeType } = await loadSubject(); + + assert.equal(isImageAttachmentFile({ name: "photo.PNG", type: "" }), true); + assert.equal(inferImageMimeType({ name: "photo.PNG", type: "" }), "image/png"); + + assert.equal(isImageAttachmentFile({ name: "photo.jpg", type: "application/octet-stream" }), true); + assert.equal(inferImageMimeType({ name: "photo.jpg", type: "application/octet-stream" }), "image/jpeg"); + + assert.equal(isImageAttachmentFile({ name: "pic.webp", type: "image/webp" }), true); + assert.equal(inferImageMimeType({ name: "pic.webp", type: "image/webp" }), "image/webp"); + + assert.equal(isImageAttachmentFile({ name: "icon.svg", type: "" }), false); + assert.equal(isImageAttachmentFile({ name: "icon.svg", type: "image/svg+xml" }), true); + assert.equal(inferImageMimeType({ name: "icon.svg", type: "image/svg+xml" }), "image/svg+xml"); + + assert.equal(isImageAttachmentFile({ name: "doc.pdf", type: "" }), false); +}); + +test("readAttachmentText decodes PDF with FlateDecode + ToUnicode CMap (including CJK) and handles empty/scanned PDF", async () => { + const { readAttachmentText } = await loadSubject(); + + const cjkPdf = createPdf({ text: "<00010002> Tj", withToUnicode: true, useFlate: true }); + const cjkResult = await readAttachmentText(mockFile("test-cjk.pdf", "application/pdf", cjkPdf)); + assert.equal(cjkResult, "你好"); + + const pdfWithBigImageAndFont = createPdf({ + text: "<00010002> Tj", + withToUnicode: true, + useFlate: true, + withLargeImageBeforeText: true, + }); + const bigMediaResult = await readAttachmentText(mockFile("big-media.pdf", "application/pdf", pdfWithBigImageAndFont)); + assert.equal(bigMediaResult, "你好"); + + const asciiPdf = createPdf({ text: "(Hello World) Tj", withToUnicode: false, useFlate: true }); + const asciiResult = await readAttachmentText(mockFile("test-ascii.pdf", "application/pdf", asciiPdf)); + assert.equal(asciiResult, "Hello World"); + + const emptyPdf = createPdf({ text: "", withToUnicode: false, useFlate: true }); + const emptyResult = await readAttachmentText(mockFile("scanned.pdf", "application/pdf", emptyPdf)); + assert.equal(emptyResult, null); +}); + +test("readAttachmentText extracts docx paragraphs and tables", async () => { + const { readAttachmentText } = await loadSubject(); + + const docxZip = createZip([ + { + name: "word/document.xml", + data: ` + + Header Paragraph + + + Col 1 + Col 2 + + + A + B + + + + `, + }, + ]); + + const result = await readAttachmentText(mockFile("sample.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", docxZip)); + assert.match(result, /Header Paragraph/); + assert.match(result, /\| Col 1 \| Col 2 \|/); + assert.match(result, /\| A \| B \|/); +}); + +test("readAttachmentText extracts xlsx with sharedStrings and worksheet into Markdown table", async () => { + const { readAttachmentText } = await loadSubject(); + + const xlsxZip = createZip([ + { + name: "xl/sharedStrings.xml", + data: `ItemPriceApple`, + }, + { + name: "xl/workbook.xml", + data: ``, + }, + { + name: "xl/_rels/workbook.xml.rels", + data: ``, + }, + { + name: "xl/worksheets/sheet1.xml", + data: ` + 01 + 210.5 + `, + }, + ]); + + const result = await readAttachmentText(mockFile("book.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xlsxZip)); + assert.match(result, /### Sales/); + assert.match(result, /\| Item \| Price \|/); + assert.match(result, /\| Apple \| 10\.5 \|/); +}); + +test("readAttachmentText extracts pptx with slides and speaker notes", async () => { + const { readAttachmentText } = await loadSubject(); + + const pptxZip = createZip([ + { + name: "ppt/presentation.xml", + data: ``, + }, + { + name: "ppt/slides/slide1.xml", + data: ` + + Slide 1 Title + + `, + }, + { + name: "ppt/notesSlides/notesSlide1.xml", + data: ` + + Speaker note for slide 1 + + `, + }, + ]); + + const result = await readAttachmentText(mockFile("pres.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", pptxZip)); + assert.match(result, /### Slide 1/); + assert.match(result, /Slide 1 Title/); + assert.match(result, /Speaker note for slide 1/); +}); + +test("readAttachmentText extracts odt with paragraphs", async () => { + const { readAttachmentText } = await loadSubject(); + + const odtZip = createZip([ + { + name: "content.xml", + data: ` + + ODT Heading + ODT Paragraph text + + `, + }, + ]); + + const result = await readAttachmentText(mockFile("document.odt", "application/vnd.oasis.opendocument.text", odtZip)); + assert.match(result, /ODT Heading/); + assert.match(result, /ODT Paragraph text/); +}); + +test("readAttachmentText extracts legacy Word 97-2003 .doc with UTF-16LE CJK text and guards against cyclic FAT", async () => { + const { readAttachmentText } = await loadSubject(); + + const oleDoc = createOleDoc("繁體中文 Word 97 測試 123"); + const result = await readAttachmentText(mockFile("legacy.doc", "application/msword", oleDoc)); + assert.equal(result, "繁體中文 Word 97 測試 123"); + + // Self-referential FAT entry (sector 1 -> sector 1) must terminate cleanly without hanging. + const cyclicDoc = Buffer.from(oleDoc); + cyclicDoc.writeInt32LE(1, 512 + 4); + const cyclicResult = await readAttachmentText(mockFile("cyclic.doc", "application/msword", cyclicDoc)); + assert.equal(cyclicResult, "繁體中文 Word 97 測試 123"); +}); + +test("readAttachmentText decodes UTF-16LE and UTF-16BE BOM text files", async () => { + const { readAttachmentText } = await loadSubject(); + + const leBuf = Buffer.concat([Buffer.from([0xFF, 0xFE]), Buffer.from("Hello UTF-16LE", "utf16le")]); + const leResult = await readAttachmentText(mockFile("utf16le.txt", "text/plain", leBuf)); + assert.equal(leResult, "Hello UTF-16LE"); + + const beBuf = Buffer.from([0xFE, 0xFF, 0x00, 0x48, 0x00, 0x69]); // "Hi" + const beResult = await readAttachmentText(mockFile("utf16be.txt", "text/plain", beBuf)); + assert.equal(beResult, "Hi"); +}); + +test("readAttachmentText returns null on raw binary files", async () => { + const { readAttachmentText } = await loadSubject(); + + const binBuf = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D]); + const binResult = await readAttachmentText(mockFile("image.png", "image/png", binBuf)); + assert.equal(binResult, null); +}); diff --git a/lib/chat-attachments.ts b/lib/chat-attachments.ts index d62fb9305..a49dd0a31 100644 --- a/lib/chat-attachments.ts +++ b/lib/chat-attachments.ts @@ -105,9 +105,52 @@ export function isTextAttachmentFile(file: Pick): boolean || TEXT_FILE_EXTENSIONS[getFileExtension(file.name)] === true; } +const MARKDOWN_EXTENSIONS: Record = { + md: true, + markdown: true, + mdx: true, + docx: true, + xlsx: true, + pptx: true, + odt: true, + ods: true, + odp: true, + epub: true, +}; + +const RASTER_IMAGE_EXTENSIONS: Record = { + png: "image/png", + jpg: "image/jpeg", + jpeg: "image/jpeg", + gif: "image/gif", + webp: "image/webp", + bmp: "image/bmp", + avif: "image/avif", + ico: "image/x-icon", +}; + +export function isImageAttachmentFile(file: Pick): boolean { + if (file.type && file.type.startsWith("image/")) { + return true; + } + if (!file.type || file.type === "application/octet-stream") { + const ext = getFileExtension(file.name); + return Boolean(RASTER_IMAGE_EXTENSIONS[ext]); + } + return false; +} + +export function inferImageMimeType(file: Pick): string { + if (file.type && file.type.startsWith("image/")) { + return file.type; + } + const ext = getFileExtension(file.name); + return RASTER_IMAGE_EXTENSIONS[ext] || file.type || "application/octet-stream"; +} + function languageForFile(name: string): string { const extension = getFileExtension(name); - if (extension === "md" || extension === "markdown" || extension === "mdx") return "markdown"; + if (MARKDOWN_EXTENSIONS[extension]) return "markdown"; return "text"; } @@ -128,3 +171,1155 @@ export function composeMessageWithTextAttachments( }); return [message.trim(), ...blocks].filter(Boolean).join("\n\n"); } + +function decodeXmlEntities(str: string): string { + return str + .replace(/&/g, "&") + .replace(/</g, "<") + .replace(/>/g, ">") + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/&#(\d+);/g, (_, code) => String.fromCharCode(parseInt(code, 10))) + .replace(/&#x([0-9a-fA-F]+);/g, (_, code) => String.fromCharCode(parseInt(code, 16))); +} + +const MAX_DECOMPRESSED_BYTES = MAX_TOTAL_ATTACHED_TEXT_BYTES * 4; +const MAX_CMAP_ENTRIES = 262144; +const MAX_CMAP_RANGE_SPAN = 4096; + +interface DecompressBudget { + remaining: number; +} + +async function decompressDeflate( + data: Uint8Array, + format: "deflate" | "deflate-raw", + budget: DecompressBudget, +): Promise { + const ds = new DecompressionStream(format); + const writer = ds.writable.getWriter(); + const writePromise = writer.write(new Uint8Array(data)).then(() => writer.close()); + writePromise.catch(() => {}); + const chunks: Uint8Array[] = []; + let total = 0; + const reader = ds.readable.getReader(); + while (true) { + const { done, value } = await reader.read(); + if (done) break; + total += value.length; + budget.remaining -= value.length; + if (total > MAX_DECOMPRESSED_BYTES || budget.remaining < 0) { + await reader.cancel().catch(() => {}); + throw new Error("Decompressed stream exceeds maximum allowed size"); + } + chunks.push(value); + } + await writePromise; + const res = new Uint8Array(total); + let off = 0; + for (const c of chunks) { + res.set(c, off); + off += c.length; + } + return res; +} + +async function tryDecompress(data: Uint8Array, budget: DecompressBudget): Promise { + if (data.length === 0) return new Uint8Array(0); + if (budget.remaining <= 0) return null; + const hasZlibHeader = data.length >= 2 + && (data[0] & 0x0f) === 8 + && (data[0] >> 4) <= 7 + && ((data[0] << 8) | data[1]) % 31 === 0; + const primary: "deflate" | "deflate-raw" = hasZlibHeader ? "deflate" : "deflate-raw"; + const secondary: "deflate" | "deflate-raw" = hasZlibHeader ? "deflate-raw" : "deflate"; + try { + return await decompressDeflate(data, primary, budget); + } catch { + if (budget.remaining <= 0) return null; + try { + return await decompressDeflate(data, secondary, budget); + } catch { + return null; + } + } +} + +interface PdfCMap { + map: Map; + codeBytes: 1 | 2; +} + +function decodeCMapTargetHex(hex: string): string { + const clean = hex.replace(/\s+/g, ""); + if (clean.length === 2) { + const cp = parseInt(clean, 16); + return cp > 0 ? String.fromCodePoint(cp) : ""; + } + let out = ""; + for (let i = 0; i < clean.length; i += 4) { + const cp = parseInt(clean.slice(i, i + 4), 16); + if (cp >= 0xd800 && cp <= 0xdbff && i + 8 <= clean.length) { + const low = parseInt(clean.slice(i + 4, i + 8), 16); + if (low >= 0xdc00 && low <= 0xdfff) { + out += String.fromCharCode(cp, low); + i += 4; + continue; + } + } + if (cp > 0 && cp !== 0xffff) out += String.fromCodePoint(cp); + } + return out; +} + +function parseCMap(cmapStr: string, cmapBudget: DecompressBudget): PdfCMap { + const map = new Map(); + let codeBytes: 1 | 2 = 1; + const csRegex = /begincodespacerange([\s\S]*?)endcodespacerange/g; + let match: RegExpExecArray | null; + while ((match = csRegex.exec(cmapStr)) !== null) { + const pairs = match[1].match(/<([0-9a-fA-F]+)>\s*<([0-9a-fA-F]+)>/g) ?? []; + for (const pair of pairs) { + const m = pair.match(/<([0-9a-fA-F]+)>/); + if (m && m[1].length >= 4) codeBytes = 2; + } + } + + const bfcharRegex = /beginbfchar([\s\S]*?)endbfchar/g; + while ((match = bfcharRegex.exec(cmapStr)) !== null && cmapBudget.remaining > 0) { + const pairRegex = /<([0-9a-fA-F]+)>\s*<([0-9a-fA-F]+)>/g; + let pm: RegExpExecArray | null; + while ((pm = pairRegex.exec(match[1])) !== null && --cmapBudget.remaining >= 0) { + if (pm[1].length >= 4) codeBytes = 2; + map.set(parseInt(pm[1], 16), decodeCMapTargetHex(pm[2])); + } + } + + const bfrangeRegex = /beginbfrange([\s\S]*?)endbfrange/g; + while ((match = bfrangeRegex.exec(cmapStr)) !== null && cmapBudget.remaining > 0) { + const rangeRegex = /<([0-9a-fA-F]+)>\s*<([0-9a-fA-F]+)>\s*(?:<([0-9a-fA-F]+)>|\[([\s\S]*?)\])/g; + let rm: RegExpExecArray | null; + while ((rm = rangeRegex.exec(match[1])) !== null && cmapBudget.remaining > 0) { + if (rm[1].length >= 4) codeBytes = 2; + const start = parseInt(rm[1], 16); + const end = parseInt(rm[2], 16); + if (end < start) continue; + if (rm[3]) { + const baseStr = decodeCMapTargetHex(rm[3]); + if (!baseStr) continue; + const prefix = baseStr.slice(0, -1); + const lastUnit = baseStr.charCodeAt(baseStr.length - 1); + const maxEnd = Math.min(end, start + MAX_CMAP_RANGE_SPAN - 1); + for (let code = start; code <= maxEnd && --cmapBudget.remaining >= 0; code++) { + const nextUnit = lastUnit + (code - start); + if (nextUnit >= 0xffff) break; + if (nextUnit > 0) { + map.set(code, prefix + String.fromCharCode(nextUnit)); + } + } + } else if (rm[4]) { + const items = rm[4].match(/<([0-9a-fA-F]+)>/g) ?? []; + for (let i = 0; i < items.length && start + i <= end && --cmapBudget.remaining >= 0; i++) { + map.set(start + i, decodeCMapTargetHex(items[i].slice(1, -1))); + } + } + } + } + return { map, codeBytes }; +} + +function decodePdfLiteralBytes(str: string): Uint8Array { + const bytes: number[] = []; + for (let i = 0; i < str.length; i++) { + const ch = str.charCodeAt(i); + if (ch === 0x5c && i + 1 < str.length) { + const next = str[++i]; + if (next === "n") bytes.push(0x0a); + else if (next === "r") bytes.push(0x0d); + else if (next === "t") bytes.push(0x09); + else if (next === "b") bytes.push(0x08); + else if (next === "f") bytes.push(0x0c); + else if (next === "(") bytes.push(0x28); + else if (next === ")") bytes.push(0x29); + else if (next === "\\") bytes.push(0x5c); + else if (next === "\r") { + if (str[i + 1] === "\n") i++; + } else if (next === "\n") { + // escaped line continuation + } else if (next >= "0" && next <= "7") { + let octal = next; + if (i + 1 < str.length && str[i + 1] >= "0" && str[i + 1] <= "7") octal += str[++i]; + if (i + 1 < str.length && str[i + 1] >= "0" && str[i + 1] <= "7") octal += str[++i]; + bytes.push(parseInt(octal, 8) & 0xff); + } else { + bytes.push(next.charCodeAt(0) & 0xff); + } + } else { + bytes.push(ch & 0xff); + } + } + return Uint8Array.from(bytes); +} + +function decodePdfHexBytes(hexStr: string): Uint8Array { + const clean = hexStr.replace(/\s+/g, ""); + if (clean.length === 0) return new Uint8Array(0); + const padded = clean.length % 2 === 1 ? `${clean}0` : clean; + const out = new Uint8Array(padded.length / 2); + for (let i = 0; i < padded.length; i += 2) { + out[i / 2] = parseInt(padded.slice(i, i + 2), 16); + } + return out; +} + +function decodeBytesWithPdfCMap(bytes: Uint8Array, cmap: PdfCMap | undefined): string { + if (!cmap || cmap.map.size === 0) { + if (bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff) { + return new TextDecoder("utf-16be").decode(bytes.subarray(2)); + } + if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xfe) { + return new TextDecoder("utf-16le").decode(bytes.subarray(2)); + } + try { + return new TextDecoder("utf-8", { fatal: true }).decode(bytes); + } catch { + return new TextDecoder("windows-1252").decode(bytes); + } + } + let out = ""; + if (cmap.codeBytes === 2 && bytes.length >= 2) { + for (let i = 0; i + 1 < bytes.length; i += 2) { + const code = (bytes[i] << 8) | bytes[i + 1]; + out += cmap.map.get(code) ?? (code >= 0x20 && code <= 0x7e ? String.fromCharCode(code) : ""); + } + } else { + for (const b of bytes) { + out += cmap.map.get(b) ?? (b >= 0x20 && b <= 0x7e ? String.fromCharCode(b) : ""); + } + } + return out; +} + +function bytesToBinaryString(bytes: Uint8Array): string { + const CHUNK = 0x8000; + let out = ""; + for (let i = 0; i < bytes.length; i += CHUNK) { + out += String.fromCharCode(...bytes.subarray(i, i + CHUNK)); + } + return out; +} + +async function extractPdfText(buf: ArrayBuffer): Promise { + const budget: DecompressBudget = { remaining: MAX_DECOMPRESSED_BYTES }; + const latin1 = bytesToBinaryString(new Uint8Array(buf)); + const objHeaderRegex = /(\d+)\s+\d+\s+obj\b/g; + const streamMarkerRe = />>\s*stream(?:\r?\n|\r)/g; + const nonTextStreamRe = /\/Subtype\s*\/(?:Image|Type1C|CIDFontType0C|OpenType)\b|\/Length[123]\b|\/Type\s*\/(?:XRef|Metadata|EmbeddedFile)\b|\/BitsPerComponent\b/; + const objects = new Map(); + let m: RegExpExecArray | null; + while ((m = objHeaderRegex.exec(latin1)) !== null) { + const id = parseInt(m[1], 10); + const bodyStart = m.index + m[0].length; + const endObjIdx = latin1.indexOf("endobj", bodyStart); + if (endObjIdx === -1) break; + objHeaderRegex.lastIndex = endObjIdx + 6; + const body = latin1.slice(bodyStart, endObjIdx); + const endStreamIdx = body.indexOf("endstream"); + const dictStart = endStreamIdx !== -1 ? body.indexOf("<<") : -1; + let sMatch: RegExpExecArray | null = null; + if (dictStart !== -1 && dictStart < endStreamIdx) { + streamMarkerRe.lastIndex = dictStart + 2; + const candidate = streamMarkerRe.exec(body); + if (candidate && candidate.index < endStreamIdx) { + sMatch = candidate; + } + } + if (sMatch && endStreamIdx !== -1) { + const dict = body.slice(dictStart + 2, sMatch.index); + if (nonTextStreamRe.test(dict)) { + objects.set(id, { dict, streamText: null, body }); + continue; + } + const streamStart = sMatch.index + sMatch[0].length; + let streamEnd = endStreamIdx; + if (body[streamEnd - 1] === "\n") streamEnd--; + if (body[streamEnd - 1] === "\r") streamEnd--; + const rawStream = streamEnd >= streamStart ? body.slice(streamStart, streamEnd) : ""; + let streamText: string | null = rawStream; + if (/\/FlateDecode\b/.test(dict) && rawStream.length > 0) { + if (budget.remaining <= 0) { + streamText = null; + } else { + const rawBytes = Uint8Array.from(rawStream, (c) => c.charCodeAt(0) & 0xff); + const decomp = await tryDecompress(rawBytes, budget); + streamText = decomp ? bytesToBinaryString(decomp) : null; + } + } + objects.set(id, { dict, streamText, body }); + if (streamText && /\/Type\s*\/ObjStm\b/.test(dict)) { + const firstMatch = /\/First\s+(\d+)/.exec(dict); + const countMatch = /\/N\s+(\d+)/.exec(dict); + if (firstMatch && countMatch) { + const first = parseInt(firstMatch[1], 10); + const count = parseInt(countMatch[1], 10); + const header = streamText.slice(0, first).trim().split(/\s+/).map(Number); + const content = streamText.slice(first); + for (let i = 0; i < count && i * 2 + 1 < header.length; i++) { + const objNum = header[i * 2]; + const offset = header[i * 2 + 1]; + const nextOffset = i + 1 < count ? header[(i + 1) * 2 + 1] : content.length; + const subBody = content.slice(offset, nextOffset); + if (!objects.has(objNum)) { + objects.set(objNum, { dict: subBody, streamText: null, body: subBody }); + } + } + } + } + } else { + objects.set(id, { dict: body, streamText: null, body }); + } + } + + const cmapBudget: DecompressBudget = { remaining: MAX_CMAP_ENTRIES }; + const cmapsByObj = new Map(); + for (const [id, obj] of objects) { + if (cmapBudget.remaining <= 0) break; + if (obj.streamText && (obj.streamText.includes("begincmap") || obj.streamText.includes("/CMapName"))) { + cmapsByObj.set(id, parseCMap(obj.streamText, cmapBudget)); + } + } + const fontObjIds = new Set(); + const fontObjToCMap = new Map(); + for (const [id, obj] of objects) { + if (/\/Type\s*\/Font\b/.test(obj.body) || /\/Subtype\s*\/(?:Type0|Type1|TrueType|MMType1|Type3|CIDFontType[02])\b/.test(obj.body)) { + fontObjIds.add(id); + } + const tu = /\/ToUnicode\s+(\d+)\s+\d+\s+R/.exec(obj.body); + if (tu) { + fontObjIds.add(id); + const cmap = cmapsByObj.get(parseInt(tu[1], 10)); + if (cmap) fontObjToCMap.set(id, cmap); + } + } + const knownFontNames = new Set(); + const fontNameToCMap = new Map(); + for (const [, obj] of objects) { + const fontRefRe = /\/([A-Za-z0-9_.-]+)\s+(\d+)\s+\d+\s+R/g; + let fm: RegExpExecArray | null; + while ((fm = fontRefRe.exec(obj.body)) !== null) { + const targetId = parseInt(fm[2], 10); + if (fontObjIds.has(targetId)) { + knownFontNames.add(fm[1]); + } + const cmap = fontObjToCMap.get(targetId); + if (cmap) fontNameToCMap.set(fm[1], cmap); + } + } + const unifiedMap = new Map(); + let unifiedCodeBytes: 1 | 2 = 1; + for (const cmap of cmapsByObj.values()) { + if (cmap.codeBytes === 2) unifiedCodeBytes = 2; + for (const [k, v] of cmap.map) { + if (unifiedMap.size >= MAX_CMAP_ENTRIES) break; + unifiedMap.set(k, v); + } + } + const fallbackCMap: PdfCMap | undefined = unifiedMap.size > 0 ? { map: unifiedMap, codeBytes: unifiedCodeBytes } : undefined; + + const resolveFontCMap = (fontName: string | null): PdfCMap | undefined => { + if (fontName) { + if (fontNameToCMap.has(fontName)) return fontNameToCMap.get(fontName); + if (knownFontNames.has(fontName)) return undefined; + } + return fallbackCMap; + }; + + const lines: string[] = []; + for (const [, obj] of objects) { + if (!obj.streamText || !obj.streamText.includes("BT") || obj.streamText.includes("begincmap")) continue; + let currentFont: string | null = null; + const btStartRe = /\bBT\b/g; + const etRe = /\bET\b/g; + let bm: RegExpExecArray | null; + while ((bm = btStartRe.exec(obj.streamText)) !== null) { + const blockStart = bm.index + bm[0].length; + etRe.lastIndex = blockStart; + const etMatch = etRe.exec(obj.streamText); + if (!etMatch) break; + btStartRe.lastIndex = etMatch.index + etMatch[0].length; + const block = obj.streamText.slice(blockStart, etMatch.index); + let chunk = ""; + const tokenRe = /\/([A-Za-z0-9_.-]+)\s+[-+\d.]+\s+Tf|\((?:\\[\s\S]|[^\\()])*\)|<([0-9a-fA-F\s]+)>|\b(Td|TD|Tm|T\*)\b/g; + let tm: RegExpExecArray | null; + while ((tm = tokenRe.exec(block)) !== null) { + if (tm[1]) { + currentFont = tm[1]; + } else if (tm[0].startsWith("(")) { + const bytes = decodePdfLiteralBytes(tm[0].slice(1, -1)); + chunk += decodeBytesWithPdfCMap(bytes, resolveFontCMap(currentFont)); + } else if (tm[2] !== undefined) { + const bytes = decodePdfHexBytes(tm[2]); + chunk += decodeBytesWithPdfCMap(bytes, resolveFontCMap(currentFont)); + } + } + if (chunk.trim()) lines.push(chunk.trim()); + } + } + + const result = lines.join("\n").replace(/\u0000/g, "").trim(); + return result.length > 0 && !result.includes("\uFFFD") ? result : null; +} + +async function readZipEntries(buffer: ArrayBuffer): Promise Promise>> { + const budget: DecompressBudget = { remaining: MAX_DECOMPRESSED_BYTES }; + const view = new DataView(buffer); + const len = buffer.byteLength; + let eocdOffset = -1; + const maxSearch = Math.min(len, 65535 + 22); + for (let i = len - 22; i >= len - maxSearch; i--) { + if (view.getUint32(i, true) === 0x06054b50) { + eocdOffset = i; + break; + } + } + + const entries = new Map Promise>(); + if (eocdOffset !== -1) { + const cdOffset = view.getUint32(eocdOffset + 16, true); + const cdCount = view.getUint16(eocdOffset + 10, true); + let curr = cdOffset; + for (let i = 0; i < cdCount && curr < eocdOffset; i++) { + if (view.getUint32(curr, true) !== 0x02014b50) break; + const method = view.getUint16(curr + 10, true); + const compressedSize = view.getUint32(curr + 20, true); + const nameLen = view.getUint16(curr + 28, true); + const extraLen = view.getUint16(curr + 30, true); + const commentLen = view.getUint16(curr + 32, true); + const localOffset = view.getUint32(curr + 42, true); + + const nameBytes = new Uint8Array(buffer, curr + 46, nameLen); + const name = new TextDecoder("utf-8").decode(nameBytes); + + if (view.getUint32(localOffset, true) === 0x04034b50) { + const localNameLen = view.getUint16(localOffset + 26, true); + const localExtraLen = view.getUint16(localOffset + 28, true); + const dataOffset = localOffset + 30 + localNameLen + localExtraLen; + const compressedData = new Uint8Array(buffer, dataOffset, compressedSize); + + entries.set(name, async () => { + if (method === 0) { + budget.remaining -= compressedData.byteLength; + if (budget.remaining < 0) { + throw new Error("Decompressed archive exceeds maximum allowed size"); + } + return compressedData; + } + if (method === 8) return await decompressDeflate(compressedData, "deflate-raw", budget); + throw new Error(`Unsupported method ${method}`); + }); + } + curr += 46 + nameLen + extraLen + commentLen; + } + } + return entries; +} + +function extractDocxRuns(containerXml: string): string { + const elemRegex = /][\s\S]*?<\/w:t>|\/>)|]*\/>|]*\/>/g; + let text = ""; + let m: RegExpExecArray | null; + while ((m = elemRegex.exec(containerXml)) !== null) { + const tag = m[0]; + if (tag.startsWith("]*>/, "").replace(/<\/w:t>$/, ""); + text += decodeXmlEntities(content); + } else if (tag.startsWith(" Promise>): Promise { + const xmlNames = ["word/document.xml"]; + for (const name of entries.keys()) { + if (/^word\/(?:header|footer)\d*\.xml$/.test(name)) { + xmlNames.push(name); + } + } + const parts: string[] = []; + for (const name of xmlNames) { + const fn = entries.get(name); + if (!fn) continue; + const buf = await fn(); + const xml = new TextDecoder("utf-8").decode(buf); + const blockRegex = /|/g; + let m: RegExpExecArray | null; + while ((m = blockRegex.exec(xml)) !== null) { + const block = m[0]; + if (block.startsWith("/g; + let trMatch: RegExpExecArray | null; + while ((trMatch = trRegex.exec(block)) !== null) { + const tr = trMatch[0]; + const cells: string[] = []; + const tcRegex = //g; + let tcMatch: RegExpExecArray | null; + while ((tcMatch = tcRegex.exec(tr)) !== null) { + const tc = tcMatch[0]; + const text = extractDocxRuns(tc); + cells.push(text.trim()); + } + if (cells.length > 0) rows.push(cells); + } + if (rows.length > 0) { + const maxCols = Math.max(...rows.map((r) => r.length)); + const formattedRows = rows.map((r) => { + const padded = [...r]; + while (padded.length < maxCols) padded.push(""); + return "| " + padded.map((c) => c.replace(/\|/g, "\\|").replace(/\n/g, " ")).join(" | ") + " |"; + }); + const header = formattedRows[0]; + const separator = "| " + Array(maxCols).fill("---").join(" | ") + " |"; + parts.push([header, separator, ...formattedRows.slice(1)].join("\n")); + } + } else { + const text = extractDocxRuns(block); + if (text.trim()) parts.push(text.trim()); + } + } + } + const res = parts.join("\n\n").trim(); + return res || null; +} + +async function extractXlsx(entries: Map Promise>): Promise { + const sharedStrings: string[] = []; + const ssFn = entries.get("xl/sharedStrings.xml"); + if (ssFn) { + const ssBuf = await ssFn(); + const ssXml = new TextDecoder("utf-8").decode(ssBuf); + const siRegex = //g; + let m: RegExpExecArray | null; + while ((m = siRegex.exec(ssXml)) !== null) { + const si = m[0]; + const tRegex = //g; + let tMatch: RegExpExecArray | null; + let text = ""; + while ((tMatch = tRegex.exec(si)) !== null) { + text += tMatch[0].replace(/^]*>/, "").replace(/<\/t>$/, ""); + } + sharedStrings.push(decodeXmlEntities(text)); + } + } + + const relsFn = entries.get("xl/_rels/workbook.xml.rels"); + const relMap = new Map(); + if (relsFn) { + const relBuf = await relsFn(); + const relXml = new TextDecoder("utf-8").decode(relBuf); + const relRegex = /]*)\/>/g; + let m: RegExpExecArray | null; + while ((m = relRegex.exec(relXml)) !== null) { + const idMatch = m[1].match(/\bId="([^"]+)"/); + const targetMatch = m[1].match(/\bTarget="([^"]+)"/); + if (idMatch && targetMatch) { + relMap.set(idMatch[1], targetMatch[1].replace(/^\/?/, "xl/")); + } + } + } + + const wbFn = entries.get("xl/workbook.xml"); + const sheets: Array<{ name: string; target: string | null }> = []; + if (wbFn) { + const wbBuf = await wbFn(); + const wbXml = new TextDecoder("utf-8").decode(wbBuf); + const sheetRegex = /]*)\/>/g; + let m: RegExpExecArray | null; + while ((m = sheetRegex.exec(wbXml)) !== null) { + const nameMatch = m[1].match(/\bname="([^"]+)"/); + const rIdMatch = m[1].match(/\br:id="([^"]+)"/); + const name = nameMatch ? decodeXmlEntities(nameMatch[1]) : "Sheet"; + const target = rIdMatch ? relMap.get(rIdMatch[1]) || null : null; + sheets.push({ name, target }); + } + } + + const sections: string[] = []; + const visitedSheets = new Set(); + for (let i = 0; i < sheets.length; i++) { + const { name, target } = sheets[i]; + const path = target || `xl/worksheets/sheet${i + 1}.xml`; + if (visitedSheets.has(path)) continue; + visitedSheets.add(path); + const sFn = entries.get(path); + if (!sFn) continue; + const sBuf = await sFn(); + const sXml = new TextDecoder("utf-8").decode(sBuf); + const rows: string[][] = []; + const rowRegex = //g; + let rMatch: RegExpExecArray | null; + while ((rMatch = rowRegex.exec(sXml)) !== null) { + const rowXml = rMatch[0]; + const cells = new Map(); + let maxCol = 0; + const cRegex = /]*)>([\s\S]*?)<\/c>|]*)\/>/g; + let cMatch: RegExpExecArray | null; + while ((cMatch = cRegex.exec(rowXml)) !== null) { + const attrs = cMatch[1] || cMatch[3] || ""; + const body = cMatch[2] || ""; + const rAttr = attrs.match(/\br="([A-Z]+)(\d+)"/); + const tAttr = attrs.match(/\bt="([^"]+)"/); + let colNum = cells.size + 1; + if (rAttr) { + const colStr = rAttr[1]; + let num = 0; + for (let k = 0; k < colStr.length; k++) { + num = num * 26 + (colStr.charCodeAt(k) - 64); + } + colNum = num; + } + maxCol = Math.max(maxCol, colNum); + + let val = ""; + const type = tAttr ? tAttr[1] : ""; + if (type === "s") { + const vMatch = body.match(/(\d+)<\/v>/); + if (vMatch) val = sharedStrings[parseInt(vMatch[1], 10)] ?? ""; + } else if (type === "inlineStr") { + const tMatch = body.match(/]*>([\s\S]*?)<\/t>/); + if (tMatch) val = decodeXmlEntities(tMatch[1]); + } else if (type === "b") { + const vMatch = body.match(/([01])<\/v>/); + if (vMatch) val = vMatch[1] === "1" ? "TRUE" : "FALSE"; + } else { + const vMatch = body.match(/([\s\S]*?)<\/v>/); + if (vMatch) val = decodeXmlEntities(vMatch[1]); + } + cells.set(colNum, val.trim()); + } + if (maxCol > 0) { + const rowList: string[] = []; + for (let c = 1; c <= maxCol; c++) { + rowList.push(cells.get(c) || ""); + } + rows.push(rowList); + } + } + + if (rows.length > 0) { + const maxCols = Math.max(...rows.map((r) => r.length)); + const formattedRows = rows.map((r) => { + const padded = [...r]; + while (padded.length < maxCols) padded.push(""); + return "| " + padded.map((c) => c.replace(/\|/g, "\\|").replace(/\n/g, " ")).join(" | ") + " |"; + }); + const header = formattedRows[0]; + const separator = "| " + Array(maxCols).fill("---").join(" | ") + " |"; + sections.push(`### ${name}\n\n` + [header, separator, ...formattedRows.slice(1)].join("\n")); + } + } + + const res = sections.join("\n\n").trim(); + return res || null; +} + +async function extractPptx(entries: Map Promise>): Promise { + const slideEntries: Array<{ num: number; name: string; isNote: boolean }> = []; + for (const name of entries.keys()) { + const m = name.match(/^ppt\/slides\/slide(\d+)\.xml$/); + if (m) { + slideEntries.push({ num: parseInt(m[1], 10), name, isNote: false }); + } + const nm = name.match(/^ppt\/notesSlides\/notesSlide(\d+)\.xml$/); + if (nm) { + slideEntries.push({ num: parseInt(nm[1], 10), name, isNote: true }); + } + } + + slideEntries.sort((a, b) => a.num - b.num || (a.isNote ? 1 : -1)); + + const slidesMap = new Map(); + for (const item of slideEntries) { + if (!slidesMap.has(item.num)) slidesMap.set(item.num, { text: [], notes: [] }); + const fn = entries.get(item.name); + if (!fn) continue; + const buf = await fn(); + const xml = new TextDecoder("utf-8").decode(buf); + const pRegex = //g; + let pMatch: RegExpExecArray | null; + const pList: string[] = []; + while ((pMatch = pRegex.exec(xml)) !== null) { + const p = pMatch[0]; + const tRegex = //g; + let tMatch: RegExpExecArray | null; + let text = ""; + while ((tMatch = tRegex.exec(p)) !== null) { + text += tMatch[0].replace(/^]*>/, "").replace(/<\/a:t>$/, ""); + } + if (text.trim()) pList.push(decodeXmlEntities(text.trim())); + } + if (item.isNote) { + slidesMap.get(item.num)!.notes.push(...pList); + } else { + slidesMap.get(item.num)!.text.push(...pList); + } + } + + const sections: string[] = []; + for (const [num, { text, notes }] of Array.from(slidesMap.entries()).sort(([a], [b]) => a - b)) { + const parts: string[] = []; + if (text.length > 0) parts.push(text.join("\n")); + if (notes.length > 0) parts.push("Notes:\n" + notes.join("\n")); + if (parts.length > 0) { + sections.push(`### Slide ${num}\n${parts.join("\n\n")}`); + } + } + + const res = sections.join("\n\n").trim(); + return res || null; +} + +async function extractOdf(entries: Map Promise>): Promise { + const contentFn = entries.get("content.xml"); + if (!contentFn) return null; + const buf = await contentFn(); + const xml = new TextDecoder("utf-8").decode(buf); + + const parts: string[] = []; + const blockRegex = /||/g; + let m: RegExpExecArray | null; + while ((m = blockRegex.exec(xml)) !== null) { + const block = m[0]; + if (block.startsWith("/g; + let trMatch: RegExpExecArray | null; + while ((trMatch = trRegex.exec(block)) !== null) { + const tr = trMatch[0]; + const cells: string[] = []; + const tcRegex = //g; + let tcMatch: RegExpExecArray | null; + while ((tcMatch = tcRegex.exec(tr)) !== null) { + const tc = tcMatch[0]; + const text = tc.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim(); + cells.push(decodeXmlEntities(text)); + } + if (cells.length > 0) rows.push(cells); + } + if (rows.length > 0) { + const maxCols = Math.max(...rows.map((r) => r.length)); + const formattedRows = rows.map((r) => { + const padded = [...r]; + while (padded.length < maxCols) padded.push(""); + return "| " + padded.map((c) => c.replace(/\|/g, "\\|").replace(/\n/g, " ")).join(" | ") + " |"; + }); + const header = formattedRows[0]; + const separator = "| " + Array(maxCols).fill("---").join(" | ") + " |"; + parts.push([header, separator, ...formattedRows.slice(1)].join("\n")); + } + } else { + const text = block.replace(/<[^>]+>/g, "").trim(); + if (text) parts.push(decodeXmlEntities(text)); + } + } + const res = parts.join("\n\n").trim(); + return res || null; +} + +async function extractEpub(entries: Map Promise>): Promise { + let rootFile = "OEBPS/content.opf"; + const containerFn = entries.get("META-INF/container.xml"); + if (containerFn) { + const cBuf = await containerFn(); + const cXml = new TextDecoder("utf-8").decode(cBuf); + const m = cXml.match(/full-path="([^"]+)"/); + if (m) rootFile = m[1]; + } + + const opfFn = entries.get(rootFile); + if (!opfFn) return null; + const opfBuf = await opfFn(); + const opfXml = new TextDecoder("utf-8").decode(opfBuf); + const basePath = rootFile.includes("/") ? rootFile.replace(/\/[^/]*$/, "/") : ""; + + const manifest = new Map(); + const itemRegex = /]*)\/>/g; + let im: RegExpExecArray | null; + while ((im = itemRegex.exec(opfXml)) !== null) { + const idMatch = im[1].match(/\bid="([^"]+)"/); + const hrefMatch = im[1].match(/\bhref="([^"]+)"/); + if (idMatch && hrefMatch) { + manifest.set(idMatch[1], hrefMatch[1]); + } + } + + const spine: string[] = []; + const itemrefRegex = /]*)\/>/g; + let irMatch: RegExpExecArray | null; + while ((irMatch = itemrefRegex.exec(opfXml)) !== null) { + const idrefMatch = irMatch[1].match(/\bidref="([^"]+)"/); + if (idrefMatch && manifest.has(idrefMatch[1])) { + spine.push(manifest.get(idrefMatch[1])!); + } + } + + const chapters: string[] = []; + const visitedChapters = new Set(); + for (const href of spine) { + const fullPath = (basePath + href).replace(/^\//, ""); + if (visitedChapters.has(fullPath)) continue; + visitedChapters.add(fullPath); + const fn = entries.get(fullPath); + if (!fn) continue; + const buf = await fn(); + const html = new TextDecoder("utf-8").decode(buf); + const text = html + .replace(//gi, "") + .replace(//gi, "") + .replace(//gi, "\n") + .replace(/<\/p>/gi, "\n\n") + .replace(/<\/h[1-6]>/gi, "\n\n") + .replace(/<\/div>/gi, "\n") + .replace(/<[^>]+>/g, "") + .replace(/&/g, "&") + .replace(/</g, "<") + .replace(/>/g, ">") + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/&#(\d+);/g, (_, code) => String.fromCharCode(parseInt(code, 10))) + .replace(/&#x([0-9a-fA-F]+);/g, (_, code) => String.fromCharCode(parseInt(code, 16))) + .replace(/\r\n/g, "\n") + .replace(/\n{3,}/g, "\n\n") + .trim(); + if (text) chapters.push(text); + } + + const res = chapters.join("\n\n").trim(); + return res || null; +} + +function extractDocText(buffer: ArrayBuffer): string | null { + const view = new DataView(buffer); + if (view.byteLength < 512) return null; + const m1 = view.getUint32(0, true); + const m2 = view.getUint32(4, true); + if (m1 !== 0xE011CFD0 || m2 !== 0xE11AB1A1) { + return null; + } + + const sectorShift = view.getUint16(30, true); + if (sectorShift !== 9 && sectorShift !== 12) { + return null; + } + const sectorSize = 1 << sectorShift; + const maxSectors = Math.floor(buffer.byteLength / sectorSize); + const numFatSectors = Math.min(view.getUint32(44, true), maxSectors); + const firstDirSector = view.getInt32(48, true); + const firstDifatSector = view.getInt32(68, true); + const numDifatSectors = Math.min(view.getUint32(72, true), maxSectors); + + const fatSectorIndices: number[] = []; + for (let i = 0; i < 109 && fatSectorIndices.length < numFatSectors; i++) { + const s = view.getInt32(76 + i * 4, true); + if (s >= 0 && s < maxSectors) fatSectorIndices.push(s); + } + + let difatSect = firstDifatSector; + const visitedDifat = new Set(); + for (let i = 0; i < numDifatSectors && difatSect >= 0 && difatSect < maxSectors && !visitedDifat.has(difatSect); i++) { + visitedDifat.add(difatSect); + const offset = (difatSect + 1) * sectorSize; + if (offset + sectorSize > buffer.byteLength) break; + for (let j = 0; j < (sectorSize / 4) - 1 && fatSectorIndices.length < numFatSectors; j++) { + const s = view.getInt32(offset + j * 4, true); + if (s >= 0 && s < maxSectors) fatSectorIndices.push(s); + } + difatSect = view.getInt32(offset + sectorSize - 4, true); + } + + const fat: number[] = []; + for (const sIndex of fatSectorIndices) { + const offset = (sIndex + 1) * sectorSize; + if (offset + sectorSize > buffer.byteLength) break; + for (let j = 0; j < sectorSize / 4; j++) { + fat.push(view.getInt32(offset + j * 4, true)); + } + } + + function getChain(startSector: number): number[] { + const chain: number[] = []; + const visited = new Set(); + let curr = startSector; + while (curr >= 0 && curr < fat.length && curr < maxSectors && chain.length < maxSectors && !visited.has(curr)) { + visited.add(curr); + chain.push(curr); + curr = fat[curr]; + if (curr === -2) break; + } + return chain; + } + + function readStream(startSector: number, size: number): Uint8Array { + const chain = getChain(startSector); + const safeSize = Math.min(size, chain.length * sectorSize, MAX_DECOMPRESSED_BYTES); + const result = new Uint8Array(safeSize); + let written = 0; + for (const sect of chain) { + const offset = (sect + 1) * sectorSize; + const toRead = Math.min(sectorSize, safeSize - written); + if (toRead <= 0 || offset + toRead > buffer.byteLength) break; + result.set(new Uint8Array(buffer, offset, toRead), written); + written += toRead; + } + return result; + } + const dirChain = getChain(firstDirSector); + const dirBytes = new Uint8Array(dirChain.length * sectorSize); + let dOff = 0; + for (const sect of dirChain) { + const offset = (sect + 1) * sectorSize; + dirBytes.set(new Uint8Array(buffer, offset, sectorSize), dOff); + dOff += sectorSize; + } + + const dirView = new DataView(dirBytes.buffer, dirBytes.byteOffset, dirBytes.byteLength); + const numEntries = dirBytes.byteLength / 128; + const entries = new Map(); + + for (let i = 0; i < numEntries; i++) { + const entryOffset = i * 128; + const nameLen = dirView.getUint16(entryOffset + 64, true); + if (nameLen === 0) continue; + const actualLen = Math.max(0, nameLen - 2); + const name = new TextDecoder("utf-16le").decode(new Uint8Array(dirBytes.buffer, entryOffset, actualLen)); + const startSect = dirView.getInt32(entryOffset + 116, true); + const size = dirView.getUint32(entryOffset + 120, true); + entries.set(name, { startSect, size }); + } + + const wordDocEntry = entries.get("WordDocument"); + if (!wordDocEntry) return null; + + const wordDocStream = readStream(wordDocEntry.startSect, wordDocEntry.size); + const wordDocView = new DataView(wordDocStream.buffer, wordDocStream.byteOffset, wordDocStream.byteLength); + + const flags = wordDocView.getUint16(0x000A, true); + const fWhichTblStm = (flags & 0x0200) !== 0; + const tableEntryName = fWhichTblStm ? "1Table" : "0Table"; + const tableEntry = entries.get(tableEntryName); + if (!tableEntry) return null; + + const tableStream = readStream(tableEntry.startSect, tableEntry.size); + const tableView = new DataView(tableStream.buffer, tableStream.byteOffset, tableStream.byteLength); + + const fcClx = wordDocView.getUint32(0x01A2, true); + const lcbClx = wordDocView.getUint32(0x01A6, true); + if (fcClx + lcbClx > tableStream.byteLength) return null; + + let currClx = fcClx; + const clxEnd = fcClx + lcbClx; + let pcdtOffset = -1; + + while (currClx < clxEnd) { + const clxt = tableView.getUint8(currClx); + if (clxt === 1) { + const cb = tableView.getUint16(currClx + 1, true); + currClx += 3 + cb; + } else if (clxt === 2) { + pcdtOffset = currClx; + break; + } else { + break; + } + } + + if (pcdtOffset === -1) return null; + + const lcbPcdt = tableView.getUint32(pcdtOffset + 1, true); + const plcfpcdOffset = pcdtOffset + 5; + const numPieces = Math.floor((lcbPcdt - 4) / 12); + const cpOffset = plcfpcdOffset; + const pcdOffset = plcfpcdOffset + (numPieces + 1) * 4; + + let fullText = ""; + for (let i = 0; i < numPieces; i++) { + if (fullText.length >= MAX_DECOMPRESSED_BYTES) break; + const cpStart = tableView.getUint32(cpOffset + i * 4, true); + const cpEnd = tableView.getUint32(cpOffset + (i + 1) * 4, true); + const charCount = cpEnd - cpStart; + if (charCount <= 0 || charCount > MAX_DECOMPRESSED_BYTES) continue; + + const thisPcdOffset = pcdOffset + i * 8; + const fcValue = tableView.getUint32(thisPcdOffset + 2, true); + + const isCompressed = (fcValue & 0x40000000) !== 0; + const actualFc = fcValue & ~0x40000000; + + if (isCompressed) { + const fileOffset = actualFc / 2; + const byteLen = charCount; + if (fileOffset + byteLen <= wordDocStream.byteLength) { + const pieceBytes = new Uint8Array(wordDocStream.buffer, wordDocStream.byteOffset + fileOffset, byteLen); + fullText += new TextDecoder("windows-1252").decode(pieceBytes); + } + } else { + const fileOffset = actualFc; + const byteLen = charCount * 2; + if (fileOffset + byteLen <= wordDocStream.byteLength) { + const pieceBytes = new Uint8Array(wordDocStream.buffer, wordDocStream.byteOffset + fileOffset, byteLen); + fullText += new TextDecoder("utf-16le").decode(pieceBytes); + } + } + } + + const cleaned = fullText + .replace(/\r\n/g, "\n") + .replace(/\r/g, "\n") + .replace(/[\x07\x0B]/g, "\n") + .replace(/[\x00-\x08\x0E-\x1F]/g, ""); + + return cleaned.trim() || null; +} + +const DOCUMENT_ATTACHMENT_EXTENSIONS: Record = { + pdf: true, + docx: true, + xlsx: true, + pptx: true, + odt: true, + ods: true, + odp: true, + epub: true, + doc: true, +}; + +const DOCUMENT_ATTACHMENT_MIMES: Record = { + "application/pdf": true, + "application/msword": true, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": true, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": true, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": true, + "application/vnd.oasis.opendocument.text": true, + "application/vnd.oasis.opendocument.spreadsheet": true, + "application/vnd.oasis.opendocument.presentation": true, + "application/epub+zip": true, +}; + +export async function readAttachmentText(file: { + name: string; + type?: string; + text: () => Promise; + arrayBuffer?: () => Promise; +}): Promise { + const ext = getFileExtension(file.name); + const isKnownDocument = DOCUMENT_ATTACHMENT_EXTENSIONS[ext] === true + || Boolean(file.type && DOCUMENT_ATTACHMENT_MIMES[file.type] === true); + + // Start non-document reads with file.text() synchronously so callers and + // tests that hold/intercept File.prototype.text observe the read immediately, + // and ordinary UTF-8 files avoid a second buffer allocation. + let fallbackText: string | null = null; + if (!isKnownDocument && typeof file.text === "function") { + const text = await file.text(); + if (!text.includes("\u0000") && !text.includes("\uFFFD")) { + return text; + } + fallbackText = text; + } + + let buffer: ArrayBuffer | null = null; + if (typeof file.arrayBuffer === "function") { + buffer = await file.arrayBuffer(); + } + if (buffer) { + const bytes = new Uint8Array(buffer); + + // a) PDF (%PDF- magic or .pdf or application/pdf) + const isPdfMagic = bytes.length >= 5 && bytes[0] === 0x25 && bytes[1] === 0x50 && bytes[2] === 0x44 && bytes[3] === 0x46 && bytes[4] === 0x2D; + if (isPdfMagic || ext === "pdf" || file.type === "application/pdf") { + try { + return await extractPdfText(buffer); + } catch { + return null; + } + } + + // b) ZIP-based documents (PK\x03\x04 magic) + const isZipMagic = bytes.length >= 4 && bytes[0] === 0x50 && bytes[1] === 0x4B && bytes[2] === 0x03 && bytes[3] === 0x04; + if (isZipMagic) { + try { + const entries = await readZipEntries(buffer); + if (ext === "docx" || entries.has("word/document.xml")) { + return await extractDocx(entries); + } + if (ext === "xlsx" || entries.has("xl/workbook.xml")) { + return await extractXlsx(entries); + } + if (ext === "pptx" || entries.has("ppt/presentation.xml")) { + return await extractPptx(entries); + } + if (ext === "odt" || ext === "ods" || ext === "odp" || entries.has("content.xml")) { + return await extractOdf(entries); + } + if (ext === "epub" || entries.has("META-INF/container.xml")) { + return await extractEpub(entries); + } + } catch { + return null; + } + } + + // c) Legacy Word 97-2003 .doc (OLE2 magic: D0 CF 11 E0 A1 B1 1A E1) + const isOleMagic = bytes.length >= 8 + && bytes[0] === 0xD0 && bytes[1] === 0xCF && bytes[2] === 0x11 && bytes[3] === 0xE0 + && bytes[4] === 0xA1 && bytes[5] === 0xB1 && bytes[6] === 0x1A && bytes[7] === 0xE1; + if (isOleMagic || ext === "doc") { + try { + return extractDocText(buffer); + } catch { + return null; + } + } + + // d) UTF-16 BOM & UTF-8 + if (bytes.length >= 2) { + if (bytes[0] === 0xFF && bytes[1] === 0xFE) { + try { + const text = new TextDecoder("utf-16le", { fatal: true }).decode(new Uint8Array(buffer, 2)); + if (text.includes("\u0000") || text.includes("\uFFFD")) return null; + return text; + } catch { + return null; + } + } + if (bytes[0] === 0xFE && bytes[1] === 0xFF) { + try { + const text = new TextDecoder("utf-16be", { fatal: true }).decode(new Uint8Array(buffer, 2)); + if (text.includes("\u0000") || text.includes("\uFFFD")) return null; + return text; + } catch { + return null; + } + } + } + + try { + const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes); + if (text.includes("\u0000") || text.includes("\uFFFD")) return null; + return text; + } catch { + return null; + } + } + + if (fallbackText !== null) { + return null; + } + const text = await file.text(); + if (text.includes("\u0000") || text.includes("\uFFFD")) return null; + return text; +} From 326ede39b6857569742d38cdb5437812263d1858 Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:41:13 +0800 Subject: [PATCH 02/13] fix(chat): address document extraction review feedback for budgets, XML parsing, and formats --- components/ChatInput.tsx | 94 +++++++++++----- lib/chat-attachments.test.mjs | 202 ++++++++++++++++++++++++++++++++++ lib/chat-attachments.ts | 81 +++++++++----- 3 files changed, 325 insertions(+), 52 deletions(-) diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 2f5ca89d7..f09104a42 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -53,7 +53,9 @@ import { formatAttachmentBytes, inferImageMimeType, isImageAttachmentFile, + MAX_ATTACHED_TEXT_BYTES, MAX_ATTACHED_TEXT_FILES, + MAX_TOTAL_ATTACHED_TEXT_BYTES, readAttachmentText, selectTextAttachments, } from "@/lib/chat-attachments"; @@ -630,7 +632,7 @@ export const ChatInput = memo(forwardRef(function ChatIn } finally { pendingImageCountRef.current -= imageFiles.length; } - }, []); + }, [t]); const processTextFiles = useCallback(async (files: File[]) => { const remaining = Math.max( @@ -654,48 +656,88 @@ export const ChatInput = memo(forwardRef(function ChatIn } const revision = attachmentRevisionRef.current; const identityRevision = attachmentIdentityRevisionRef.current; + const reservedBytes = textFiles.reduce((total, file) => total + file.size, 0); pendingTextFileCountRef.current += textFiles.length; - pendingTextFileBytesRef.current += textFiles.reduce((total, file) => total + file.size, 0); + pendingTextFileBytesRef.current += reservedBytes; try { + type ReadCandidate = + | { status: "binary" } + | { status: "text"; file: AttachedTextFile }; + const readFiles = await Promise.all( - textFiles.map(async (file): Promise => { + textFiles.map(async (file): Promise => { const content = await readAttachmentText(file); - if (content === null) return null; + if (content === null || content.includes("\u0000") || content.includes("\uFFFD")) { + return { status: "binary" }; + } + const contentBytes = new TextEncoder().encode(content).byteLength; return { - name: file.name, - mimeType: file.type, - content, - size: file.size, + status: "text", + file: { + name: file.name, + mimeType: file.type, + content, + size: contentBytes, + }, }; - }) + }), ); // The composer was cleared/sent while the reads were in flight — // drop the batch instead of re-appending stale attachments. if (attachmentRevisionRef.current !== revision) return; - // Binary content cannot be inlined into the prompt: NUL bytes, or - // U+FFFD replacement characters left by mis-decoded binary (e.g. - // UTF-16 text read as UTF-8). - const newFiles = readFiles.filter( - (file): file is AttachedTextFile => file !== null && !file.content.includes("\u0000") && !file.content.includes("\uFFFD"), - ); - const skipped = textFiles.length - newFiles.length; - setAttachedTextFiles((prev) => [ - ...prev, - ...(identityRevision !== attachmentIdentityRevisionRef.current - ? newFiles - : newFiles.slice(0, Math.max(0, MAX_ATTACHED_TEXT_FILES - prev.length))), - ]); + + const binaryCount = readFiles.filter((r) => r.status === "binary").length; + const textCandidates = readFiles + .filter((r): r is { status: "text"; file: AttachedTextFile } => r.status === "text") + .map((r) => r.file); + + const otherInFlightBytes = Math.max(0, pendingTextFileBytesRef.current - reservedBytes); + let currentBytes = attachedTextFilesRef.current.reduce((total, file) => total + file.size, 0) + otherInFlightBytes; + let extractedTooLarge = 0; + let extractedOverBudget = 0; + const validTextFiles: AttachedTextFile[] = []; + + for (const candidate of textCandidates) { + if (candidate.size > MAX_ATTACHED_TEXT_BYTES) { + extractedTooLarge++; + continue; + } + if (currentBytes + candidate.size > MAX_TOTAL_ATTACHED_TEXT_BYTES) { + extractedOverBudget++; + continue; + } + currentBytes += candidate.size; + validTextFiles.push(candidate); + } + + const totalTooLarge = tooLarge + extractedTooLarge; + const totalOverBudget = overBudget + extractedOverBudget; + + setAttachedTextFiles((prev) => { + const accepted = identityRevision !== attachmentIdentityRevisionRef.current + ? validTextFiles + : validTextFiles.slice(0, Math.max(0, MAX_ATTACHED_TEXT_FILES - prev.length)); + return [...prev, ...accepted]; + }); + + const sizeLimitMessage = describeTextAttachmentSkip({ + tooLarge: totalTooLarge, + overBudget: totalOverBudget, + }); + const effectiveLimitMessage = sizeLimitMessage + ?? (binaryCount > 0 ? t("chatInput.attachmentBinarySkipped", { count: binaryCount }) : null); + setAttachError( - limitMessage - ?? (skipped > 0 ? t("chatInput.attachmentBinarySkipped", { count: skipped }) : null), + effectiveLimitMessage + ?? (validTextFiles.length === 0 && files.length > 0 ? t("chatInput.attachmentFilesSkipped", { count: files.length }) : null), ); } catch { setAttachError(t("chatInput.attachmentTextReadFailed")); } finally { pendingTextFileCountRef.current -= textFiles.length; - pendingTextFileBytesRef.current -= textFiles.reduce((total, file) => total + file.size, 0); + pendingTextFileBytesRef.current -= reservedBytes; } - }, []); + }, [t]); const processFiles = useCallback((files: File[]) => { const imageFiles = files.filter((file) => isImageAttachmentFile(file)); diff --git a/lib/chat-attachments.test.mjs b/lib/chat-attachments.test.mjs index 6c7cc900f..935b99005 100644 --- a/lib/chat-attachments.test.mjs +++ b/lib/chat-attachments.test.mjs @@ -556,3 +556,205 @@ test("readAttachmentText returns null on raw binary files", async () => { const binResult = await readAttachmentText(mockFile("image.png", "image/png", binBuf)); assert.equal(binResult, null); }); + +test("decodeXmlEntities decodes entities in a single pass and supports astral numeric references", async () => { + const { decodeXmlEntities } = await loadSubject(); + + // Single-pass decoding: &lt; preserves <, never turns into < + assert.equal(decodeXmlEntities("&lt;"), "<"); + assert.equal(decodeXmlEntities("&gt;"), ">"); + assert.equal(decodeXmlEntities("&amp;"), "&"); + assert.equal(decodeXmlEntities("&quot;"), '"'); + assert.equal(decodeXmlEntities("&apos;"), "'"); + + // Decimal and hex astral numeric references above U+FFFF + assert.equal(decodeXmlEntities("😀"), "😀"); + assert.equal(decodeXmlEntities("😀"), "😀"); + + // Preserves invalid codepoints (surrogates and out-of-range) + assert.equal(decodeXmlEntities("�"), "�"); + assert.equal(decodeXmlEntities("�"), "�"); +}); + +test("readAttachmentText extracts epub and decodes XML entities", async () => { + const { readAttachmentText } = await loadSubject(); + + const epubZip = createZip([ + { + name: "META-INF/container.xml", + data: ` + + + + + `, + }, + { + name: "OEBPS/content.opf", + data: ` + + + + + + + + `, + }, + { + name: "OEBPS/ch1.xhtml", + data: `

Chapter 1: &lt;Escaped&gt; & 😀

`, + }, + ]); + + const result = await readAttachmentText(mockFile("book.epub", "application/epub+zip", epubZip)); + assert.match(result, /Chapter 1: <Escaped> & 😀/); +}); + +test("readAttachmentText separates lines for PDF Td and positioning operators", async () => { + const { readAttachmentText } = await loadSubject(); + + const multiLinePdf = createPdf({ + text: "(First line) Tj 0 -15 Td (Second line) Tj T* (Third line) Tj", + withToUnicode: false, + useFlate: true, + }); + const result = await readAttachmentText(mockFile("multiline.pdf", "application/pdf", multiLinePdf)); + assert.equal(result, "First line\nSecond line\nThird line"); +}); + +test("readAttachmentText extracts xlsx with absolute relationship target path", async () => { + const { readAttachmentText } = await loadSubject(); + + const xlsxZip = createZip([ + { + name: "xl/workbook.xml", + data: ``, + }, + { + name: "xl/_rels/workbook.xml.rels", + data: ``, + }, + { + name: "xl/worksheets/sheet1.xml", + data: ` + 100200 + `, + }, + ]); + + const result = await readAttachmentText(mockFile("absolute.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xlsxZip)); + assert.match(result, /### Data/); + assert.match(result, /\| 100 \| 200 \|/); +}); + +test("readAttachmentText handles xlsx self-closing empty cells and rows without shifting columns", async () => { + const { readAttachmentText } = await loadSubject(); + + const xlsxZip = createZip([ + { + name: "xl/workbook.xml", + data: ``, + }, + { + name: "xl/_rels/workbook.xml.rels", + data: ``, + }, + { + name: "xl/worksheets/sheet1.xml", + data: ` + + + 42 + + + + 99 + + `, + }, + ]); + + const result = await readAttachmentText(mockFile("sparse.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xlsxZip)); + assert.match(result, /### Sheet1/); + assert.match(result, /\|\s*\|\s*42\s*\|/); + assert.match(result, /\|\s*99\s*\|/); +}); + +test("readAttachmentText extracts odf tables with self-closing cells preserving column alignment", async () => { + const { readAttachmentText } = await loadSubject(); + + const odsZip = createZip([ + { + name: "content.xml", + data: ` + + + + + ColA + ColB + ColC + + + ValA + + ValC + + + + + `, + }, + ]); + + const result = await readAttachmentText(mockFile("sheet.ods", "application/vnd.oasis.opendocument.spreadsheet", odsZip)); + assert.match(result, /\| ColA \| ColB \| ColC \|/); + assert.match(result, /\| ValA \|\s*\| ValC \|/); +}); + +test("enforces text byte budget on extracted text byte length", async () => { + const { + selectTextAttachments, + MAX_ATTACHED_TEXT_BYTES, + MAX_TOTAL_ATTACHED_TEXT_BYTES, + describeTextAttachmentSkip, + } = await loadSubject(); + + // Compressed file is small, but extracted content expands beyond MAX_ATTACHED_TEXT_BYTES + const largeExtractedCandidate = { + name: "expanded.docx", + mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + content: "x".repeat(MAX_ATTACHED_TEXT_BYTES + 10), + size: new TextEncoder().encode("x".repeat(MAX_ATTACHED_TEXT_BYTES + 10)).byteLength, + }; + + const selOversized = selectTextAttachments([largeExtractedCandidate], { usedBytes: 0, usedSlots: 0 }); + assert.equal(selOversized.accepted.length, 0); + assert.equal(selOversized.tooLarge, 1); + assert.equal(selOversized.overBudget, 0); + assert.equal( + describeTextAttachmentSkip(selOversized), + "1 file(s) skipped: files up to 4 MB are supported.", + ); + + // Extracted content exceeds remaining aggregate budget + const moderateExtractedCandidate = { + name: "moderate.pdf", + mimeType: "application/pdf", + content: "x".repeat(1024 * 1024), + size: new TextEncoder().encode("x".repeat(1024 * 1024)).byteLength, + }; + + const selOverBudget = selectTextAttachments([moderateExtractedCandidate], { + usedBytes: MAX_TOTAL_ATTACHED_TEXT_BYTES - 512 * 1024, + usedSlots: 1, + }); + assert.equal(selOverBudget.accepted.length, 0); + assert.equal(selOverBudget.tooLarge, 0); + assert.equal(selOverBudget.overBudget, 1); + assert.equal( + describeTextAttachmentSkip(selOverBudget), + "1 file(s) skipped: attachments are limited to 4 MB per message.", + ); +}); diff --git a/lib/chat-attachments.ts b/lib/chat-attachments.ts index a49dd0a31..d214e4e84 100644 --- a/lib/chat-attachments.ts +++ b/lib/chat-attachments.ts @@ -29,6 +29,7 @@ export interface AttachedTextFileData { size: number; } +/** Extracts lowercased file extension without leading dot. */ function getFileExtension(name: string): string { return name.toLowerCase().replace(/\\/g, "/").split("/").pop()?.split(".").pop() ?? ""; } @@ -99,6 +100,7 @@ export function describeTextAttachmentSkip( return null; } +/** Checks whether file is candidate for text attachment by MIME type or extension. */ export function isTextAttachmentFile(file: Pick): boolean { return file.type === "text/plain" || file.type === "text/markdown" @@ -129,6 +131,7 @@ const RASTER_IMAGE_EXTENSIONS: Record = { ico: "image/x-icon", }; +/** Checks whether file is candidate for image attachment by MIME type or extension. */ export function isImageAttachmentFile(file: Pick): boolean { if (file.type && file.type.startsWith("image/")) { return true; @@ -140,6 +143,7 @@ export function isImageAttachmentFile(file: Pick): boolea return false; } +/** Determines MIME type for image file from type property or extension fallback. */ export function inferImageMimeType(file: Pick): string { if (file.type && file.type.startsWith("image/")) { return file.type; @@ -148,12 +152,14 @@ export function inferImageMimeType(file: Pick): string { return RASTER_IMAGE_EXTENSIONS[ext] || file.type || "application/octet-stream"; } +/** Maps file extension to composer markdown language identifier. */ function languageForFile(name: string): string { const extension = getFileExtension(name); if (MARKDOWN_EXTENSIONS[extension]) return "markdown"; return "text"; } +/** Computes markdown code fence backtick count that safely encloses content. */ function fenceForContent(content: string): string { const longestRun = content.match(/`+/g)?.reduce((longest, run) => Math.max(longest, run.length), 0) ?? 0; return "`".repeat(Math.max(3, longestRun + 1)); @@ -172,15 +178,23 @@ export function composeMessageWithTextAttachments( return [message.trim(), ...blocks].filter(Boolean).join("\n\n"); } -function decodeXmlEntities(str: string): string { - return str - .replace(/&/g, "&") - .replace(/</g, "<") - .replace(/>/g, ">") - .replace(/"/g, '"') - .replace(/'/g, "'") - .replace(/&#(\d+);/g, (_, code) => String.fromCharCode(parseInt(code, 10))) - .replace(/&#x([0-9a-fA-F]+);/g, (_, code) => String.fromCharCode(parseInt(code, 16))); +/** Decodes XML named and numeric character entities in a single pass. */ +export function decodeXmlEntities(str: string): string { + const named: Record = { + amp: "&", + lt: "<", + gt: ">", + quot: '"', + apos: "'", + nbsp: "\u00a0", + }; + return str.replace(/&(?:#(\d+)|#x([0-9a-fA-F]+)|([a-zA-Z]+));/g, (whole, dec, hex, name) => { + if (name) return named[name] ?? whole; + const cp = dec ? parseInt(dec, 10) : parseInt(hex, 16); + return cp > 0 && cp <= 0x10ffff && (cp < 0xd800 || cp > 0xdfff) + ? String.fromCodePoint(cp) + : whole; + }); } const MAX_DECOMPRESSED_BYTES = MAX_TOTAL_ATTACHED_TEXT_BYTES * 4; @@ -191,6 +205,7 @@ interface DecompressBudget { remaining: number; } +/** Decompresses deflate data stream while enforcing byte budget. */ async function decompressDeflate( data: Uint8Array, format: "deflate" | "deflate-raw", @@ -224,6 +239,7 @@ async function decompressDeflate( return res; } +/** Attempts deflate or deflate-raw decompression within budget. */ async function tryDecompress(data: Uint8Array, budget: DecompressBudget): Promise { if (data.length === 0) return new Uint8Array(0); if (budget.remaining <= 0) return null; @@ -250,6 +266,7 @@ interface PdfCMap { codeBytes: 1 | 2; } +/** Converts CMap hex destination sequence into a UTF-16 string. */ function decodeCMapTargetHex(hex: string): string { const clean = hex.replace(/\s+/g, ""); if (clean.length === 2) { @@ -272,6 +289,7 @@ function decodeCMapTargetHex(hex: string): string { return out; } +/** Parses a PDF ToUnicode CMap stream into a character mapping table. */ function parseCMap(cmapStr: string, cmapBudget: DecompressBudget): PdfCMap { const map = new Map(); let codeBytes: 1 | 2 = 1; @@ -328,6 +346,7 @@ function parseCMap(cmapStr: string, cmapBudget: DecompressBudget): PdfCMap { return { map, codeBytes }; } +/** Decodes PDF literal string escape sequences into raw byte values. */ function decodePdfLiteralBytes(str: string): Uint8Array { const bytes: number[] = []; for (let i = 0; i < str.length; i++) { @@ -361,6 +380,7 @@ function decodePdfLiteralBytes(str: string): Uint8Array { return Uint8Array.from(bytes); } +/** Decodes PDF hex string into raw byte array. */ function decodePdfHexBytes(hexStr: string): Uint8Array { const clean = hexStr.replace(/\s+/g, ""); if (clean.length === 0) return new Uint8Array(0); @@ -372,6 +392,7 @@ function decodePdfHexBytes(hexStr: string): Uint8Array { return out; } +/** Maps decoded PDF bytes to text using font CMap or fallback encodings. */ function decodeBytesWithPdfCMap(bytes: Uint8Array, cmap: PdfCMap | undefined): string { if (!cmap || cmap.map.size === 0) { if (bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff) { @@ -400,6 +421,7 @@ function decodeBytesWithPdfCMap(bytes: Uint8Array, cmap: PdfCMap | undefined): s return out; } +/** Converts byte array to binary Latin-1 string in bounded chunks. */ function bytesToBinaryString(bytes: Uint8Array): string { const CHUNK = 0x8000; let out = ""; @@ -409,6 +431,7 @@ function bytesToBinaryString(bytes: Uint8Array): string { return out; } +/** Extracts text streams and character mappings from PDF file buffer. */ async function extractPdfText(buf: ArrayBuffer): Promise { const budget: DecompressBudget = { remaining: MAX_DECOMPRESSED_BYTES }; const latin1 = bytesToBinaryString(new Uint8Array(buf)); @@ -549,7 +572,7 @@ async function extractPdfText(buf: ArrayBuffer): Promise { btStartRe.lastIndex = etMatch.index + etMatch[0].length; const block = obj.streamText.slice(blockStart, etMatch.index); let chunk = ""; - const tokenRe = /\/([A-Za-z0-9_.-]+)\s+[-+\d.]+\s+Tf|\((?:\\[\s\S]|[^\\()])*\)|<([0-9a-fA-F\s]+)>|\b(Td|TD|Tm|T\*)\b/g; + const tokenRe = /\/([A-Za-z0-9_.-]+)\s+[-+\d.]+\s+Tf|\((?:\\[\s\S]|[^\\()])*\)|<([0-9a-fA-F\s]+)>|(\b(?:Td|TD|Tm)\b|\bT\*|['"])/g; let tm: RegExpExecArray | null; while ((tm = tokenRe.exec(block)) !== null) { if (tm[1]) { @@ -560,6 +583,8 @@ async function extractPdfText(buf: ArrayBuffer): Promise { } else if (tm[2] !== undefined) { const bytes = decodePdfHexBytes(tm[2]); chunk += decodeBytesWithPdfCMap(bytes, resolveFontCMap(currentFont)); + } else if (tm[3]) { + if (chunk && !chunk.endsWith("\n")) chunk += "\n"; } } if (chunk.trim()) lines.push(chunk.trim()); @@ -570,6 +595,7 @@ async function extractPdfText(buf: ArrayBuffer): Promise { return result.length > 0 && !result.includes("\uFFFD") ? result : null; } +/** Parses ZIP central directory and returns lazy decompression loaders. */ async function readZipEntries(buffer: ArrayBuffer): Promise Promise>> { const budget: DecompressBudget = { remaining: MAX_DECOMPRESSED_BYTES }; const view = new DataView(buffer); @@ -624,6 +650,7 @@ async function readZipEntries(buffer: ArrayBuffer): Promise Pr return entries; } +/** Extracts plain text from DOCX run XML elements. */ function extractDocxRuns(containerXml: string): string { const elemRegex = /][\s\S]*?<\/w:t>|\/>)|]*\/>|]*\/>/g; let text = ""; @@ -642,6 +669,7 @@ function extractDocxRuns(containerXml: string): string { return text; } +/** Extracts paragraphs and tables from OOXML DOCX document entries. */ async function extractDocx(entries: Map Promise>): Promise { const xmlNames = ["word/document.xml"]; for (const name of entries.keys()) { @@ -696,6 +724,7 @@ async function extractDocx(entries: Map Promise>): Pro return res || null; } +/** Extracts worksheets and shared strings from OOXML XLSX into Markdown tables. */ async function extractXlsx(entries: Map Promise>): Promise { const sharedStrings: string[] = []; const ssFn = entries.get("xl/sharedStrings.xml"); @@ -727,7 +756,8 @@ async function extractXlsx(entries: Map Promise>): Pro const idMatch = m[1].match(/\bId="([^"]+)"/); const targetMatch = m[1].match(/\bTarget="([^"]+)"/); if (idMatch && targetMatch) { - relMap.set(idMatch[1], targetMatch[1].replace(/^\/?/, "xl/")); + const target = targetMatch[1]; + relMap.set(idMatch[1], target.startsWith("/") ? target.slice(1) : (target.startsWith("xl/") ? target : `xl/${target}`)); } } } @@ -760,17 +790,17 @@ async function extractXlsx(entries: Map Promise>): Pro const sBuf = await sFn(); const sXml = new TextDecoder("utf-8").decode(sBuf); const rows: string[][] = []; - const rowRegex = //g; + const rowRegex = /]*\/>|]*[^/]>[\s\S]*?<\/row>/g; let rMatch: RegExpExecArray | null; while ((rMatch = rowRegex.exec(sXml)) !== null) { const rowXml = rMatch[0]; const cells = new Map(); let maxCol = 0; - const cRegex = /]*)>([\s\S]*?)<\/c>|]*)\/>/g; + const cRegex = /]*?)\/>|]*)>([\s\S]*?)<\/c>/g; let cMatch: RegExpExecArray | null; while ((cMatch = cRegex.exec(rowXml)) !== null) { - const attrs = cMatch[1] || cMatch[3] || ""; - const body = cMatch[2] || ""; + const attrs = cMatch[1] ?? cMatch[2] ?? ""; + const body = cMatch[3] || ""; const rAttr = attrs.match(/\br="([A-Z]+)(\d+)"/); const tAttr = attrs.match(/\bt="([^"]+)"/); let colNum = cells.size + 1; @@ -827,6 +857,7 @@ async function extractXlsx(entries: Map Promise>): Pro return res || null; } +/** Extracts slide text and speaker notes from OOXML PPTX presentation entries. */ async function extractPptx(entries: Map Promise>): Promise { const slideEntries: Array<{ num: number; name: string; isNote: boolean }> = []; for (const name of entries.keys()) { @@ -883,6 +914,7 @@ async function extractPptx(entries: Map Promise>): Pro return res || null; } +/** Extracts paragraphs and tables from OpenDocument (ODT/ODS/ODP) content. */ async function extractOdf(entries: Map Promise>): Promise { const contentFn = entries.get("content.xml"); if (!contentFn) return null; @@ -901,11 +933,11 @@ async function extractOdf(entries: Map Promise>): Prom while ((trMatch = trRegex.exec(block)) !== null) { const tr = trMatch[0]; const cells: string[] = []; - const tcRegex = //g; + const tcRegex = /]*\/>|/g; let tcMatch: RegExpExecArray | null; while ((tcMatch = tcRegex.exec(tr)) !== null) { const tc = tcMatch[0]; - const text = tc.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim(); + const text = tc.endsWith("/>") ? "" : tc.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim(); cells.push(decodeXmlEntities(text)); } if (cells.length > 0) rows.push(cells); @@ -930,6 +962,7 @@ async function extractOdf(entries: Map Promise>): Prom return res || null; } +/** Extracts chapter text from EPUB archive spine in reading order. */ async function extractEpub(entries: Map Promise>): Promise { let rootFile = "OEBPS/content.opf"; const containerFn = entries.get("META-INF/container.xml"); @@ -977,21 +1010,15 @@ async function extractEpub(entries: Map Promise>): Pro if (!fn) continue; const buf = await fn(); const html = new TextDecoder("utf-8").decode(buf); - const text = html + const stripped = html .replace(//gi, "") .replace(//gi, "") .replace(//gi, "\n") .replace(/<\/p>/gi, "\n\n") .replace(/<\/h[1-6]>/gi, "\n\n") .replace(/<\/div>/gi, "\n") - .replace(/<[^>]+>/g, "") - .replace(/&/g, "&") - .replace(/</g, "<") - .replace(/>/g, ">") - .replace(/"/g, '"') - .replace(/'/g, "'") - .replace(/&#(\d+);/g, (_, code) => String.fromCharCode(parseInt(code, 10))) - .replace(/&#x([0-9a-fA-F]+);/g, (_, code) => String.fromCharCode(parseInt(code, 16))) + .replace(/<[^>]+>/g, ""); + const text = decodeXmlEntities(stripped) .replace(/\r\n/g, "\n") .replace(/\n{3,}/g, "\n\n") .trim(); @@ -1002,6 +1029,7 @@ async function extractEpub(entries: Map Promise>): Pro return res || null; } +/** Extracts plain text from legacy Word 97-2003 OLE2 binary file buffer. */ function extractDocText(buffer: ArrayBuffer): string | null { const view = new DataView(buffer); if (view.byteLength < 512) return null; @@ -1209,6 +1237,7 @@ const DOCUMENT_ATTACHMENT_MIMES: Record = { "application/epub+zip": true, }; +/** Reads and decodes text content from text files or supported document formats. */ export async function readAttachmentText(file: { name: string; type?: string; From e01d57149728f0b19d5d7bdb25d37f57aba94d73 Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Tue, 27 Oct 2026 19:49:04 +0800 Subject: [PATCH 03/13] fix(chat-attachments): support attribute-less xlsx rows and odf repeat columns --- lib/chat-attachments.test.mjs | 51 +++++++++++++++++++++++++++++++++++ lib/chat-attachments.ts | 13 +++++---- 2 files changed, 59 insertions(+), 5 deletions(-) diff --git a/lib/chat-attachments.test.mjs b/lib/chat-attachments.test.mjs index 935b99005..0337375ca 100644 --- a/lib/chat-attachments.test.mjs +++ b/lib/chat-attachments.test.mjs @@ -713,6 +713,57 @@ test("readAttachmentText extracts odf tables with self-closing cells preserving assert.match(result, /\| ValA \|\s*\| ValC \|/); }); +test("readAttachmentText extracts xlsx worksheet with attribute-less row elements", async () => { + const { readAttachmentText } = await loadSubject(); + + const xlsxZip = createZip([ + { + name: "xl/workbook.xml", + data: ``, + }, + { + name: "xl/_rels/workbook.xml.rels", + data: ``, + }, + { + name: "xl/worksheets/sheet1.xml", + data: `NoRowAttrs`, + }, + ]); + + const result = await readAttachmentText(mockFile("no-row-attrs.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xlsxZip)); + assert.match(result, /### Sheet1/); + assert.match(result, /\| NoRowAttrs \|/); +}); + +test("readAttachmentText expands odf repeated columns and trims trailing empty cells", async () => { + const { readAttachmentText } = await loadSubject(); + + const odsZip = createZip([ + { + name: "content.xml", + data: ` + + + + + + Middle + + + + + + `, + }, + ]); + + const result = await readAttachmentText(mockFile("repeated.ods", "application/vnd.oasis.opendocument.spreadsheet", odsZip)); + // Should have 3 columns total: 2 leading empty columns + "Middle" column. Trailing 500 empty columns trimmed. + assert.match(result, /\|\s*\|\s*\|\s*Middle\s*\|/); + assert.doesNotMatch(result, /\| Middle \|(?:\s*\|){5,}/); +}); + test("enforces text byte budget on extracted text byte length", async () => { const { selectTextAttachments, diff --git a/lib/chat-attachments.ts b/lib/chat-attachments.ts index d214e4e84..5e8311b08 100644 --- a/lib/chat-attachments.ts +++ b/lib/chat-attachments.ts @@ -790,7 +790,7 @@ async function extractXlsx(entries: Map Promise>): Pro const sBuf = await sFn(); const sXml = new TextDecoder("utf-8").decode(sBuf); const rows: string[][] = []; - const rowRegex = /]*\/>|]*[^/]>[\s\S]*?<\/row>/g; + const rowRegex = /]*\/>|]*>[\s\S]*?<\/row>/g; let rMatch: RegExpExecArray | null; while ((rMatch = rowRegex.exec(sXml)) !== null) { const rowXml = rMatch[0]; @@ -933,13 +933,16 @@ async function extractOdf(entries: Map Promise>): Prom while ((trMatch = trRegex.exec(block)) !== null) { const tr = trMatch[0]; const cells: string[] = []; - const tcRegex = /]*\/>|/g; + const tcRegex = /]*?)\/>|]*)>([\s\S]*?)<\/table:(?:covered-)?table-cell>/g; let tcMatch: RegExpExecArray | null; while ((tcMatch = tcRegex.exec(tr)) !== null) { - const tc = tcMatch[0]; - const text = tc.endsWith("/>") ? "" : tc.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim(); - cells.push(decodeXmlEntities(text)); + const attrs = tcMatch[1] ?? tcMatch[2] ?? ""; + const body = tcMatch[3] ?? ""; + const text = decodeXmlEntities(body.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim()); + const repeat = Math.min(Math.max(Number(/table:number-columns-repeated="(\d+)"/.exec(attrs)?.[1] ?? 1), 1), 64); + for (let i = 0; i < repeat; i++) cells.push(text); } + while (cells.length > 0 && cells[cells.length - 1] === "") cells.pop(); if (cells.length > 0) rows.push(cells); } if (rows.length > 0) { From e714d726a83a22128ae41efa1046f5a25db4bd10 Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Tue, 27 Oct 2026 20:56:55 +0800 Subject: [PATCH 04/13] fix(chat-attachments): bound ODF output size before table construction --- lib/chat-attachments.test.mjs | 28 ++++++++++++++++++++++++++++ lib/chat-attachments.ts | 29 +++++++++++++++++++++++++++-- 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/lib/chat-attachments.test.mjs b/lib/chat-attachments.test.mjs index 0337375ca..2210c9845 100644 --- a/lib/chat-attachments.test.mjs +++ b/lib/chat-attachments.test.mjs @@ -764,6 +764,34 @@ test("readAttachmentText expands odf repeated columns and trims trailing empty c assert.doesNotMatch(result, /\| Middle \|(?:\s*\|){5,}/); }); +test("readAttachmentText rejects odf spreadsheet exceeding output byte budget via repeated cells", async () => { + const { readAttachmentText } = await loadSubject(); + + // Each row has repeated cells with non-empty text, expanding beyond 4 MiB + const cellText = "A".repeat(1000); + const rowXml = `${cellText}`; + // 64 * 1003 bytes ~ 64 KB per row; 70 rows > 4.4 MB (> 4 MiB MAX_ATTACHED_TEXT_BYTES) + const rowsXml = rowXml.repeat(70); + + const odsZip = createZip([ + { + name: "content.xml", + data: ` + + + + ${rowsXml} + + + + `, + }, + ]); + + const result = await readAttachmentText(mockFile("huge-repeated.ods", "application/vnd.oasis.opendocument.spreadsheet", odsZip)); + assert.strictEqual(result, null); +}); + test("enforces text byte budget on extracted text byte length", async () => { const { selectTextAttachments, diff --git a/lib/chat-attachments.ts b/lib/chat-attachments.ts index 5e8311b08..886030f36 100644 --- a/lib/chat-attachments.ts +++ b/lib/chat-attachments.ts @@ -921,6 +921,8 @@ async function extractOdf(entries: Map Promise>): Prom const buf = await contentFn(); const xml = new TextDecoder("utf-8").decode(buf); + const encoder = new TextEncoder(); + let outputBytes = 0; const parts: string[] = []; const blockRegex = /||/g; let m: RegExpExecArray | null; @@ -940,13 +942,31 @@ async function extractOdf(entries: Map Promise>): Prom const body = tcMatch[3] ?? ""; const text = decodeXmlEntities(body.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim()); const repeat = Math.min(Math.max(Number(/table:number-columns-repeated="(\d+)"/.exec(attrs)?.[1] ?? 1), 1), 64); + const escaped = text.replace(/\|/g, "\\|").replace(/\n/g, " "); + if (escaped.length > 0) { + const cellBytes = encoder.encode(escaped).byteLength + 3; + outputBytes += repeat * cellBytes; + if (outputBytes > MAX_ATTACHED_TEXT_BYTES) return null; + } for (let i = 0; i < repeat; i++) cells.push(text); } while (cells.length > 0 && cells[cells.length - 1] === "") cells.pop(); - if (cells.length > 0) rows.push(cells); + if (cells.length > 0) { + for (const c of cells) { + if (c === "") outputBytes += 3; + } + outputBytes += 2; + if (outputBytes > MAX_ATTACHED_TEXT_BYTES) return null; + rows.push(cells); + } } if (rows.length > 0) { const maxCols = Math.max(...rows.map((r) => r.length)); + outputBytes += 2 + maxCols * 6; + for (const r of rows) { + outputBytes += (maxCols - r.length) * 3; + } + if (outputBytes > MAX_ATTACHED_TEXT_BYTES) return null; const formattedRows = rows.map((r) => { const padded = [...r]; while (padded.length < maxCols) padded.push(""); @@ -958,7 +978,12 @@ async function extractOdf(entries: Map Promise>): Prom } } else { const text = block.replace(/<[^>]+>/g, "").trim(); - if (text) parts.push(decodeXmlEntities(text)); + if (text) { + const decoded = decodeXmlEntities(text); + outputBytes += encoder.encode(decoded).byteLength + 2; + if (outputBytes > MAX_ATTACHED_TEXT_BYTES) return null; + parts.push(decoded); + } } } const res = parts.join("\n\n").trim(); From 130873512784313c5b1c3894049136c98c273721 Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Tue, 27 Oct 2026 23:39:11 +0800 Subject: [PATCH 05/13] fix(chat-attachments): bound XLSX output size and recheck aggregate budget post-read --- .../ChatInput.queue-attachments.test.mjs | 47 +++++++++++++++++++ components/ChatInput.tsx | 14 ++++-- lib/chat-attachments.test.mjs | 33 +++++++++++++ lib/chat-attachments.ts | 30 +++++++++++- 4 files changed, 119 insertions(+), 5 deletions(-) diff --git a/components/ChatInput.queue-attachments.test.mjs b/components/ChatInput.queue-attachments.test.mjs index 0d35f9ca6..d547ec5cb 100644 --- a/components/ChatInput.queue-attachments.test.mjs +++ b/components/ChatInput.queue-attachments.test.mjs @@ -1034,3 +1034,50 @@ for (const holdUpload of [false, true]) { await waitFor(() => assert.equal(getDraft(targetKey), null)); }); } + +test("drops candidates expanding beyond per-file and aggregate limits post-read", async () => { + const { MAX_ATTACHED_TEXT_BYTES, MAX_TOTAL_ATTACHED_TEXT_BYTES } = await jiti.import("@/lib/chat-attachments"); + const ref = React.createRef(); + render(React.createElement(ChatInput, { + ref, + draftKey: "budget-check-test", + isStreaming: false, + onSend: async () => ({ status: "accepted" }), + })); + + // Mock readAttachmentText expansion behavior by providing a file whose read text expands past MAX_ATTACHED_TEXT_BYTES + // In jsdom / test environment, File.text() returns the file content + const hugeContent = "A".repeat(MAX_ATTACHED_TEXT_BYTES + 100); + const hugeFile = new File([hugeContent], "huge.txt", { type: "text/plain" }); + // Override size on the File object so it passes initial selectTextAttachments (pre-read) + Object.defineProperty(hugeFile, "size", { value: 100, configurable: true }); + + await act(async () => { + ref.current.addFiles([hugeFile]); + }); + + await waitFor(() => { + const draft = getDraft("budget-check-test"); + assert.equal(draft?.files?.length ?? 0, 0, "oversized post-read file is rejected"); + }); + + // Now test aggregate budget enforcement post-read + const fitsBytes = Math.floor(MAX_TOTAL_ATTACHED_TEXT_BYTES * 0.6); + const file1Content = "B".repeat(fitsBytes); + const file1 = new File([file1Content], "file1.txt", { type: "text/plain" }); + Object.defineProperty(file1, "size", { value: 100, configurable: true }); + + const file2Content = "C".repeat(fitsBytes); + const file2 = new File([file2Content], "file2.txt", { type: "text/plain" }); + Object.defineProperty(file2, "size", { value: 100, configurable: true }); + + await act(async () => { + ref.current.addFiles([file1, file2]); + }); + + await waitFor(() => { + const draft = getDraft("budget-check-test"); + assert.equal(draft?.files?.length, 1, "only file fitting within aggregate limit is retained"); + assert.equal(draft.files[0].name, "file1.txt"); + }); +}); diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index f09104a42..f8949fd47 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -714,9 +714,17 @@ export const ChatInput = memo(forwardRef(function ChatIn const totalOverBudget = overBudget + extractedOverBudget; setAttachedTextFiles((prev) => { - const accepted = identityRevision !== attachmentIdentityRevisionRef.current - ? validTextFiles - : validTextFiles.slice(0, Math.max(0, MAX_ATTACHED_TEXT_FILES - prev.length)); + if (identityRevision !== attachmentIdentityRevisionRef.current) { + return [...prev, ...validTextFiles]; + } + let committedBytes = prev.reduce((total, file) => total + file.size, 0); + const accepted = validTextFiles + .filter((file) => { + if (committedBytes + file.size > MAX_TOTAL_ATTACHED_TEXT_BYTES) return false; + committedBytes += file.size; + return true; + }) + .slice(0, Math.max(0, MAX_ATTACHED_TEXT_FILES - prev.length)); return [...prev, ...accepted]; }); diff --git a/lib/chat-attachments.test.mjs b/lib/chat-attachments.test.mjs index 2210c9845..5eb8b5d99 100644 --- a/lib/chat-attachments.test.mjs +++ b/lib/chat-attachments.test.mjs @@ -792,6 +792,39 @@ test("readAttachmentText rejects odf spreadsheet exceeding output byte budget vi assert.strictEqual(result, null); }); +test("readAttachmentText rejects xlsx exceeding output byte budget via repeated shared strings", async () => { + const { readAttachmentText } = await loadSubject(); + + const sharedString = "B".repeat(10000); + // 500 rows referencing the 10KB shared string -> 5 MB (> 4 MiB MAX_ATTACHED_TEXT_BYTES) + let rowsXml = ""; + for (let r = 1; r <= 500; r++) { + rowsXml += `0`; + } + + const xlsxZip = createZip([ + { + name: "xl/sharedStrings.xml", + data: `${sharedString}`, + }, + { + name: "xl/workbook.xml", + data: ``, + }, + { + name: "xl/_rels/workbook.xml.rels", + data: ``, + }, + { + name: "xl/worksheets/sheet1.xml", + data: `${rowsXml}`, + }, + ]); + + const result = await readAttachmentText(mockFile("huge-shared-strings.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xlsxZip)); + assert.strictEqual(result, null); +}); + test("enforces text byte budget on extracted text byte length", async () => { const { selectTextAttachments, diff --git a/lib/chat-attachments.ts b/lib/chat-attachments.ts index 886030f36..c68889d07 100644 --- a/lib/chat-attachments.ts +++ b/lib/chat-attachments.ts @@ -777,9 +777,10 @@ async function extractXlsx(entries: Map Promise>): Pro sheets.push({ name, target }); } } - const sections: string[] = []; const visitedSheets = new Set(); + const encoder = new TextEncoder(); + let projectedBytes = 0; for (let i = 0; i < sheets.length; i++) { const { name, target } = sheets[i]; const path = target || `xl/worksheets/sheet${i + 1}.xml`; @@ -829,7 +830,12 @@ async function extractXlsx(entries: Map Promise>): Pro const vMatch = body.match(/([\s\S]*?)<\/v>/); if (vMatch) val = decodeXmlEntities(vMatch[1]); } - cells.set(colNum, val.trim()); + const trimmed = val.trim(); + if (trimmed) { + projectedBytes += encoder.encode(trimmed).byteLength; + if (projectedBytes > MAX_ATTACHED_TEXT_BYTES) return null; + } + cells.set(colNum, trimmed); } if (maxCol > 0) { const rowList: string[] = []; @@ -842,6 +848,26 @@ async function extractXlsx(entries: Map Promise>): Pro if (rows.length > 0) { const maxCols = Math.max(...rows.map((r) => r.length)); + // Heading: "### ${name}\n\n" + let sheetBytes = encoder.encode(`### ${name}\n\n`).byteLength; + // Separator row: "| --- | ... |" -> 2 + maxCols * 6 + 1 (\n) + sheetBytes += 2 + maxCols * 6 + 1; + // Format data rows and calculate byte size + for (const r of rows) { + let rowContentBytes = 0; + for (const c of r) { + const escaped = c.replace(/\|/g, "\\|").replace(/\n/g, " "); + rowContentBytes += encoder.encode(escaped).byteLength; + } + // "| " + joined + " |\n" -> 2 + rowContentBytes + (r.length - 1) * 3 + (maxCols - r.length) * 3 + 2 + 1 + // = rowContentBytes + maxCols * 3 + 2 (outer pipes/spaces) + 1 (\n) + sheetBytes += rowContentBytes + maxCols * 3 + 3; + } + // Section separator: "\n\n" between sections + sheetBytes += 2; + projectedBytes += sheetBytes; + if (projectedBytes > MAX_ATTACHED_TEXT_BYTES) return null; + const formattedRows = rows.map((r) => { const padded = [...r]; while (padded.length < maxCols) padded.push(""); From 9ac8858e3b79c46a4421f2464fdf0b762148982c Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Tue, 27 Oct 2026 23:42:55 +0800 Subject: [PATCH 06/13] fix(chat-attachments): avoid double counting cell bytes in extractXlsx projected size --- lib/chat-attachments.ts | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/lib/chat-attachments.ts b/lib/chat-attachments.ts index c68889d07..4faaa684f 100644 --- a/lib/chat-attachments.ts +++ b/lib/chat-attachments.ts @@ -791,6 +791,7 @@ async function extractXlsx(entries: Map Promise>): Pro const sBuf = await sFn(); const sXml = new TextDecoder("utf-8").decode(sBuf); const rows: string[][] = []; + let rawCellBytes = 0; const rowRegex = /]*\/>|]*>[\s\S]*?<\/row>/g; let rMatch: RegExpExecArray | null; while ((rMatch = rowRegex.exec(sXml)) !== null) { @@ -832,8 +833,8 @@ async function extractXlsx(entries: Map Promise>): Pro } const trimmed = val.trim(); if (trimmed) { - projectedBytes += encoder.encode(trimmed).byteLength; - if (projectedBytes > MAX_ATTACHED_TEXT_BYTES) return null; + rawCellBytes += encoder.encode(trimmed).byteLength; + if (projectedBytes + rawCellBytes > MAX_ATTACHED_TEXT_BYTES) return null; } cells.set(colNum, trimmed); } @@ -863,11 +864,9 @@ async function extractXlsx(entries: Map Promise>): Pro // = rowContentBytes + maxCols * 3 + 2 (outer pipes/spaces) + 1 (\n) sheetBytes += rowContentBytes + maxCols * 3 + 3; } - // Section separator: "\n\n" between sections - sheetBytes += 2; - projectedBytes += sheetBytes; - if (projectedBytes > MAX_ATTACHED_TEXT_BYTES) return null; - + const sectionSeparatorBytes = sections.length > 0 ? 2 : 0; + if (projectedBytes + sectionSeparatorBytes + sheetBytes > MAX_ATTACHED_TEXT_BYTES) return null; + projectedBytes += sectionSeparatorBytes + sheetBytes; const formattedRows = rows.map((r) => { const padded = [...r]; while (padded.length < maxCols) padded.push(""); From 77402052e77b94f9b35f3479e305d01c600f5a7f Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Fri, 30 Oct 2026 11:39:51 +0800 Subject: [PATCH 07/13] feat(chat-attachments): sort PDF text runs by (Y, X) coordinates and space TJ/Td table cells --- lib/chat-attachments.test.mjs | 21 +++ lib/chat-attachments.ts | 265 ++++++++++++++++++++++++++++++---- 2 files changed, 260 insertions(+), 26 deletions(-) diff --git a/lib/chat-attachments.test.mjs b/lib/chat-attachments.test.mjs index 5eb8b5d99..2d3fe5ea1 100644 --- a/lib/chat-attachments.test.mjs +++ b/lib/chat-attachments.test.mjs @@ -623,6 +623,27 @@ test("readAttachmentText separates lines for PDF Td and positioning operators", assert.equal(result, "First line\nSecond line\nThird line"); }); +test("readAttachmentText sorts out-of-order PDF table columns by (Y, X) and spaces TJ cells", async () => { + const { readAttachmentText } = await loadSubject(); + + // Simulate an Excel-exported PDF where ASCII columns are drawn first via TJ negative kerning + // and a middle column (dates) is drawn in a subsequent BT...ET block at the same Y coordinates. + const tablePdf = createPdf({ + text: [ + "1 0 0 1 20 700 Tm [(0653) -4500 (265W36507D) -1200 (S1-300) -20 (A)] TJ", + "1 0 0 1 20 680 Tm [(0654) -4500 (264W365059) -1200 (S3-300)] TJ", + "ET", + "BT /F1 12 Tf", + "1 0 0 1 55 700 Tm (10/08) Tj", + "1 0 0 1 55 680 Tm (10/14) Tj", + ].join("\n"), + withToUnicode: false, + useFlate: true, + }); + const result = await readAttachmentText(mockFile("table.pdf", "application/pdf", tablePdf)); + assert.equal(result, "0653 10/08 265W36507D S1-300A\n0654 10/14 264W365059 S3-300"); +}); + test("readAttachmentText extracts xlsx with absolute relationship target path", async () => { const { readAttachmentText } = await loadSubject(); diff --git a/lib/chat-attachments.ts b/lib/chat-attachments.ts index 4faaa684f..496571f13 100644 --- a/lib/chat-attachments.ts +++ b/lib/chat-attachments.ts @@ -557,40 +557,253 @@ async function extractPdfText(buf: ArrayBuffer): Promise { return fallbackCMap; }; + type Mat2D = [number, number, number, number, number, number]; + const mulMat = (m1: Mat2D, m2: Mat2D): Mat2D => [ + m1[0] * m2[0] + m1[1] * m2[2], + m1[0] * m2[1] + m1[1] * m2[3], + m1[2] * m2[0] + m1[3] * m2[2], + m1[2] * m2[1] + m1[3] * m2[3], + m1[4] * m2[0] + m1[5] * m2[2] + m2[4], + m1[4] * m2[1] + m1[5] * m2[3] + m2[5], + ]; + const estimateTextAdvance = ( + str: string, + fontSize: number, + charSpacing: number, + wordSpacing: number, + horizScale: number, + ): number => { + let adv = 0; + for (let i = 0; i < str.length; i++) { + const cp = str.codePointAt(i)!; + if (cp > 0xffff) i++; + const glyphW = cp >= 0x2e80 ? 1.0 : 0.52; + adv += (glyphW * fontSize + charSpacing + (cp === 0x20 ? wordSpacing : 0)) * horizScale; + } + return adv; + }; + + interface PdfTextRun { + text: string; + x: number; + y: number; + width: number; + fontSize: number; + btId: number; + forcedSpace: boolean; + seq: number; + } + const lines: string[] = []; + let globalSeq = 0; + let globalBtId = 0; + const streamTokenRe = + /\/([A-Za-z0-9_.-]+)|\((?:\\[\s\S]|[^\\()])*\)|<([0-9a-fA-F\s]+)>|(\[|\])|([-+]?(?:\d+\.?\d*|\.\d+))|(\b(?:BT|ET|Tf|Tm|Td|TD|TL|Tc|Tw|Tz|cm|q|Q|Tj|TJ)\b|\bT\*|['"])|\b([A-Za-z*]+)\b/g; + for (const [, obj] of objects) { if (!obj.streamText || !obj.streamText.includes("BT") || obj.streamText.includes("begincmap")) continue; + let ctm: Mat2D = [1, 0, 0, 1, 0, 0]; + const ctmStack: Mat2D[] = []; + let tmMat: Mat2D = [1, 0, 0, 1, 0, 0]; + let tlmMat: Mat2D = [1, 0, 0, 1, 0, 0]; let currentFont: string | null = null; - const btStartRe = /\bBT\b/g; - const etRe = /\bET\b/g; - let bm: RegExpExecArray | null; - while ((bm = btStartRe.exec(obj.streamText)) !== null) { - const blockStart = bm.index + bm[0].length; - etRe.lastIndex = blockStart; - const etMatch = etRe.exec(obj.streamText); - if (!etMatch) break; - btStartRe.lastIndex = etMatch.index + etMatch[0].length; - const block = obj.streamText.slice(blockStart, etMatch.index); - let chunk = ""; - const tokenRe = /\/([A-Za-z0-9_.-]+)\s+[-+\d.]+\s+Tf|\((?:\\[\s\S]|[^\\()])*\)|<([0-9a-fA-F\s]+)>|(\b(?:Td|TD|Tm)\b|\bT\*|['"])/g; - let tm: RegExpExecArray | null; - while ((tm = tokenRe.exec(block)) !== null) { - if (tm[1]) { - currentFont = tm[1]; - } else if (tm[0].startsWith("(")) { - const bytes = decodePdfLiteralBytes(tm[0].slice(1, -1)); - chunk += decodeBytesWithPdfCMap(bytes, resolveFontCMap(currentFont)); - } else if (tm[2] !== undefined) { - const bytes = decodePdfHexBytes(tm[2]); - chunk += decodeBytesWithPdfCMap(bytes, resolveFontCMap(currentFont)); - } else if (tm[3]) { - if (chunk && !chunk.endsWith("\n")) chunk += "\n"; + let pendingName: string | null = null; + let fontSize = 10; + let leading = 0; + let charSpacing = 0; + let wordSpacing = 0; + let horizScale = 1; + let inText = false; + let inTjArray = false; + let currentBtId = 0; + let nextForcedSpace = false; + const numStack: number[] = []; + const pageRuns: PdfTextRun[] = []; + let activeRun: PdfTextRun | null = null; + + const flushRun = () => { + if (activeRun) { + if (activeRun.text) pageRuns.push(activeRun); + activeRun = null; + } + }; + + const appendDecodedText = (decoded: string) => { + if (!decoded) return; + const dev = mulMat(tmMat, ctm); + const effFontSize = Math.max(4, fontSize * (Math.hypot(dev[0], dev[1]) || Math.hypot(dev[2], dev[3]) || 1)); + const advText = estimateTextAdvance(decoded, fontSize, charSpacing, wordSpacing, horizScale); + const advDev = advText * (Math.hypot(dev[0], dev[1]) || 1); + if (!activeRun) { + activeRun = { + text: decoded, + x: dev[4], + y: dev[5], + width: advDev, + fontSize: effFontSize, + btId: currentBtId, + forcedSpace: nextForcedSpace, + seq: globalSeq++, + }; + nextForcedSpace = false; + } else { + activeRun.text += decoded; + activeRun.width += advDev; + } + tmMat = mulMat([1, 0, 0, 1, advText, 0], tmMat); + }; + + streamTokenRe.lastIndex = 0; + let tok: RegExpExecArray | null; + while ((tok = streamTokenRe.exec(obj.streamText)) !== null) { + if (tok[1] !== undefined) { + pendingName = tok[1]; + } else if (tok[0].startsWith("(")) { + if (inText) { + const bytes = decodePdfLiteralBytes(tok[0].slice(1, -1)); + appendDecodedText(decodeBytesWithPdfCMap(bytes, resolveFontCMap(currentFont))); + } + } else if (tok[2] !== undefined) { + if (inText) { + const bytes = decodePdfHexBytes(tok[2]); + appendDecodedText(decodeBytesWithPdfCMap(bytes, resolveFontCMap(currentFont))); + } + } else if (tok[3] !== undefined) { + if (tok[3] === "[") { + inTjArray = true; + numStack.length = 0; + } else { + inTjArray = false; + numStack.length = 0; + } + } else if (tok[4] !== undefined) { + const num = parseFloat(tok[4]); + if (Number.isFinite(num)) { + if (inText && inTjArray) { + if (num <= -150) { + flushRun(); + nextForcedSpace = true; + } + tmMat = mulMat([1, 0, 0, 1, (-num / 1000) * fontSize * horizScale, 0], tmMat); + } else { + numStack.push(num); + if (numStack.length > 6) numStack.shift(); + } + } + } else if (tok[5] !== undefined) { + const op = tok[5]; + if (op === "BT") { + flushRun(); + inText = true; + inTjArray = false; + currentBtId = ++globalBtId; + nextForcedSpace = false; + tmMat = [1, 0, 0, 1, 0, 0]; + tlmMat = [1, 0, 0, 1, 0, 0]; + } else if (op === "ET") { + flushRun(); + inText = false; + inTjArray = false; + } else if (op === "Tf") { + if (pendingName) currentFont = pendingName; + const sz = numStack.pop(); + if (sz !== undefined && Number.isFinite(sz)) fontSize = Math.abs(sz) || 10; + } else if (op === "Tm") { + if (numStack.length >= 6) { + const prevDevX = activeRun ? activeRun.x + activeRun.width : null; + flushRun(); + const [a, b, c, d, e, f] = numStack.slice(-6); + tlmMat = [a, b, c, d, e, f]; + tmMat = [a, b, c, d, e, f]; + const newDev = mulMat(tmMat, ctm); + if (prevDevX === null || Math.abs(newDev[4] - prevDevX) > Math.max(1.5, fontSize * 0.12)) { + nextForcedSpace = true; + } + } + } else if (op === "Td" || op === "TD") { + if (numStack.length >= 2) { + const [tx, ty] = numStack.slice(-2); + if (op === "TD") leading = -ty; + const prevDevX = activeRun ? activeRun.x + activeRun.width : null; + flushRun(); + tlmMat = mulMat([1, 0, 0, 1, tx, ty], tlmMat); + tmMat = [...tlmMat] as Mat2D; + const newDev = mulMat(tmMat, ctm); + if (prevDevX === null || Math.abs(newDev[4] - prevDevX) > Math.max(1.5, fontSize * 0.12)) { + nextForcedSpace = true; + } + } + } else if (op === "T*" || op === "'" || op === '"') { + flushRun(); + const dy = -(leading || fontSize * 1.2); + tlmMat = mulMat([1, 0, 0, 1, 0, dy], tlmMat); + tmMat = [...tlmMat] as Mat2D; + nextForcedSpace = false; + } else if (op === "TL") { + const tl = numStack.pop(); + if (tl !== undefined) leading = tl; + } else if (op === "Tc") { + const tc = numStack.pop(); + if (tc !== undefined) charSpacing = tc; + } else if (op === "Tw") { + const tw = numStack.pop(); + if (tw !== undefined) wordSpacing = tw; + } else if (op === "Tz") { + const tz = numStack.pop(); + if (tz !== undefined) horizScale = (tz || 100) / 100; + } else if (op === "cm") { + if (numStack.length >= 6) { + const [a, b, c, d, e, f] = numStack.slice(-6); + ctm = mulMat([a, b, c, d, e, f], ctm); + } + } else if (op === "q") { + ctmStack.push([...ctm] as Mat2D); + } else if (op === "Q") { + if (ctmStack.length > 0) ctm = ctmStack.pop()!; + } + numStack.length = 0; + pendingName = null; + } else if (tok[6] !== undefined) { + numStack.length = 0; + pendingName = null; + } + } + flushRun(); + + if (pageRuns.length > 0) { + pageRuns.sort((a, b) => b.y - a.y || a.x - b.x || a.seq - b.seq); + const rows: { y: number; fontSize: number; runs: PdfTextRun[] }[] = []; + for (const run of pageRuns) { + const lastRow = rows[rows.length - 1]; + const tol = lastRow ? Math.max(2.5, Math.min(lastRow.fontSize, run.fontSize) * 0.45) : 0; + if (lastRow && Math.abs(run.y - lastRow.y) <= tol) { + lastRow.runs.push(run); + } else { + rows.push({ y: run.y, fontSize: run.fontSize, runs: [run] }); } } - if (chunk.trim()) lines.push(chunk.trim()); + for (const row of rows) { + row.runs.sort((a, b) => a.x - b.x || a.seq - b.seq); + let rowText = ""; + let prevRun: PdfTextRun | null = null; + for (const run of row.runs) { + if (!run.text) continue; + if (!prevRun) { + rowText = run.text; + } else { + const gap = run.x - (prevRun.x + prevRun.width); + const needSpace = + !rowText.endsWith(" ") && + !run.text.startsWith(" ") && + (run.btId !== prevRun.btId || run.forcedSpace || gap > Math.max(1.5, prevRun.fontSize * 0.15)); + rowText += (needSpace ? " " : "") + run.text; + } + prevRun = run; + } + if (rowText.trim()) lines.push(rowText.trim()); + } } } - const result = lines.join("\n").replace(/\u0000/g, "").trim(); return result.length > 0 && !result.includes("\uFFFD") ? result : null; } From 36a9801252be03689f909153130e507deaae9631 Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Fri, 30 Oct 2026 11:40:44 +0800 Subject: [PATCH 08/13] fix(chat-attachments): return previous run X from flushRun for strict TS narrowing --- lib/chat-attachments.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/lib/chat-attachments.ts b/lib/chat-attachments.ts index 496571f13..5c538cc68 100644 --- a/lib/chat-attachments.ts +++ b/lib/chat-attachments.ts @@ -621,11 +621,14 @@ async function extractPdfText(buf: ArrayBuffer): Promise { const pageRuns: PdfTextRun[] = []; let activeRun: PdfTextRun | null = null; - const flushRun = () => { + const flushRun = (): number | null => { if (activeRun) { + const endX = activeRun.x + activeRun.width; if (activeRun.text) pageRuns.push(activeRun); activeRun = null; + return endX; } + return null; }; const appendDecodedText = (decoded: string) => { @@ -710,8 +713,7 @@ async function extractPdfText(buf: ArrayBuffer): Promise { if (sz !== undefined && Number.isFinite(sz)) fontSize = Math.abs(sz) || 10; } else if (op === "Tm") { if (numStack.length >= 6) { - const prevDevX = activeRun ? activeRun.x + activeRun.width : null; - flushRun(); + const prevDevX = flushRun(); const [a, b, c, d, e, f] = numStack.slice(-6); tlmMat = [a, b, c, d, e, f]; tmMat = [a, b, c, d, e, f]; @@ -724,8 +726,7 @@ async function extractPdfText(buf: ArrayBuffer): Promise { if (numStack.length >= 2) { const [tx, ty] = numStack.slice(-2); if (op === "TD") leading = -ty; - const prevDevX = activeRun ? activeRun.x + activeRun.width : null; - flushRun(); + const prevDevX = flushRun(); tlmMat = mulMat([1, 0, 0, 1, tx, ty], tlmMat); tmMat = [...tlmMat] as Mat2D; const newDev = mulMat(tmMat, ctm); From e4b13ea097a7dbbf519cc4e7b21f10fcdeda29eb Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:51:40 +0800 Subject: [PATCH 09/13] fix(test): close test block in ChatInput.queue-attachments.test.mjs --- components/ChatInput.queue-attachments.test.mjs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/components/ChatInput.queue-attachments.test.mjs b/components/ChatInput.queue-attachments.test.mjs index fd74e17e5..332d2e3a1 100644 --- a/components/ChatInput.queue-attachments.test.mjs +++ b/components/ChatInput.queue-attachments.test.mjs @@ -1433,6 +1433,8 @@ test("drops candidates expanding beyond per-file and aggregate limits post-read" assert.equal(draft?.files?.length, 1, "only file fitting within aggregate limit is retained"); assert.equal(draft.files[0].name, "file1.txt"); }); +}); + test("a second Enter must not invoke a pending slash builtin twice; success clears unchanged text", async (t) => { override(window.HTMLElement.prototype, "scrollIntoView", () => {}); let finish; From 4e446c4ab6d6508149680cac186e7a0a51c0eec3 Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Sat, 7 Nov 2026 18:28:51 +0800 Subject: [PATCH 10/13] fix(chat): bound XML/XLSX/PDF parsers and preserve As-file uploads for binary documents --- components/ChatInput-draft-attachments.ts | 28 +- .../ChatInput.queue-attachments.test.mjs | 278 +++++ components/ChatInput.tsx | 226 ++-- lib/chat-attachments.test.mjs | 135 +++ lib/chat-attachments.ts | 997 +++++++++++++----- lib/draft-store.ts | 1 + 6 files changed, 1310 insertions(+), 355 deletions(-) diff --git a/components/ChatInput-draft-attachments.ts b/components/ChatInput-draft-attachments.ts index 6a6bbe004..36f4facd6 100644 --- a/components/ChatInput-draft-attachments.ts +++ b/components/ChatInput-draft-attachments.ts @@ -32,19 +32,33 @@ export function draftImagesToAttachedImages(images: ChatDraftImage[] | undefined } export function textFileToDraftFile(file: AttachedTextFile): ChatDraftFile { - return { name: file.name, mimeType: file.mimeType, content: file.content, size: file.size }; + return { + name: file.name, + mimeType: file.mimeType, + content: file.content, + size: file.size, + ...(file.uploadId ? { uploadId: file.uploadId } : {}), + }; } /** Recovery and Edit relocation can merge individually valid drafts past picker * budgets. Keep every well-formed file; sending validates the composed request, * not the picker file-count or text-byte limits. */ export function draftFilesToAttachedFiles(files: ChatDraftFile[] | undefined): AttachedTextFile[] { - return (files ?? []).filter((file) => file !== null && typeof file === "object" - && typeof file.name === "string" - && typeof file.mimeType === "string" - && typeof file.content === "string" - && Number.isFinite(file.size) - && file.size >= 0); + return (files ?? []) + .filter((file) => file !== null && typeof file === "object" + && typeof file.name === "string" + && typeof file.mimeType === "string" + && typeof file.content === "string" + && Number.isFinite(file.size) + && file.size >= 0) + .map((file) => ({ + name: file.name, + mimeType: file.mimeType, + content: file.content, + size: file.size, + ...(file.uploadId ? { uploadId: file.uploadId } : {}), + })); } export function revokeImagePreview(image: AttachedImage): void { diff --git a/components/ChatInput.queue-attachments.test.mjs b/components/ChatInput.queue-attachments.test.mjs index 332d2e3a1..582ecaae4 100644 --- a/components/ChatInput.queue-attachments.test.mjs +++ b/components/ChatInput.queue-attachments.test.mjs @@ -1499,3 +1499,281 @@ test("a completed slash builtin must not erase an attachment added while its cal assert.equal(textbox.value, "/goal keep this draft", "an attachment change preserves the composer text too"); assert.deepEqual(getDraft(KEY), changedDraft, "builtin completion must not erase the newly attached file"); }); + +function createStoredZip(entries) { + function crc32(buf) { + let crc = ~0; + for (let i = 0; i < buf.length; i++) { + crc ^= buf[i]; + for (let j = 0; j < 8; j++) { + crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0); + } + } + return ~crc >>> 0; + } + + const localHeaders = []; + const cdHeaders = []; + let offset = 0; + + for (const entry of entries) { + const nameBuf = Buffer.from(entry.name, "utf-8"); + const dataBuf = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(entry.data, "utf-8"); + const crc = crc32(dataBuf); + const uncompressedSize = dataBuf.length; + const method = 0; + const compressedBuf = dataBuf; + const compressedSize = compressedBuf.length; + + const localHeader = Buffer.alloc(30 + nameBuf.length + compressedBuf.length); + localHeader.writeUInt32LE(0x04034b50, 0); + localHeader.writeUInt16LE(20, 4); + localHeader.writeUInt16LE(0, 6); + localHeader.writeUInt16LE(method, 8); + localHeader.writeUInt16LE(0, 10); + localHeader.writeUInt16LE(0, 12); + localHeader.writeUInt32LE(crc, 14); + localHeader.writeUInt32LE(compressedSize, 18); + localHeader.writeUInt32LE(uncompressedSize, 22); + localHeader.writeUInt16LE(nameBuf.length, 26); + localHeader.writeUInt16LE(0, 28); + nameBuf.copy(localHeader, 30); + compressedBuf.copy(localHeader, 30 + nameBuf.length); + localHeaders.push(localHeader); + + const cdHeader = Buffer.alloc(46 + nameBuf.length); + cdHeader.writeUInt32LE(0x02014b50, 0); + cdHeader.writeUInt16LE(20, 4); + cdHeader.writeUInt16LE(20, 6); + cdHeader.writeUInt16LE(0, 8); + cdHeader.writeUInt16LE(method, 10); + cdHeader.writeUInt16LE(0, 12); + cdHeader.writeUInt16LE(0, 14); + cdHeader.writeUInt32LE(crc, 16); + cdHeader.writeUInt32LE(compressedSize, 20); + cdHeader.writeUInt32LE(uncompressedSize, 24); + cdHeader.writeUInt16LE(nameBuf.length, 28); + cdHeader.writeUInt16LE(0, 30); + cdHeader.writeUInt16LE(0, 32); + cdHeader.writeUInt16LE(0, 34); + cdHeader.writeUInt16LE(0, 36); + cdHeader.writeUInt32LE(0, 38); + cdHeader.writeUInt32LE(offset, 42); + nameBuf.copy(cdHeader, 46); + cdHeaders.push(cdHeader); + + offset += localHeader.length; + } + + const cdTotalSize = cdHeaders.reduce((acc, h) => acc + h.length, 0); + const eocd = Buffer.alloc(22); + eocd.writeUInt32LE(0x06054b50, 0); + eocd.writeUInt16LE(0, 4); + eocd.writeUInt16LE(0, 6); + eocd.writeUInt16LE(entries.length, 8); + eocd.writeUInt16LE(entries.length, 10); + eocd.writeUInt32LE(cdTotalSize, 12); + eocd.writeUInt32LE(offset, 16); + eocd.writeUInt16LE(0, 20); + + return Buffer.concat([...localHeaders, ...cdHeaders, eocd]); +} + +function createDocxBuffer(text = "Hello DOCX") { + const xml = `` + + `` + + `${text}`; + return createStoredZip([ + { name: "word/document.xml", data: Buffer.from(xml, "utf-8") }, + ]); +} + +function createPdfBuffer(text = "Hello PDF") { + const stream = `BT\n/F1 12 Tf\n(${text}) Tj\nET\n`; + return Buffer.from( + `%PDF-1.4\n` + + `1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n` + + `2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n` + + `3 0 obj\n<< /Type /Page /Parent 2 0 R /Contents 4 0 R >>\nendobj\n` + + `4 0 obj\n<< /Length ${Buffer.byteLength(stream)} >>\nstream\n` + + stream + + `endstream\nendobj\n` + + `trailer\n<< /Root 1 0 R >>\n%%EOF` + ); +} + +function setupUploadFetchMock() { + const previousFetch = globalThis.fetch; + override(globalThis, "fetch", async (url, init = {}) => { + const method = init.method ?? "GET"; + const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); + if (url === "/api/uploads" && method === "POST") return json({ received: 0 }); + if (String(url).startsWith("/api/uploads/") && method === "PUT") { + const offset = Number(new URL(String(url), "https://omp.test/").searchParams.get("offset") ?? 0); + return json({ received: offset + (init.body?.size ?? 0), done: true }); + } + if (previousFetch) return previousFetch(url, init); + return json({}); + }); +} + +test("binary documents (report.docx) preserve upload As file while extracting inline text", async () => { + setupUploadFetchMock(); + const user = userEvent.setup(); + const calls = []; + const ref = React.createRef(); + render(React.createElement(ChatInput, { + ref, + draftKey: KEY, + isStreaming: false, + onAbort() {}, + onSend: async (message, images, ...uploads) => { + calls.push({ message, images, uploads }); + return { status: "accepted" }; + }, + })); + + const docxBuf = createDocxBuffer("Extracted docx text"); + await act(async () => { + ref.current.addFiles([ + new File([docxBuf], "report.docx", { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }), + ]); + }); + + // Verify only 1 chip renders (UploadChip, not a duplicate text chip) + await waitFor(() => { + const draft = getDraft(KEY); + assert.equal(draft?.files?.length, 1); + assert.equal(draft?.uploads?.length, 1); + assert.equal(draft?.files[0]?.uploadId, draft?.uploads[0]?.id); + }); + const chips = screen.getAllByText("report.docx"); + assert.equal(chips.length, 1, "only a single UploadChip renders for report.docx"); + + const textbox = screen.getByRole("textbox"); + await user.type(textbox, "check this docx"); + await user.keyboard("{Enter}"); + + await waitFor(() => assert.equal(calls.length, 1)); + assert.match(calls[0].message, /check this docx/); + assert.match(calls[0].message, /Extracted docx text/); + assert.equal(calls[0].uploads?.[0]?.length, 1, "upload argument is present"); +}); + +test("extensionless binary documents preserve upload As file while extracting inline text", async () => { + setupUploadFetchMock(); + const user = userEvent.setup(); + const calls = []; + const ref = React.createRef(); + render(React.createElement(ChatInput, { + ref, + draftKey: KEY, + isStreaming: false, + onAbort() {}, + onSend: async (message, images, ...uploads) => { + calls.push({ message, images, uploads }); + return { status: "accepted" }; + }, + })); + + const docxBuf = createDocxBuffer("Extensionless docx text"); + await act(async () => { + ref.current.addFiles([ + new File([docxBuf], "report", { type: "" }), + ]); + }); + + await waitFor(() => { + const draft = getDraft(KEY); + assert.equal(draft?.files?.length, 1); + assert.equal(draft?.uploads?.length, 1); + assert.equal(draft?.files[0]?.uploadId, draft?.uploads[0]?.id); + }); + const chips = screen.getAllByText("report"); + assert.equal(chips.length, 1, "only a single chip renders for extensionless report"); + + const textbox = screen.getByRole("textbox"); + await user.type(textbox, "check extensionless"); + await user.keyboard("{Enter}"); + + await waitFor(() => assert.equal(calls.length, 1)); + assert.match(calls[0].message, /check extensionless/); + assert.match(calls[0].message, /Extensionless docx text/); + assert.equal(calls[0].uploads?.[0]?.length, 1, "upload argument is present"); +}); + +test("PDF documents (report.pdf and extensionless report) preserve upload As file while extracting inline text", async () => { + setupUploadFetchMock(); + const user = userEvent.setup(); + const calls = []; + const ref = React.createRef(); + render(React.createElement(ChatInput, { + ref, + draftKey: KEY, + isStreaming: false, + onAbort() {}, + onSend: async (message, images, ...uploads) => { + calls.push({ message, images, uploads }); + return { status: "accepted" }; + }, + })); + + const pdfBuf = createPdfBuffer("Extracted PDF content"); + await act(async () => { + ref.current.addFiles([ + new File([pdfBuf], "report.pdf", { type: "application/pdf" }), + ]); + }); + + await waitFor(() => { + const draft = getDraft(KEY); + assert.equal(draft?.files?.length, 1); + assert.equal(draft?.uploads?.length, 1); + assert.equal(draft?.files[0]?.uploadId, draft?.uploads[0]?.id); + }); + const chips = screen.getAllByText("report.pdf"); + assert.equal(chips.length, 1, "only a single chip renders for report.pdf"); + + const textbox = screen.getByRole("textbox"); + await user.type(textbox, "check this pdf"); + await user.keyboard("{Enter}"); + + await waitFor(() => assert.equal(calls.length, 1)); + assert.match(calls[0].message, /check this pdf/); + assert.match(calls[0].message, /Extracted PDF content/); + assert.equal(calls[0].uploads?.[0]?.length, 1, "upload argument is present"); +}); + +test("removing an upload chip also removes paired extracted text file from draft", async () => { + setupUploadFetchMock(); + const ref = React.createRef(); + render(React.createElement(ChatInput, { + ref, + draftKey: KEY, + isStreaming: false, + onAbort() {}, + onSend: async () => ({ status: "accepted" }), + })); + + const docxBuf = createDocxBuffer("To be removed"); + await act(async () => { + ref.current.addFiles([ + new File([docxBuf], "remove-me.docx", { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }), + ]); + }); + + await waitFor(() => { + const draft = getDraft(KEY); + assert.equal(draft?.files?.length, 1); + assert.equal(draft?.uploads?.length, 1); + }); + + const removeBtn = screen.getByLabelText(/chatInput\.removeFile|Remove file/i); + fireEvent.click(removeBtn); + + await waitFor(() => { + const draft = getDraft(KEY); + assert.equal(draft?.files?.length ?? 0, 0, "paired text file removed from draft"); + assert.equal(draft?.uploads?.length ?? 0, 0, "upload removed from draft"); + }); +}); diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 2468b7239..cc531faf3 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -63,7 +63,9 @@ import { CHAT_COLUMN_MAX_WIDTH } from "@/lib/chat-layout"; import { composeMessageWithTextAttachments, inferImageMimeType, + isBinaryDocumentAttachment, isImageAttachmentFile, + isKnownBinaryDocumentMeta, MAX_ATTACHED_TEXT_BYTES, MAX_ATTACHED_TEXT_FILES, MAX_TOTAL_ATTACHED_TEXT_BYTES, @@ -682,9 +684,9 @@ export const ChatInput = memo(forwardRef(function ChatIn }, [patchUpload]); /** Attaches files As file and starts their uploads: up to MAX_UPLOAD_BYTES each, MAX_UPLOADS_PER_MESSAGE in all - * (the only refusals left, spec U2). `previewUrls[i]`: an image's thumbnail, made here when missing. Returns how - * many were attached. */ - const attachAsFiles = useCallback((files: File[], previewUrls: string[] = []): number => { + * (the only refusals left, spec U2). `previewUrls[i]`: an image's thumbnail, made here when missing. Returns + * the attached uploads. */ + const attachAsFiles = useCallback((files: File[], previewUrls: string[] = []): AttachedUpload[] => { const room = Math.max(0, MAX_UPLOADS_PER_MESSAGE - attachedUploadsRef.current.length); const fitting = files.flatMap((file, i) => (file.size <= MAX_UPLOAD_BYTES ? [{ file, previewUrl: previewUrls[i] }] : [])); const added = fitting.slice(0, room).map(({ file, previewUrl }): AttachedUpload => ({ @@ -703,13 +705,13 @@ export const ChatInput = memo(forwardRef(function ChatIn } else if (added.length < fitting.length) { setAttachError(t("chatInput.attachmentUploadLimit", { count: MAX_UPLOADS_PER_MESSAGE })); } - if (added.length === 0) return 0; + if (added.length === 0) return []; markInputEdited(); // Counted at once: another batch in the same tick sees these. attachedUploadsRef.current = [...attachedUploadsRef.current, ...added]; setAttachedUploads((prev) => [...prev, ...added]); added.forEach(runUpload); - return added.length; + return added; }, [markInputEdited, runUpload, t]); /** Whether `bytes` more of images (`extra` more of them) still fit the inline budget the send checks. */ @@ -733,7 +735,7 @@ export const ChatInput = memo(forwardRef(function ChatIn } } const switched = attachAsFiles(asFiles); - if (switched > 0) setAttachNotice(t("chatInput.imagesAsFile", { count: switched })); + if (switched.length > 0) setAttachNotice(t("chatInput.imagesAsFile", { count: switched.length })); if (!imageFiles.length) return; // Admission is a new composer edit now, not only when FileReader finishes: an older ACK must not invalidate it. markInputEdited(); @@ -776,42 +778,60 @@ export const ChatInput = memo(forwardRef(function ChatIn } }, [attachAsFiles, fitsInline, markInputEdited, t]); - /** Text is inlined while it fits the text budget; past it, when it turns out binary, and always for a PDF (omp reads - * it as a document; its decoded bytes are not text), it goes As file. */ + /** Text is inlined while it fits the text budget; past it, when it turns out binary, it goes As file. + * Binary documents (PDF, Office, etc.) are always attached As file, and their text is inlined + * while it fits the budget without showing a duplicate chip. */ const processTextFiles = useCallback(async (files: File[]) => { + if (!files.length) return; + const knownBinaryDocs = files.filter((file) => isKnownBinaryDocumentMeta(file)); + const docUploads = knownBinaryDocs.length ? attachAsFiles(knownBinaryDocs) : []; + const docUploadMap = new Map(); + for (const upload of docUploads) { + if (upload.file) docUploadMap.set(upload.file, upload); + } // In-flight batches reserve their bytes too, so two overlapping drops // cannot each fit under the aggregate budget on their own. - const { accepted: textFiles } = selectTextAttachments(files.filter((file) => file.type !== "application/pdf" && !/\.pdf$/i.test(file.name)), { + const { accepted: acceptedFiles } = selectTextAttachments(files, { usedBytes: attachedTextFilesRef.current.reduce((total, file) => total + file.size, 0) + pendingTextFileBytesRef.current, usedSlots: attachedTextFilesRef.current.length + pendingTextFileCountRef.current, }); - attachAsFiles(files.filter((file) => !textFiles.includes(file))); - if (!textFiles.length) return; + + const rejectedTextCandidates = files.filter((file) => !docUploadMap.has(file) && !acceptedFiles.includes(file)); + if (rejectedTextCandidates.length) { + attachAsFiles(rejectedTextCandidates); + } + + if (!acceptedFiles.length) return; markInputEdited(); const revision = attachmentRevisionRef.current; const identityRevision = attachmentIdentityRevisionRef.current; - const reservedBytes = textFiles.reduce((total, file) => total + file.size, 0); - pendingTextFileCountRef.current += textFiles.length; + const reservedBytes = acceptedFiles.reduce((total, file) => total + file.size, 0); + pendingTextFileCountRef.current += acceptedFiles.length; pendingTextFileBytesRef.current += reservedBytes; try { type ReadCandidate = - | { status: "binary" } - | { status: "text"; file: AttachedTextFile }; + | { status: "binary"; file: File; isDoc: boolean } + | { status: "text"; file: File; isDoc: boolean; attachedFile: AttachedTextFile }; const readFiles = await Promise.all( - textFiles.map(async (file): Promise => { + acceptedFiles.map(async (file): Promise => { const content = await readAttachmentText(file); + const isDoc = docUploadMap.has(file) || await isBinaryDocumentAttachment(file); if (content === null || content.includes("\u0000") || content.includes("\uFFFD")) { - return { status: "binary" }; + return { status: "binary", file, isDoc }; } const contentBytes = new TextEncoder().encode(content).byteLength; + const upload = docUploadMap.get(file); return { status: "text", - file: { + file, + isDoc, + attachedFile: { name: file.name, mimeType: file.type, content, size: contentBytes, + ...(upload ? { uploadId: upload.id } : {}), }, }; }), @@ -819,28 +839,47 @@ export const ChatInput = memo(forwardRef(function ChatIn // The composer was cleared/sent while the reads were in flight — // drop the batch instead of re-appending stale attachments. if (attachmentRevisionRef.current !== revision) return; + const sniffedDocs = readFiles + .filter((candidate) => candidate.isDoc && !docUploadMap.has(candidate.file)) + .map((candidate) => candidate.file); + if (sniffedDocs.length > 0) { + for (const upload of attachAsFiles(sniffedDocs)) { + if (upload.file) docUploadMap.set(upload.file, upload); + } + for (const candidate of readFiles) { + if (candidate.status === "text" && !candidate.attachedFile.uploadId) { + const upload = docUploadMap.get(candidate.file); + if (upload) candidate.attachedFile.uploadId = upload.id; + } + } + } const fallbackAsFiles: File[] = []; const otherInFlightBytes = Math.max(0, pendingTextFileBytesRef.current - reservedBytes); let currentBytes = attachedTextFilesRef.current.reduce((total, file) => total + file.size, 0) + otherInFlightBytes; const validTextFiles: AttachedTextFile[] = []; - for (let i = 0; i < readFiles.length; i++) { - const candidate = readFiles[i]; + for (const candidate of readFiles) { if (candidate.status === "binary") { - fallbackAsFiles.push(textFiles[i]); + if (!candidate.isDoc) { + fallbackAsFiles.push(candidate.file); + } continue; } if ( - candidate.file.size > MAX_ATTACHED_TEXT_BYTES - || currentBytes + candidate.file.size > MAX_TOTAL_ATTACHED_TEXT_BYTES + candidate.attachedFile.size > MAX_ATTACHED_TEXT_BYTES + || currentBytes + candidate.attachedFile.size > MAX_TOTAL_ATTACHED_TEXT_BYTES ) { - fallbackAsFiles.push(textFiles[i]); + if (!candidate.isDoc) { + fallbackAsFiles.push(candidate.file); + } continue; } - currentBytes += candidate.file.size; - validTextFiles.push(candidate.file); + currentBytes += candidate.attachedFile.size; + validTextFiles.push(candidate.attachedFile); + } + if (fallbackAsFiles.length > 0) { + attachAsFiles(fallbackAsFiles); } - attachAsFiles(fallbackAsFiles); setAttachedTextFiles((prev) => { if (identityRevision !== attachmentIdentityRevisionRef.current) { @@ -859,7 +898,7 @@ export const ChatInput = memo(forwardRef(function ChatIn } catch { setAttachError(t("chatInput.attachmentTextReadFailed")); } finally { - pendingTextFileCountRef.current -= textFiles.length; + pendingTextFileCountRef.current -= acceptedFiles.length; pendingTextFileBytesRef.current -= reservedBytes; } }, [attachAsFiles, markInputEdited, t]); @@ -919,9 +958,14 @@ export const ChatInput = memo(forwardRef(function ChatIn setAttachNotice(null); }, [markInputEdited]); - const removeTextFile = useCallback((index: number) => { + const removeTextFile = useCallback((target: number | AttachedTextFile) => { markInputEdited(); - setAttachedTextFiles((prev) => prev.filter((_, fileIndex) => fileIndex !== index)); + setAttachedTextFiles((prev) => { + if (typeof target === "number") { + return prev.filter((_, fileIndex) => fileIndex !== target); + } + return prev.filter((file) => file !== target); + }); setAttachError(null); }, [markInputEdited]); @@ -949,6 +993,7 @@ export const ChatInput = memo(forwardRef(function ChatIn if (removed?.previewUrl) URL.revokeObjectURL(removed.previewUrl); return prev.filter((upload) => upload.id !== id); }); + setAttachedTextFiles((prev) => prev.filter((file) => file.uploadId !== id)); setAttachError(null); setAttachNotice(null); }, [markInputEdited]); @@ -968,7 +1013,7 @@ export const ChatInput = memo(forwardRef(function ChatIn `image.${image.mimeType.slice("image/".length)}`, { type: image.mimeType }, ); - if (!attachAsFiles([file], [image.previewUrl])) return; + if (!attachAsFiles([file], [image.previewUrl]).length) return; setAttachedImages((prev) => prev.filter((each) => each !== image)); }, [attachAsFiles]); @@ -2540,67 +2585,70 @@ export const ChatInput = memo(forwardRef(function ChatIn ))} )} - {(attachedTextFiles.length > 0 || fileUploads.length > 0) && ( -
- {attachedTextFiles.map((file, i) => ( -
- - - - - - - - {file.name} - - - {file.size < 1024 ? `${file.size} B` : `${Math.round(file.size / 1024)} KB`} - - -
- ))} - {fileUploads.map((upload) => ( - removeUpload(upload.id)} onRetry={() => retryUpload(upload.id)} /> - ))} -
- )} + + + + + + + + {file.name} + + + {file.size < 1024 ? `${file.size} B` : `${Math.round(file.size / 1024)} KB`} + + + + ))} + {fileUploads.map((upload) => ( + removeUpload(upload.id)} onRetry={() => retryUpload(upload.id)} /> + ))} + + ); + })()} {/* Main input */}
diff --git a/lib/chat-attachments.test.mjs b/lib/chat-attachments.test.mjs index 67b727199..d73acca12 100644 --- a/lib/chat-attachments.test.mjs +++ b/lib/chat-attachments.test.mjs @@ -882,3 +882,138 @@ test("enforces text byte budget on extracted text byte length", async () => { "1 file(s) skipped: attachments are limited to 4 MB per message.", ); }); + +test("readAttachmentText handles 40,000 unclosed in DOCX in linear time without regex backtracking", async () => { + const { readAttachmentText } = await loadSubject(); + const unclosed = "A".repeat(40_000); + const docxZip = createZip([ + { + name: "word/document.xml", + data: `${unclosed}`, + }, + ]); + const start = performance.now(); + const result = await readAttachmentText(mockFile("unclosed.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", docxZip)); + const elapsed = performance.now() - start; + assert.ok(elapsed < 2000, `Took ${elapsed}ms, expected linear scaling`); + assert.ok(result !== null); + assert.ok(result.length > 0); +}); + +test("readAttachmentText bounds extreme xlsx cell coordinates like ZZZZZZZZ1 without huge allocation", async () => { + const { readAttachmentText } = await loadSubject(); + const sheetData = `0`; + const xlsxZip = createZip([ + { + name: "xl/sharedStrings.xml", + data: `OutOfBounds`, + }, + { + name: "xl/workbook.xml", + data: ``, + }, + { + name: "xl/_rels/workbook.xml.rels", + data: ``, + }, + { + name: "xl/worksheets/sheet1.xml", + data: `${sheetData}`, + }, + ]); + const start = performance.now(); + const result = await readAttachmentText(mockFile("extreme-coord.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xlsxZip)); + const elapsed = performance.now() - start; + assert.ok(elapsed < 1000, `Took ${elapsed}ms`); + assert.strictEqual(result, null); +}); + +test("readAttachmentText rejects sparse huge-column XFD XLSX without large memory allocation", async () => { + const { readAttachmentText } = await loadSubject(); + let rowsXml = ""; + for (let r = 1; r <= 100; r++) { + rowsXml += `${r}`; + } + const xlsxZip = createZip([ + { + name: "xl/workbook.xml", + data: ``, + }, + { + name: "xl/_rels/workbook.xml.rels", + data: ``, + }, + { + name: "xl/worksheets/sheet1.xml", + data: `${rowsXml}`, + }, + ]); + const start = performance.now(); + const result = await readAttachmentText(mockFile("sparse-xfd.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xlsxZip)); + const elapsed = performance.now() - start; + assert.ok(elapsed < 1000, `Took ${elapsed}ms`); + assert.strictEqual(result, null); +}); + +test("readAttachmentText rejects ODF with extreme column repeat counts without allocating huge arrays", async () => { + const { readAttachmentText } = await loadSubject(); + const odsZip = createZip([ + { + name: "content.xml", + data: `Repeat`, + }, + ]); + const start = performance.now(); + const result = await readAttachmentText(mockFile("extreme-repeat.ods", "application/vnd.oasis.opendocument.spreadsheet", odsZip)); + const elapsed = performance.now() - start; + assert.ok(elapsed < 500, `Took ${elapsed}ms`); + assert.strictEqual(result, null); +}); + +test("extractPdfText rejects ObjStm with count exceeding MAX_OBJSTM_OBJECTS or non-monotonic offsets", async () => { + const { readAttachmentText } = await loadSubject(); + + // 1. /N 50000 > MAX_OBJSTM_OBJECTS (2048) + const hugeObjStmStream = Buffer.from("10 0 11 100 << /Type /Font >> << /Type /Font >>"); + const hugeObjStmPdf = Buffer.from( + `%PDF-1.4\n1 0 obj\n<< /Type /ObjStm /N 50000 /First 8 /Length ${hugeObjStmStream.length} >>\nstream\n` + + hugeObjStmStream.toString("binary") + + `\nendstream\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF` + ); + const hugeResult = await readAttachmentText(mockFile("huge-objstm.pdf", "application/pdf", hugeObjStmPdf)); + assert.strictEqual(hugeResult, null); + + // 2. Non-monotonic offsets in ObjStm + // Two objects: obj 10 at offset 50, obj 11 at offset 20 (decreasing) + const badOffsetsStream = Buffer.from("10 50 11 20" + " ".repeat(10) + "hello world content stream data"); + const badOffsetsPdf = Buffer.from( + `%PDF-1.4\n1 0 obj\n<< /Type /ObjStm /N 2 /First 11 /Length ${badOffsetsStream.length} >>\nstream\n` + + badOffsetsStream.toString("binary") + + `\nendstream\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF` + ); + const badOffsetsResult = await readAttachmentText(mockFile("bad-offsets.pdf", "application/pdf", badOffsetsPdf)); + assert.strictEqual(badOffsetsResult, null); +}); + +test("readAttachmentText exhibits parity between extension and extensionless document files", async () => { + const { readAttachmentText } = await loadSubject(); + + // PDF + const pdfBuf = createPdf({ text: "(Parity Test PDF) Tj", withToUnicode: false, useFlate: true }); + const withExtPdf = await readAttachmentText(mockFile("report.pdf", "application/pdf", pdfBuf)); + const noExtPdf = await readAttachmentText(mockFile("report", "", pdfBuf)); + assert.equal(withExtPdf, "Parity Test PDF"); + assert.equal(noExtPdf, "Parity Test PDF"); + + // DOCX + const docxZip = createZip([ + { + name: "word/document.xml", + data: `Parity Test DOCX`, + }, + ]); + const withExtDocx = await readAttachmentText(mockFile("report.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", docxZip)); + const noExtDocx = await readAttachmentText(mockFile("report", "", docxZip)); + assert.equal(withExtDocx, "Parity Test DOCX"); + assert.equal(noExtDocx, "Parity Test DOCX"); +}); diff --git a/lib/chat-attachments.ts b/lib/chat-attachments.ts index 5c538cc68..408cd24b7 100644 --- a/lib/chat-attachments.ts +++ b/lib/chat-attachments.ts @@ -27,6 +27,7 @@ export interface AttachedTextFileData { mimeType: string; content: string; size: number; + uploadId?: string; } /** Extracts lowercased file extension without leading dot. */ @@ -197,10 +198,161 @@ export function decodeXmlEntities(str: string): string { }); } +export const MAX_XML_TAGS = 250_000; +export const MAX_TABLE_COLS = 512; +export const MAX_TABLE_ROWS = 10_000; +export const MAX_TABLE_CELLS = 100_000; +export const MAX_PDF_OBJECTS = 8_192; +export const MAX_OBJSTM_OBJECTS = 2_048; +export const MAX_PDF_STREAM_TOKENS = 200_000; + const MAX_DECOMPRESSED_BYTES = MAX_TOTAL_ATTACHED_TEXT_BYTES * 4; const MAX_CMAP_ENTRIES = 262144; const MAX_CMAP_RANGE_SPAN = 4096; +export interface XmlTagBudget { + tags: number; + maxTags: number; +} + +/** Formats a 2D string array as Markdown table with bounds checking. */ +export function formatMarkdownTable(rows: string[][]): string | null { + if (rows.length === 0) return ""; + if (rows.length > MAX_TABLE_ROWS) return null; + let maxCols = 0; + for (const r of rows) { + if (r.length > MAX_TABLE_COLS) return null; + if (r.length > maxCols) maxCols = r.length; + } + if (maxCols > MAX_TABLE_COLS) return null; + if (rows.length * maxCols > MAX_TABLE_CELLS) return null; + + const formattedRows = rows.map((r) => { + const padded = [...r]; + while (padded.length < maxCols) padded.push(""); + return "| " + padded.map((c) => c.replace(/\|/g, "\\|").replace(/\n/g, " ")).join(" | ") + " |"; + }); + const header = formattedRows[0]; + const separator = "| " + Array(maxCols).fill("---").join(" | ") + " |"; + return [header, separator, ...formattedRows.slice(1)].join("\n"); +} + +/** + * Linear O(N) XML scanner using indexOf("<") and indexOf(">"). + * Enforces shared per-document tag budget. + */ +export function walkXml( + xml: string, + budget: XmlTagBudget, + onTag: (name: string, isClose: boolean, selfClosing: boolean, attrs: string) => boolean | void, + onText?: (text: string) => boolean | void, +): boolean { + let pos = 0; + const len = xml.length; + + while (pos < len) { + const lt = xml.indexOf("<", pos); + if (lt === -1) { + if (onText && pos < len) { + onText(xml.slice(pos)); + } + break; + } + + if (onText && lt > pos) { + if (onText(xml.slice(pos, lt)) === false) return false; + } + + if (xml.startsWith("", lt + 4); + if (endComment === -1) break; + pos = endComment + 3; + continue; + } + + if (xml.startsWith("", lt + 9); + if (endCdata === -1) break; + if (onText) { + if (onText(xml.slice(lt + 9, endCdata)) === false) return false; + } + pos = endCdata + 3; + continue; + } + + if (xml.startsWith("", lt + 2); + if (gt === -1) break; + pos = gt + 1; + continue; + } + + const gt = xml.indexOf(">", lt + 1); + if (gt === -1) break; + + budget.tags++; + if (budget.tags > budget.maxTags) { + return false; + } + + let rawTag = xml.slice(lt + 1, gt).trim(); + const isClose = rawTag.startsWith("/"); + if (isClose) { + rawTag = rawTag.slice(1).trim(); + } + const selfClosing = !isClose && rawTag.endsWith("/"); + if (selfClosing) { + rawTag = rawTag.slice(0, -1).trim(); + } + + let name = rawTag; + let attrs = ""; + const spaceIdx = rawTag.search(/\s/); + if (spaceIdx !== -1) { + name = rawTag.slice(0, spaceIdx); + attrs = rawTag.slice(spaceIdx + 1).trim(); + } + + if (onTag(name, isClose, selfClosing, attrs) === false) { + return false; + } + + pos = gt + 1; + } + + return true; +} + +/** Strips "; + } else if (nextScript !== -1) { + target = nextScript; + closeTag = ""; + } else { + result += html.slice(pos); + break; + } + + result += html.slice(pos, target); + const closeIdx = lower.indexOf(closeTag, target); + if (closeIdx === -1) { + break; + } + pos = closeIdx + closeTag.length; + } + return result; +} interface DecompressBudget { remaining: number; } @@ -293,53 +445,108 @@ function decodeCMapTargetHex(hex: string): string { function parseCMap(cmapStr: string, cmapBudget: DecompressBudget): PdfCMap { const map = new Map(); let codeBytes: 1 | 2 = 1; - const csRegex = /begincodespacerange([\s\S]*?)endcodespacerange/g; - let match: RegExpExecArray | null; - while ((match = csRegex.exec(cmapStr)) !== null) { - const pairs = match[1].match(/<([0-9a-fA-F]+)>\s*<([0-9a-fA-F]+)>/g) ?? []; - for (const pair of pairs) { - const m = pair.match(/<([0-9a-fA-F]+)>/); - if (m && m[1].length >= 4) codeBytes = 2; + const MAX_CMAP_ITERATIONS = 65_536; + let totalEntries = 0; + + let pos = 0; + while (pos < cmapStr.length) { + const startIdx = cmapStr.indexOf("begincodespacerange", pos); + if (startIdx === -1) break; + const contentStart = startIdx + "begincodespacerange".length; + const endIdx = cmapStr.indexOf("endcodespacerange", contentStart); + if (endIdx === -1) break; + const block = cmapStr.slice(contentStart, endIdx); + pos = endIdx + "endcodespacerange".length; + + const pairRegex = /<([0-9a-fA-F]+)>\s*<([0-9a-fA-F]+)>/g; + let pm: RegExpExecArray | null; + while ((pm = pairRegex.exec(block)) !== null) { + if (pm[1].length >= 4) codeBytes = 2; } } - const bfcharRegex = /beginbfchar([\s\S]*?)endbfchar/g; - while ((match = bfcharRegex.exec(cmapStr)) !== null && cmapBudget.remaining > 0) { + pos = 0; + while (pos < cmapStr.length && cmapBudget.remaining > 0 && totalEntries < MAX_CMAP_ITERATIONS) { + const startIdx = cmapStr.indexOf("beginbfchar", pos); + if (startIdx === -1) break; + const contentStart = startIdx + "beginbfchar".length; + const endIdx = cmapStr.indexOf("endbfchar", contentStart); + if (endIdx === -1) break; + const block = cmapStr.slice(contentStart, endIdx); + pos = endIdx + "endbfchar".length; + const pairRegex = /<([0-9a-fA-F]+)>\s*<([0-9a-fA-F]+)>/g; let pm: RegExpExecArray | null; - while ((pm = pairRegex.exec(match[1])) !== null && --cmapBudget.remaining >= 0) { + while ((pm = pairRegex.exec(block)) !== null && --cmapBudget.remaining >= 0 && ++totalEntries <= MAX_CMAP_ITERATIONS) { if (pm[1].length >= 4) codeBytes = 2; map.set(parseInt(pm[1], 16), decodeCMapTargetHex(pm[2])); } } - const bfrangeRegex = /beginbfrange([\s\S]*?)endbfrange/g; - while ((match = bfrangeRegex.exec(cmapStr)) !== null && cmapBudget.remaining > 0) { - const rangeRegex = /<([0-9a-fA-F]+)>\s*<([0-9a-fA-F]+)>\s*(?:<([0-9a-fA-F]+)>|\[([\s\S]*?)\])/g; - let rm: RegExpExecArray | null; - while ((rm = rangeRegex.exec(match[1])) !== null && cmapBudget.remaining > 0) { - if (rm[1].length >= 4) codeBytes = 2; - const start = parseInt(rm[1], 16); - const end = parseInt(rm[2], 16); - if (end < start) continue; - if (rm[3]) { - const baseStr = decodeCMapTargetHex(rm[3]); + pos = 0; + while (pos < cmapStr.length && cmapBudget.remaining > 0 && totalEntries < MAX_CMAP_ITERATIONS) { + const startIdx = cmapStr.indexOf("beginbfrange", pos); + if (startIdx === -1) break; + const contentStart = startIdx + "beginbfrange".length; + const endIdx = cmapStr.indexOf("endbfrange", contentStart); + if (endIdx === -1) break; + const block = cmapStr.slice(contentStart, endIdx); + pos = endIdx + "endbfrange".length; + + let bPos = 0; + while (bPos < block.length && cmapBudget.remaining > 0 && totalEntries < MAX_CMAP_ITERATIONS) { + const lt1 = block.indexOf("<", bPos); + if (lt1 === -1) break; + const gt1 = block.indexOf(">", lt1 + 1); + if (gt1 === -1) break; + const startHex = block.slice(lt1 + 1, gt1); + + const lt2 = block.indexOf("<", gt1 + 1); + if (lt2 === -1) break; + const gt2 = block.indexOf(">", lt2 + 1); + if (gt2 === -1) break; + const endHex = block.slice(lt2 + 1, gt2); + + if (startHex.length >= 4) codeBytes = 2; + const start = parseInt(startHex, 16); + const end = parseInt(endHex, 16); + if (end < start) { + bPos = gt2 + 1; + continue; + } + + let cur = gt2 + 1; + while (cur < block.length && /\s/.test(block[cur])) cur++; + if (cur >= block.length) break; + + if (block[cur] === "<") { + const gt3 = block.indexOf(">", cur + 1); + if (gt3 === -1) break; + const destHex = block.slice(cur + 1, gt3); + bPos = gt3 + 1; + const baseStr = decodeCMapTargetHex(destHex); if (!baseStr) continue; const prefix = baseStr.slice(0, -1); const lastUnit = baseStr.charCodeAt(baseStr.length - 1); const maxEnd = Math.min(end, start + MAX_CMAP_RANGE_SPAN - 1); - for (let code = start; code <= maxEnd && --cmapBudget.remaining >= 0; code++) { + for (let code = start; code <= maxEnd && --cmapBudget.remaining >= 0 && ++totalEntries <= MAX_CMAP_ITERATIONS; code++) { const nextUnit = lastUnit + (code - start); if (nextUnit >= 0xffff) break; if (nextUnit > 0) { map.set(code, prefix + String.fromCharCode(nextUnit)); } } - } else if (rm[4]) { - const items = rm[4].match(/<([0-9a-fA-F]+)>/g) ?? []; - for (let i = 0; i < items.length && start + i <= end && --cmapBudget.remaining >= 0; i++) { + } else if (block[cur] === "[") { + const closeBracket = block.indexOf("]", cur + 1); + if (closeBracket === -1) break; + const arrayContent = block.slice(cur + 1, closeBracket); + bPos = closeBracket + 1; + const items = arrayContent.match(/<([0-9a-fA-F]+)>/g) ?? []; + for (let i = 0; i < items.length && start + i <= end && --cmapBudget.remaining >= 0 && ++totalEntries <= MAX_CMAP_ITERATIONS; i++) { map.set(start + i, decodeCMapTargetHex(items[i].slice(1, -1))); } + } else { + bPos = cur + 1; } } } @@ -439,8 +646,10 @@ async function extractPdfText(buf: ArrayBuffer): Promise { const streamMarkerRe = />>\s*stream(?:\r?\n|\r)/g; const nonTextStreamRe = /\/Subtype\s*\/(?:Image|Type1C|CIDFontType0C|OpenType)\b|\/Length[123]\b|\/Type\s*\/(?:XRef|Metadata|EmbeddedFile)\b|\/BitsPerComponent\b/; const objects = new Map(); + let totalObjStmBytes = 0; let m: RegExpExecArray | null; while ((m = objHeaderRegex.exec(latin1)) !== null) { + if (objects.size >= MAX_PDF_OBJECTS) break; const id = parseInt(m[1], 10); const bodyStart = m.index + m[0].length; const endObjIdx = latin1.indexOf("endobj", bodyStart); @@ -485,14 +694,28 @@ async function extractPdfText(buf: ArrayBuffer): Promise { if (firstMatch && countMatch) { const first = parseInt(firstMatch[1], 10); const count = parseInt(countMatch[1], 10); - const header = streamText.slice(0, first).trim().split(/\s+/).map(Number); + if (first < 0 || first > streamText.length || count < 0 || count > MAX_OBJSTM_OBJECTS) { + return null; + } + const headerStr = streamText.slice(0, first).trim(); + const headerNumbers = headerStr ? headerStr.split(/\s+/).map(Number) : []; + if (headerNumbers.length < count * 2) { + return null; + } const content = streamText.slice(first); - for (let i = 0; i < count && i * 2 + 1 < header.length; i++) { - const objNum = header[i * 2]; - const offset = header[i * 2 + 1]; - const nextOffset = i + 1 < count ? header[(i + 1) * 2 + 1] : content.length; + for (let i = 0; i < count; i++) { + const objNum = headerNumbers[i * 2]; + const offset = headerNumbers[i * 2 + 1]; + const nextOffset = i + 1 < count ? headerNumbers[(i + 1) * 2 + 1] : content.length; + if (!Number.isInteger(objNum) || objNum <= 0) return null; + if (!Number.isInteger(offset) || !Number.isInteger(nextOffset)) return null; + if (!(0 <= offset && offset <= nextOffset && nextOffset <= content.length)) { + return null; + } const subBody = content.slice(offset, nextOffset); - if (!objects.has(objNum)) { + totalObjStmBytes += subBody.length; + if (totalObjStmBytes > MAX_DECOMPRESSED_BYTES) return null; + if (objects.size < MAX_PDF_OBJECTS && !objects.has(objNum)) { objects.set(objNum, { dict: subBody, streamText: null, body: subBody }); } } @@ -514,10 +737,11 @@ async function extractPdfText(buf: ArrayBuffer): Promise { const fontObjIds = new Set(); const fontObjToCMap = new Map(); for (const [id, obj] of objects) { - if (/\/Type\s*\/Font\b/.test(obj.body) || /\/Subtype\s*\/(?:Type0|Type1|TrueType|MMType1|Type3|CIDFontType[02])\b/.test(obj.body)) { + const dictSlice = obj.dict.slice(0, 4096); + if (/\/Type\s*\/Font\b/.test(dictSlice) || /\/Subtype\s*\/(?:Type0|Type1|TrueType|MMType1|Type3|CIDFontType[02])\b/.test(dictSlice)) { fontObjIds.add(id); } - const tu = /\/ToUnicode\s+(\d+)\s+\d+\s+R/.exec(obj.body); + const tu = /\/ToUnicode\s+(\d+)\s+\d+\s+R/.exec(dictSlice); if (tu) { fontObjIds.add(id); const cmap = cmapsByObj.get(parseInt(tu[1], 10)); @@ -527,9 +751,10 @@ async function extractPdfText(buf: ArrayBuffer): Promise { const knownFontNames = new Set(); const fontNameToCMap = new Map(); for (const [, obj] of objects) { + const dictSlice = obj.dict.slice(0, 4096); const fontRefRe = /\/([A-Za-z0-9_.-]+)\s+(\d+)\s+\d+\s+R/g; let fm: RegExpExecArray | null; - while ((fm = fontRefRe.exec(obj.body)) !== null) { + while ((fm = fontRefRe.exec(dictSlice)) !== null) { const targetId = parseInt(fm[2], 10); if (fontObjIds.has(targetId)) { knownFontNames.add(fm[1]); @@ -600,7 +825,9 @@ async function extractPdfText(buf: ArrayBuffer): Promise { const streamTokenRe = /\/([A-Za-z0-9_.-]+)|\((?:\\[\s\S]|[^\\()])*\)|<([0-9a-fA-F\s]+)>|(\[|\])|([-+]?(?:\d+\.?\d*|\.\d+))|(\b(?:BT|ET|Tf|Tm|Td|TD|TL|Tc|Tw|Tz|cm|q|Q|Tj|TJ)\b|\bT\*|['"])|\b([A-Za-z*]+)\b/g; + let totalStreamTokens = 0; for (const [, obj] of objects) { + if (totalStreamTokens >= MAX_PDF_STREAM_TOKENS) break; if (!obj.streamText || !obj.streamText.includes("BT") || obj.streamText.includes("begincmap")) continue; let ctm: Mat2D = [1, 0, 0, 1, 0, 0]; const ctmStack: Mat2D[] = []; @@ -659,6 +886,7 @@ async function extractPdfText(buf: ArrayBuffer): Promise { streamTokenRe.lastIndex = 0; let tok: RegExpExecArray | null; while ((tok = streamTokenRe.exec(obj.streamText)) !== null) { + if (++totalStreamTokens > MAX_PDF_STREAM_TOKENS) break; if (tok[1] !== undefined) { pendingName = tok[1]; } else if (tok[0].startsWith("(")) { @@ -864,25 +1092,6 @@ async function readZipEntries(buffer: ArrayBuffer): Promise Pr return entries; } -/** Extracts plain text from DOCX run XML elements. */ -function extractDocxRuns(containerXml: string): string { - const elemRegex = /][\s\S]*?<\/w:t>|\/>)|]*\/>|]*\/>/g; - let text = ""; - let m: RegExpExecArray | null; - while ((m = elemRegex.exec(containerXml)) !== null) { - const tag = m[0]; - if (tag.startsWith("]*>/, "").replace(/<\/w:t>$/, ""); - text += decodeXmlEntities(content); - } else if (tag.startsWith(" Promise>): Promise { const xmlNames = ["word/document.xml"]; @@ -891,49 +1100,118 @@ async function extractDocx(entries: Map Promise>): Pro xmlNames.push(name); } } + + const tagBudget: XmlTagBudget = { tags: 0, maxTags: MAX_XML_TAGS }; const parts: string[] = []; + for (const name of xmlNames) { const fn = entries.get(name); if (!fn) continue; const buf = await fn(); const xml = new TextDecoder("utf-8").decode(buf); - const blockRegex = /|/g; - let m: RegExpExecArray | null; - while ((m = blockRegex.exec(xml)) !== null) { - const block = m[0]; - if (block.startsWith("/g; - let trMatch: RegExpExecArray | null; - while ((trMatch = trRegex.exec(block)) !== null) { - const tr = trMatch[0]; - const cells: string[] = []; - const tcRegex = //g; - let tcMatch: RegExpExecArray | null; - while ((tcMatch = tcRegex.exec(tr)) !== null) { - const tc = tcMatch[0]; - const text = extractDocxRuns(tc); - cells.push(text.trim()); + + let inTable = false; + let tableRows: string[][] = []; + let currentRow: string[] = []; + let inCell = false; + let cellText = ""; + let inPara = false; + let paraText = ""; + let inT = false; + let totalCellsInTable = 0; + + const ok = walkXml( + xml, + tagBudget, + (tagName, isClose, selfClosing) => { + if (tagName === "w:tbl") { + if (!isClose) { + inTable = true; + tableRows = []; + totalCellsInTable = 0; + } else { + inTable = false; + const tableMd = formatMarkdownTable(tableRows); + if (tableMd === null) return false; + if (tableMd) parts.push(tableMd); + tableRows = []; + } + } else if (tagName === "w:tr") { + if (!isClose) { + if (tableRows.length + 1 > MAX_TABLE_ROWS) return false; + currentRow = []; + } else { + if (currentRow.length > 0) { + tableRows.push(currentRow); + } + } + } else if (tagName === "w:tc") { + if (!isClose) { + if (currentRow.length + 1 > MAX_TABLE_COLS) return false; + if (totalCellsInTable + 1 > MAX_TABLE_CELLS) return false; + totalCellsInTable++; + inCell = true; + cellText = ""; + } else { + inCell = false; + currentRow.push(cellText.trim()); + cellText = ""; + } + } else if (tagName === "w:p") { + if (!isClose) { + if (inPara && !inCell) { + const trimmed = paraText.trim(); + if (trimmed) parts.push(trimmed); + } + inPara = true; + if (!inCell) { + paraText = ""; + } + } else { + inPara = false; + if (!inCell) { + const trimmed = paraText.trim(); + if (trimmed) parts.push(trimmed); + paraText = ""; + } else { + if (cellText && !cellText.endsWith("\n")) { + cellText += " "; + } + } + } + } else if (tagName === "w:t") { + if (!isClose && !selfClosing) { + inT = true; + } else { + inT = false; } - if (cells.length > 0) rows.push(cells); + } else if (tagName === "w:br") { + if (inCell) cellText += "\n"; + else if (inPara) paraText += "\n"; + } else if (tagName === "w:tab") { + if (inCell) cellText += "\t"; + else if (inPara) paraText += "\t"; } - if (rows.length > 0) { - const maxCols = Math.max(...rows.map((r) => r.length)); - const formattedRows = rows.map((r) => { - const padded = [...r]; - while (padded.length < maxCols) padded.push(""); - return "| " + padded.map((c) => c.replace(/\|/g, "\\|").replace(/\n/g, " ")).join(" | ") + " |"; - }); - const header = formattedRows[0]; - const separator = "| " + Array(maxCols).fill("---").join(" | ") + " |"; - parts.push([header, separator, ...formattedRows.slice(1)].join("\n")); + }, + (text) => { + if (inT) { + const decoded = decodeXmlEntities(text); + if (inCell) { + cellText += decoded; + } else if (inPara) { + paraText += decoded; + } } - } else { - const text = extractDocxRuns(block); - if (text.trim()) parts.push(text.trim()); - } + }, + ); + if (inPara && !inCell) { + const trimmed = paraText.trim(); + if (trimmed) parts.push(trimmed); } + + if (!ok) return null; } + const res = parts.join("\n\n").trim(); return res || null; } @@ -941,22 +1219,41 @@ async function extractDocx(entries: Map Promise>): Pro /** Extracts worksheets and shared strings from OOXML XLSX into Markdown tables. */ async function extractXlsx(entries: Map Promise>): Promise { const sharedStrings: string[] = []; + const tagBudget: XmlTagBudget = { tags: 0, maxTags: MAX_XML_TAGS }; + const ssFn = entries.get("xl/sharedStrings.xml"); if (ssFn) { const ssBuf = await ssFn(); const ssXml = new TextDecoder("utf-8").decode(ssBuf); - const siRegex = //g; - let m: RegExpExecArray | null; - while ((m = siRegex.exec(ssXml)) !== null) { - const si = m[0]; - const tRegex = //g; - let tMatch: RegExpExecArray | null; - let text = ""; - while ((tMatch = tRegex.exec(si)) !== null) { - text += tMatch[0].replace(/^]*>/, "").replace(/<\/t>$/, ""); - } - sharedStrings.push(decodeXmlEntities(text)); - } + let inSi = false; + let inT = false; + let siText = ""; + + const ok = walkXml( + ssXml, + tagBudget, + (tagName, isClose, selfClosing) => { + if (tagName === "si") { + if (!isClose) { + inSi = true; + siText = ""; + } else { + inSi = false; + sharedStrings.push(decodeXmlEntities(siText)); + siText = ""; + } + } else if (tagName === "t") { + if (!isClose && !selfClosing) inT = true; + else inT = false; + } + }, + (text) => { + if (inSi && inT) { + siText += text; + } + }, + ); + if (!ok) return null; } const relsFn = entries.get("xl/_rels/workbook.xml.rels"); @@ -991,10 +1288,13 @@ async function extractXlsx(entries: Map Promise>): Pro sheets.push({ name, target }); } } + const sections: string[] = []; const visitedSheets = new Set(); const encoder = new TextEncoder(); let projectedBytes = 0; + let totalCellsAcrossWorkbook = 0; + for (let i = 0; i < sheets.length; i++) { const { name, target } = sheets[i]; const path = target || `xl/worksheets/sheet${i + 1}.xml`; @@ -1004,91 +1304,133 @@ async function extractXlsx(entries: Map Promise>): Pro if (!sFn) continue; const sBuf = await sFn(); const sXml = new TextDecoder("utf-8").decode(sBuf); + const rows: string[][] = []; let rawCellBytes = 0; - const rowRegex = /]*\/>|]*>[\s\S]*?<\/row>/g; - let rMatch: RegExpExecArray | null; - while ((rMatch = rowRegex.exec(sXml)) !== null) { - const rowXml = rMatch[0]; - const cells = new Map(); - let maxCol = 0; - const cRegex = /]*?)\/>|]*)>([\s\S]*?)<\/c>/g; - let cMatch: RegExpExecArray | null; - while ((cMatch = cRegex.exec(rowXml)) !== null) { - const attrs = cMatch[1] ?? cMatch[2] ?? ""; - const body = cMatch[3] || ""; - const rAttr = attrs.match(/\br="([A-Z]+)(\d+)"/); - const tAttr = attrs.match(/\bt="([^"]+)"/); - let colNum = cells.size + 1; - if (rAttr) { - const colStr = rAttr[1]; - let num = 0; - for (let k = 0; k < colStr.length; k++) { - num = num * 26 + (colStr.charCodeAt(k) - 64); + let inRow = false; + let rowCells = new Map(); + let rowMaxCol = 0; + let sheetMaxCol = 0; + let rowCount = 0; + let inCell = false; + let cellColNum = 0; + let cellType = ""; + let inV = false; + let inT = false; + let cellRawText = ""; + + const ok = walkXml( + sXml, + tagBudget, + (tagName, isClose, selfClosing, attrs) => { + if (tagName === "row") { + if (!isClose) { + rowCount++; + if (rowCount > MAX_TABLE_ROWS) return false; + inRow = true; + rowCells = new Map(); + rowMaxCol = 0; + if (selfClosing) { + inRow = false; + } + } else { + inRow = false; + if (rowCount > MAX_TABLE_ROWS || sheetMaxCol > MAX_TABLE_COLS || rowCount * sheetMaxCol > MAX_TABLE_CELLS) { + return false; + } + if (rowMaxCol > 0) { + const rowList: string[] = []; + for (let c = 1; c <= rowMaxCol; c++) { + rowList.push(rowCells.get(c) || ""); + } + rows.push(rowList); + totalCellsAcrossWorkbook += rowMaxCol; + if (totalCellsAcrossWorkbook > MAX_TABLE_CELLS) return false; + } } - colNum = num; - } - maxCol = Math.max(maxCol, colNum); - - let val = ""; - const type = tAttr ? tAttr[1] : ""; - if (type === "s") { - const vMatch = body.match(/(\d+)<\/v>/); - if (vMatch) val = sharedStrings[parseInt(vMatch[1], 10)] ?? ""; - } else if (type === "inlineStr") { - const tMatch = body.match(/]*>([\s\S]*?)<\/t>/); - if (tMatch) val = decodeXmlEntities(tMatch[1]); - } else if (type === "b") { - const vMatch = body.match(/([01])<\/v>/); - if (vMatch) val = vMatch[1] === "1" ? "TRUE" : "FALSE"; - } else { - const vMatch = body.match(/([\s\S]*?)<\/v>/); - if (vMatch) val = decodeXmlEntities(vMatch[1]); - } - const trimmed = val.trim(); - if (trimmed) { - rawCellBytes += encoder.encode(trimmed).byteLength; - if (projectedBytes + rawCellBytes > MAX_ATTACHED_TEXT_BYTES) return null; + } else if (tagName === "c") { + if (!isClose) { + inCell = true; + cellRawText = ""; + const rMatch = attrs.match(/\br="([A-Za-z]+)(\d+)"/); + const tMatch = attrs.match(/\bt="([^"]+)"/); + cellType = tMatch ? tMatch[1] : ""; + + let colNum: number; + if (rMatch) { + const colStr = rMatch[1].toUpperCase(); + if (colStr.length < 1 || colStr.length > 3) return false; + let num = 0; + for (let k = 0; k < colStr.length; k++) { + num = num * 26 + (colStr.charCodeAt(k) - 64); + } + colNum = num; + if (colNum < 1 || colNum > MAX_TABLE_COLS) return false; + } else { + colNum = rowCells.size + 1; + if (colNum > MAX_TABLE_COLS) return false; + } + + cellColNum = colNum; + rowMaxCol = Math.max(rowMaxCol, colNum); + sheetMaxCol = Math.max(sheetMaxCol, rowMaxCol); + + if (rowCount > MAX_TABLE_ROWS || sheetMaxCol > MAX_TABLE_COLS || rowCount * sheetMaxCol > MAX_TABLE_CELLS) { + return false; + } + + if (selfClosing) { + inCell = false; + rowCells.set(cellColNum, ""); + } + } else { + if (inCell) { + inCell = false; + let val = ""; + if (cellType === "s") { + const idx = parseInt(cellRawText.trim(), 10); + val = Number.isFinite(idx) ? sharedStrings[idx] ?? "" : ""; + } else if (cellType === "inlineStr") { + val = decodeXmlEntities(cellRawText); + } else if (cellType === "b") { + val = cellRawText.trim() === "1" ? "TRUE" : "FALSE"; + } else { + val = decodeXmlEntities(cellRawText); + } + const trimmed = val.trim(); + if (trimmed) { + rawCellBytes += encoder.encode(trimmed).byteLength; + if (projectedBytes + rawCellBytes > MAX_ATTACHED_TEXT_BYTES) return false; + } + rowCells.set(cellColNum, trimmed); + } + } + } else if (tagName === "v") { + if (!isClose && !selfClosing) inV = true; + else inV = false; + } else if (tagName === "t") { + if (!isClose && !selfClosing) inT = true; + else inT = false; } - cells.set(colNum, trimmed); - } - if (maxCol > 0) { - const rowList: string[] = []; - for (let c = 1; c <= maxCol; c++) { - rowList.push(cells.get(c) || ""); + }, + (text) => { + if (inCell && (inV || inT)) { + cellRawText += text; } - rows.push(rowList); - } - } + }, + ); + + if (!ok) return null; if (rows.length > 0) { - const maxCols = Math.max(...rows.map((r) => r.length)); - // Heading: "### ${name}\n\n" - let sheetBytes = encoder.encode(`### ${name}\n\n`).byteLength; - // Separator row: "| --- | ... |" -> 2 + maxCols * 6 + 1 (\n) - sheetBytes += 2 + maxCols * 6 + 1; - // Format data rows and calculate byte size - for (const r of rows) { - let rowContentBytes = 0; - for (const c of r) { - const escaped = c.replace(/\|/g, "\\|").replace(/\n/g, " "); - rowContentBytes += encoder.encode(escaped).byteLength; - } - // "| " + joined + " |\n" -> 2 + rowContentBytes + (r.length - 1) * 3 + (maxCols - r.length) * 3 + 2 + 1 - // = rowContentBytes + maxCols * 3 + 2 (outer pipes/spaces) + 1 (\n) - sheetBytes += rowContentBytes + maxCols * 3 + 3; - } + const tableMd = formatMarkdownTable(rows); + if (tableMd === null) return null; + const heading = `### ${name}\n\n`; + const sheetBytes = encoder.encode(heading).byteLength + encoder.encode(tableMd).byteLength; const sectionSeparatorBytes = sections.length > 0 ? 2 : 0; if (projectedBytes + sectionSeparatorBytes + sheetBytes > MAX_ATTACHED_TEXT_BYTES) return null; projectedBytes += sectionSeparatorBytes + sheetBytes; - const formattedRows = rows.map((r) => { - const padded = [...r]; - while (padded.length < maxCols) padded.push(""); - return "| " + padded.map((c) => c.replace(/\|/g, "\\|").replace(/\n/g, " ")).join(" | ") + " |"; - }); - const header = formattedRows[0]; - const separator = "| " + Array(maxCols).fill("---").join(" | ") + " |"; - sections.push(`### ${name}\n\n` + [header, separator, ...formattedRows.slice(1)].join("\n")); + sections.push(heading + tableMd); } } @@ -1112,6 +1454,7 @@ async function extractPptx(entries: Map Promise>): Pro slideEntries.sort((a, b) => a.num - b.num || (a.isNote ? 1 : -1)); + const tagBudget: XmlTagBudget = { tags: 0, maxTags: MAX_XML_TAGS }; const slidesMap = new Map(); for (const item of slideEntries) { if (!slidesMap.has(item.num)) slidesMap.set(item.num, { text: [], notes: [] }); @@ -1119,19 +1462,41 @@ async function extractPptx(entries: Map Promise>): Pro if (!fn) continue; const buf = await fn(); const xml = new TextDecoder("utf-8").decode(buf); - const pRegex = //g; - let pMatch: RegExpExecArray | null; + + let inP = false; + let inT = false; + let pText = ""; const pList: string[] = []; - while ((pMatch = pRegex.exec(xml)) !== null) { - const p = pMatch[0]; - const tRegex = //g; - let tMatch: RegExpExecArray | null; - let text = ""; - while ((tMatch = tRegex.exec(p)) !== null) { - text += tMatch[0].replace(/^]*>/, "").replace(/<\/a:t>$/, ""); - } - if (text.trim()) pList.push(decodeXmlEntities(text.trim())); - } + + const ok = walkXml( + xml, + tagBudget, + (tagName, isClose, selfClosing) => { + if (tagName === "a:p") { + if (!isClose) { + inP = true; + pText = ""; + } else { + inP = false; + const trimmed = pText.trim(); + if (trimmed) pList.push(decodeXmlEntities(trimmed)); + pText = ""; + } + } else if (tagName === "a:t") { + if (!isClose && !selfClosing) inT = true; + else inT = false; + } else if (tagName === "a:br") { + if (inP) pText += "\n"; + } + }, + (text) => { + if (inP && inT) { + pText += text; + } + }, + ); + if (!ok) return null; + if (item.isNote) { slidesMap.get(item.num)!.notes.push(...pList); } else { @@ -1160,71 +1525,111 @@ async function extractOdf(entries: Map Promise>): Prom const buf = await contentFn(); const xml = new TextDecoder("utf-8").decode(buf); + const tagBudget: XmlTagBudget = { tags: 0, maxTags: MAX_XML_TAGS }; const encoder = new TextEncoder(); let outputBytes = 0; const parts: string[] = []; - const blockRegex = /||/g; - let m: RegExpExecArray | null; - while ((m = blockRegex.exec(xml)) !== null) { - const block = m[0]; - if (block.startsWith("/g; - let trMatch: RegExpExecArray | null; - while ((trMatch = trRegex.exec(block)) !== null) { - const tr = trMatch[0]; - const cells: string[] = []; - const tcRegex = /]*?)\/>|]*)>([\s\S]*?)<\/table:(?:covered-)?table-cell>/g; - let tcMatch: RegExpExecArray | null; - while ((tcMatch = tcRegex.exec(tr)) !== null) { - const attrs = tcMatch[1] ?? tcMatch[2] ?? ""; - const body = tcMatch[3] ?? ""; - const text = decodeXmlEntities(body.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim()); - const repeat = Math.min(Math.max(Number(/table:number-columns-repeated="(\d+)"/.exec(attrs)?.[1] ?? 1), 1), 64); - const escaped = text.replace(/\|/g, "\\|").replace(/\n/g, " "); - if (escaped.length > 0) { - const cellBytes = encoder.encode(escaped).byteLength + 3; - outputBytes += repeat * cellBytes; - if (outputBytes > MAX_ATTACHED_TEXT_BYTES) return null; + + let inTable = false; + let tableRows: string[][] = []; + let currentRow: string[] = []; + let inCell = false; + let cellText = ""; + let cellRepeat = 1; + let totalCellsInTable = 0; + + let inPara = false; + let paraText = ""; + + const ok = walkXml( + xml, + tagBudget, + (tagName, isClose, selfClosing, attrs) => { + if (tagName === "table:table") { + if (!isClose) { + inTable = true; + tableRows = []; + totalCellsInTable = 0; + } else { + inTable = false; + if (tableRows.length > 0) { + const tableMd = formatMarkdownTable(tableRows); + if (tableMd === null) return false; + outputBytes += encoder.encode(tableMd).byteLength + 2; + if (outputBytes > MAX_ATTACHED_TEXT_BYTES) return false; + parts.push(tableMd); } - for (let i = 0; i < repeat; i++) cells.push(text); + tableRows = []; } - while (cells.length > 0 && cells[cells.length - 1] === "") cells.pop(); - if (cells.length > 0) { - for (const c of cells) { - if (c === "") outputBytes += 3; + } else if (tagName === "table:table-row") { + if (!isClose) { + if (tableRows.length + 1 > MAX_TABLE_ROWS) return false; + currentRow = []; + } else { + while (currentRow.length > 0 && currentRow[currentRow.length - 1] === "") { + currentRow.pop(); + } + if (currentRow.length > 0) { + tableRows.push(currentRow); } - outputBytes += 2; - if (outputBytes > MAX_ATTACHED_TEXT_BYTES) return null; - rows.push(cells); } - } - if (rows.length > 0) { - const maxCols = Math.max(...rows.map((r) => r.length)); - outputBytes += 2 + maxCols * 6; - for (const r of rows) { - outputBytes += (maxCols - r.length) * 3; + } else if (tagName === "table:table-cell" || tagName === "table:covered-table-cell") { + if (!isClose) { + const repMatch = attrs.match(/\btable:number-columns-repeated="(\d+)"/); + const repeat = repMatch ? Number(repMatch[1]) : 1; + if (repeat > MAX_TABLE_COLS || currentRow.length + repeat > MAX_TABLE_COLS) { + return false; + } + if (totalCellsInTable + repeat > MAX_TABLE_CELLS) { + return false; + } + totalCellsInTable += repeat; + cellRepeat = repeat; + inCell = true; + cellText = ""; + if (selfClosing) { + for (let i = 0; i < cellRepeat; i++) currentRow.push(""); + inCell = false; + } + } else { + inCell = false; + const trimmed = decodeXmlEntities(cellText.trim()); + const escaped = trimmed.replace(/\|/g, "\\|").replace(/\n/g, " "); + for (let i = 0; i < cellRepeat; i++) { + currentRow.push(escaped); + } + cellText = ""; + } + } else if (tagName.startsWith("text:h") || tagName.startsWith("text:p")) { + if (!isClose) { + if (!inTable) { + inPara = true; + paraText = ""; + } + } else { + if (!inTable && inPara) { + inPara = false; + const trimmed = decodeXmlEntities(paraText.trim()); + if (trimmed) { + outputBytes += encoder.encode(trimmed).byteLength + 2; + if (outputBytes > MAX_ATTACHED_TEXT_BYTES) return false; + parts.push(trimmed); + } + paraText = ""; + } } - if (outputBytes > MAX_ATTACHED_TEXT_BYTES) return null; - const formattedRows = rows.map((r) => { - const padded = [...r]; - while (padded.length < maxCols) padded.push(""); - return "| " + padded.map((c) => c.replace(/\|/g, "\\|").replace(/\n/g, " ")).join(" | ") + " |"; - }); - const header = formattedRows[0]; - const separator = "| " + Array(maxCols).fill("---").join(" | ") + " |"; - parts.push([header, separator, ...formattedRows.slice(1)].join("\n")); } - } else { - const text = block.replace(/<[^>]+>/g, "").trim(); - if (text) { - const decoded = decodeXmlEntities(text); - outputBytes += encoder.encode(decoded).byteLength + 2; - if (outputBytes > MAX_ATTACHED_TEXT_BYTES) return null; - parts.push(decoded); + }, + (text) => { + if (inCell) { + cellText += (cellText ? " " : "") + text; + } else if (inPara) { + paraText += (paraText ? " " : "") + text; } - } - } + }, + ); + + if (!ok) return null; const res = parts.join("\n\n").trim(); return res || null; } @@ -1267,8 +1672,10 @@ async function extractEpub(entries: Map Promise>): Pro } } + const tagBudget: XmlTagBudget = { tags: 0, maxTags: MAX_XML_TAGS }; const chapters: string[] = []; const visitedChapters = new Set(); + for (const href of spine) { const fullPath = (basePath + href).replace(/^\//, ""); if (visitedChapters.has(fullPath)) continue; @@ -1277,15 +1684,31 @@ async function extractEpub(entries: Map Promise>): Pro if (!fn) continue; const buf = await fn(); const html = new TextDecoder("utf-8").decode(buf); - const stripped = html - .replace(//gi, "") - .replace(//gi, "") - .replace(//gi, "\n") - .replace(/<\/p>/gi, "\n\n") - .replace(/<\/h[1-6]>/gi, "\n\n") - .replace(/<\/div>/gi, "\n") - .replace(/<[^>]+>/g, ""); - const text = decodeXmlEntities(stripped) + const strippedHtml = stripStyleAndScriptTags(html); + + let chapterText = ""; + const ok = walkXml( + strippedHtml, + tagBudget, + (tagName, isClose, selfClosing) => { + const lowerName = tagName.toLowerCase(); + if (lowerName === "br") { + chapterText += "\n"; + } else if (isClose && lowerName === "p") { + chapterText += "\n\n"; + } else if (isClose && /^h[1-6]$/.test(lowerName)) { + chapterText += "\n\n"; + } else if (isClose && lowerName === "div") { + chapterText += "\n"; + } + }, + (text) => { + chapterText += text; + }, + ); + if (!ok) return null; + + const text = decodeXmlEntities(chapterText) .replace(/\r\n/g, "\n") .replace(/\n{3,}/g, "\n\n") .trim(); @@ -1504,33 +1927,86 @@ const DOCUMENT_ATTACHMENT_MIMES: Record = { "application/epub+zip": true, }; +export function isKnownBinaryDocumentMeta(file: { name: string; type?: string }): boolean { + const ext = getFileExtension(file.name); + if (DOCUMENT_ATTACHMENT_EXTENSIONS[ext] === true) return true; + if (file.type && DOCUMENT_ATTACHMENT_MIMES[file.type] === true) return true; + return false; +} + +export async function isBinaryDocumentAttachment(file: { + name: string; + type?: string; + slice?: (start?: number, end?: number) => Blob; + arrayBuffer?: () => Promise; + text?: () => Promise; +}): Promise { + if (isKnownBinaryDocumentMeta(file)) return true; + try { + let headerBytes: Uint8Array | null = null; + if (typeof file.slice === "function") { + const slice = file.slice(0, 8); + if (slice && typeof slice.arrayBuffer === "function") { + const sliceBuf = await slice.arrayBuffer(); + headerBytes = new Uint8Array(sliceBuf); + } + } + if (!headerBytes && typeof file.arrayBuffer === "function") { + const buf = await file.arrayBuffer(); + headerBytes = new Uint8Array(buf, 0, Math.min(8, buf.byteLength)); + } else if (!headerBytes && typeof file.text === "function") { + const head = await file.text(); + if (head.startsWith("%PDF-") || head.startsWith("PK\u0003\u0004") || head.startsWith("\u00d0\u00cf\u0011\u00e0")) { + return true; + } + } + if (headerBytes && headerBytes.length >= 4) { + if (headerBytes.length >= 5 && headerBytes[0] === 0x25 && headerBytes[1] === 0x50 && headerBytes[2] === 0x44 && headerBytes[3] === 0x46 && headerBytes[4] === 0x2d) { + return true; + } + if (headerBytes[0] === 0x50 && headerBytes[1] === 0x4b && headerBytes[2] === 0x03 && headerBytes[3] === 0x04) { + return true; + } + if (headerBytes[0] === 0xd0 && headerBytes[1] === 0xcf && headerBytes[2] === 0x11 && headerBytes[3] === 0xe0) { + return true; + } + } + } catch { + return false; + } + return false; +} + /** Reads and decodes text content from text files or supported document formats. */ export async function readAttachmentText(file: { name: string; type?: string; - text: () => Promise; + text?: () => Promise; arrayBuffer?: () => Promise; + slice?: (start?: number, end?: number) => Blob; }): Promise { const ext = getFileExtension(file.name); - const isKnownDocument = DOCUMENT_ATTACHMENT_EXTENSIONS[ext] === true - || Boolean(file.type && DOCUMENT_ATTACHMENT_MIMES[file.type] === true); + const isKnownDocument = isKnownBinaryDocumentMeta(file); - // Start non-document reads with file.text() synchronously so callers and - // tests that hold/intercept File.prototype.text observe the read immediately, - // and ordinary UTF-8 files avoid a second buffer allocation. let fallbackText: string | null = null; if (!isKnownDocument && typeof file.text === "function") { const text = await file.text(); - if (!text.includes("\u0000") && !text.includes("\uFFFD")) { + if (text.startsWith("%PDF-") || text.startsWith("PK\u0003\u0004") || text.startsWith("\u00d0\u00cf\u0011\u00e0")) { + fallbackText = text; + } else if (!text.includes("\u0000") && !text.includes("\uFFFD")) { return text; + } else { + fallbackText = text; } - fallbackText = text; } let buffer: ArrayBuffer | null = null; if (typeof file.arrayBuffer === "function") { buffer = await file.arrayBuffer(); + } else if (fallbackText !== null && (fallbackText.startsWith("%PDF-") || fallbackText.startsWith("PK\u0003\u0004") || fallbackText.startsWith("\u00d0\u00cf\u0011\u00e0"))) { + buffer = Uint8Array.from(fallbackText, (c) => c.charCodeAt(0) & 0xff).buffer; } + if (buffer) { const bytes = new Uint8Array(buffer); @@ -1615,7 +2091,10 @@ export async function readAttachmentText(file: { if (fallbackText !== null) { return null; } - const text = await file.text(); - if (text.includes("\u0000") || text.includes("\uFFFD")) return null; - return text; + if (typeof file.text === "function") { + const text = await file.text(); + if (text.includes("\u0000") || text.includes("\uFFFD")) return null; + return text; + } + return null; } diff --git a/lib/draft-store.ts b/lib/draft-store.ts index db5483202..4f076dd14 100644 --- a/lib/draft-store.ts +++ b/lib/draft-store.ts @@ -8,6 +8,7 @@ export interface ChatDraftFile { mimeType: string; content: string; size: number; + uploadId?: string; } /** A finished upload staged on `hostId` (docs/specs/2026-11-02-file-uploads-design.md U2). */ From c49fbc40eb1cbf7af0243c4c08639e13c46b821b Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Sat, 7 Nov 2026 18:38:00 +0800 Subject: [PATCH 11/13] fix(chat): remove unused variables in walkXml document parsers --- lib/chat-attachments.ts | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/lib/chat-attachments.ts b/lib/chat-attachments.ts index 408cd24b7..2368ebd25 100644 --- a/lib/chat-attachments.ts +++ b/lib/chat-attachments.ts @@ -1110,7 +1110,6 @@ async function extractDocx(entries: Map Promise>): Pro const buf = await fn(); const xml = new TextDecoder("utf-8").decode(buf); - let inTable = false; let tableRows: string[][] = []; let currentRow: string[] = []; let inCell = false; @@ -1126,11 +1125,9 @@ async function extractDocx(entries: Map Promise>): Pro (tagName, isClose, selfClosing) => { if (tagName === "w:tbl") { if (!isClose) { - inTable = true; tableRows = []; totalCellsInTable = 0; } else { - inTable = false; const tableMd = formatMarkdownTable(tableRows); if (tableMd === null) return false; if (tableMd) parts.push(tableMd); @@ -1307,7 +1304,6 @@ async function extractXlsx(entries: Map Promise>): Pro const rows: string[][] = []; let rawCellBytes = 0; - let inRow = false; let rowCells = new Map(); let rowMaxCol = 0; let sheetMaxCol = 0; @@ -1327,14 +1323,9 @@ async function extractXlsx(entries: Map Promise>): Pro if (!isClose) { rowCount++; if (rowCount > MAX_TABLE_ROWS) return false; - inRow = true; rowCells = new Map(); rowMaxCol = 0; - if (selfClosing) { - inRow = false; - } } else { - inRow = false; if (rowCount > MAX_TABLE_ROWS || sheetMaxCol > MAX_TABLE_COLS || rowCount * sheetMaxCol > MAX_TABLE_CELLS) { return false; } @@ -1690,7 +1681,7 @@ async function extractEpub(entries: Map Promise>): Pro const ok = walkXml( strippedHtml, tagBudget, - (tagName, isClose, selfClosing) => { + (tagName, isClose) => { const lowerName = tagName.toLowerCase(); if (lowerName === "br") { chapterText += "\n"; From 72e3cc2861549b8d3eec295c143b4d5fb53b20bd Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Tue, 10 Nov 2026 00:38:57 +0800 Subject: [PATCH 12/13] fix(chat): address review feedback for document attachment extraction --- .../ChatInput.queue-attachments.test.mjs | 94 ++++++++ components/ChatInput.tsx | 227 ++++++++++++++---- lib/chat-attachments.test.mjs | 124 ++++++++++ lib/chat-attachments.ts | 175 ++++++++++++-- 4 files changed, 544 insertions(+), 76 deletions(-) diff --git a/components/ChatInput.queue-attachments.test.mjs b/components/ChatInput.queue-attachments.test.mjs index 582ecaae4..5cfcd8b87 100644 --- a/components/ChatInput.queue-attachments.test.mjs +++ b/components/ChatInput.queue-attachments.test.mjs @@ -1777,3 +1777,97 @@ test("removing an upload chip also removes paired extracted text file from draft assert.equal(draft?.uploads?.length ?? 0, 0, "upload removed from draft"); }); }); + +test("removing a document chip while text extraction is in flight discards the extracted text when it resolves", async () => { + setupUploadFetchMock(); + const ref = React.createRef(); + render(React.createElement(ChatInput, { + ref, + draftKey: KEY, + isStreaming: false, + onAbort() {}, + onSend: async () => ({ status: "accepted" }), + })); + + const docxBuf = createDocxBuffer("Slow extracted text"); + let resolveBuffer; + const slowFile = new File([docxBuf], "slow-remove.docx", { + type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + }); + slowFile.arrayBuffer = () => new Promise((resolve) => { + resolveBuffer = () => resolve(docxBuf.buffer.slice(docxBuf.byteOffset, docxBuf.byteOffset + docxBuf.byteLength)); + }); + + await act(async () => { + ref.current.addFiles([slowFile]); + }); + + // Upload chip is visible while extraction is still pending; remove it before extraction resolves. + const removeBtn = await screen.findByLabelText(/chatInput\.removeFile|Remove file/i); + fireEvent.click(removeBtn); + + await act(async () => { + resolveBuffer(); + await new Promise((resolve) => setImmediate(resolve)); + }); + + const draft = getDraft(KEY); + assert.equal(draft?.uploads?.length ?? 0, 0, "upload remains removed"); + assert.equal(draft?.files?.length ?? 0, 0, "late-resolving extracted text is discarded"); +}); + +test("410 upload replacement updates uploadId on paired extracted document text", async () => { + let postCount = 0; + let putCount = 0; + const previousFetch = globalThis.fetch; + override(globalThis, "fetch", async (url, init = {}) => { + const method = init.method ?? "GET"; + const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); + if (url === "/api/uploads" && method === "POST") { + postCount += 1; + return json({ received: 0 }); + } + if (String(url).startsWith("/api/uploads/") && method === "PUT") { + putCount += 1; + if (putCount === 1) { + return json({ error: "expired" }, 410); + } + const offset = Number(new URL(String(url), "https://omp.test/").searchParams.get("offset") ?? 0); + return json({ received: offset + (init.body?.size ?? 0), done: true }); + } + if (previousFetch) return previousFetch(url, init); + return json({}); + }); + + const ref = React.createRef(); + render(React.createElement(ChatInput, { + ref, + draftKey: KEY, + isStreaming: false, + onAbort() {}, + onSend: async () => ({ status: "accepted" }), + })); + + const docxBuf = createDocxBuffer("410 recovered text"); + await act(async () => { + ref.current.addFiles([ + new File([docxBuf], "retry-410.docx", { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }), + ]); + }); + + // After 410, the upload settles to error with a newly minted id; the paired text file's uploadId is updated immediately, + // so there is still only 1 deduplicated chip. Clicking Retry completes the upload under the new id. + const retryBtn = await screen.findByLabelText(/chatInput\.retryUpload|Retry upload/i); + assert.equal(screen.getAllByText("retry-410.docx").length, 1, "single chip during 410 error state"); + fireEvent.click(retryBtn); + + await waitFor(() => { + const draft = getDraft(KEY); + assert.equal(draft?.uploads?.length, 1); + assert.equal(draft?.files?.length, 1); + assert.equal(draft?.files[0]?.uploadId, draft?.uploads[0]?.id, "extracted text uploadId matches replacement upload id"); + }); + assert.ok(postCount >= 2, "retried POST /api/uploads after 410"); + const chips = screen.getAllByText("retry-410.docx"); + assert.equal(chips.length, 1, "still renders a single deduplicated chip after 410 ID replacement"); +}); diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index cc531faf3..9b70ba4b6 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -62,15 +62,18 @@ import { ComposerModeStatus, ModelErrorBanner, QueuedActionButton } from "./Chat import { CHAT_COLUMN_MAX_WIDTH } from "@/lib/chat-layout"; import { composeMessageWithTextAttachments, + describeTextAttachmentSkip, inferImageMimeType, isBinaryDocumentAttachment, isImageAttachmentFile, isKnownBinaryDocumentMeta, MAX_ATTACHED_TEXT_BYTES, MAX_ATTACHED_TEXT_FILES, + MAX_DECOMPRESSED_BYTES, MAX_TOTAL_ATTACHED_TEXT_BYTES, readAttachmentText, selectTextAttachments, + wasOversizedDocumentText, } from "@/lib/chat-attachments"; import { attachedImageBytes, @@ -465,6 +468,7 @@ export const ChatInput = memo(forwardRef(function ChatIn const [attachError, setAttachError] = useState(null); /** An informational note about the last batch (images that went As file). */ const [attachNotice, setAttachNotice] = useState(null); + const [pendingTextReadCount, setPendingTextReadCount] = useState(0); const trimmedValue = value.trimStart(); const bashMode = attachedImages.length === 0 && attachedTextFiles.length === 0 && attachedUploads.length === 0 && trimmedValue.startsWith("!"); const bashExcluded = bashMode && trimmedValue.startsWith("!!"); @@ -652,7 +656,12 @@ export const ChatInput = memo(forwardRef(function ChatIn })); const patchUpload = useCallback((id: string, patch: Partial) => { + attachedUploadsRef.current = attachedUploadsRef.current.map((upload) => (upload.id === id ? { ...upload, ...patch } : upload)); setAttachedUploads((prev) => prev.map((upload) => (upload.id === id ? { ...upload, ...patch } : upload))); + if (patch.id && patch.id !== id) { + attachedTextFilesRef.current = attachedTextFilesRef.current.map((file) => (file.uploadId === id ? { ...file, uploadId: patch.id } : file)); + setAttachedTextFiles((prev) => prev.map((file) => (file.uploadId === id ? { ...file, uploadId: patch.id } : file))); + } }, []); /** Uploads the chip's file to its host; a retry resumes at the host's offset (same id). While a transient failure @@ -698,7 +707,7 @@ export const ChatInput = memo(forwardRef(function ChatIn received: 0, status: "uploading", error: null, - previewUrl: previewUrl ?? (file.type.startsWith("image/") ? URL.createObjectURL(file) : null), + previewUrl: previewUrl ?? (isImageAttachmentFile(file) ? URL.createObjectURL(file) : null), })); if (fitting.length < files.length) { setAttachError(t("chatInput.attachmentUploadTooLarge", { count: files.length - fitting.length, size: `${MAX_UPLOAD_BYTES / 1024 ** 3} GB` })); @@ -773,8 +782,10 @@ export const ChatInput = memo(forwardRef(function ChatIn created.forEach(revokeImagePreview); setAttachError(t("chatInput.attachmentImageReadFailed")); } finally { - pendingImageCountRef.current -= imageFiles.length; - pendingImageBytesRef.current -= inlineBytes; + if (attachmentRevisionRef.current === revision) { + pendingImageCountRef.current = Math.max(0, pendingImageCountRef.current - imageFiles.length); + pendingImageBytesRef.current = Math.max(0, pendingImageBytesRef.current - inlineBytes); + } } }, [attachAsFiles, fitsInline, markInputEdited, t]); @@ -789,25 +800,43 @@ export const ChatInput = memo(forwardRef(function ChatIn for (const upload of docUploads) { if (upload.file) docUploadMap.set(upload.file, upload); } - // In-flight batches reserve their bytes too, so two overlapping drops - // cannot each fit under the aggregate budget on their own. - const { accepted: acceptedFiles } = selectTextAttachments(files, { + // Known binary documents are budgeted by their extracted text size after parsing + // (bounded at MAX_DECOMPRESSED_BYTES), so a >4 MiB PDF with small text is still + // extracted and a 3 MiB DOCX does not displace a 2 MiB plain-text file pre-read. + const preCandidates = files + .filter((file) => !isKnownBinaryDocumentMeta(file) || docUploadMap.has(file)) + .map((file) => { + const isKnownDoc = docUploadMap.has(file); + return { + file, + isKnownDoc, + size: isKnownDoc ? (file.size > MAX_DECOMPRESSED_BYTES ? file.size : 0) : file.size, + }; + }); + const preSelection = selectTextAttachments(preCandidates, { usedBytes: attachedTextFilesRef.current.reduce((total, file) => total + file.size, 0) + pendingTextFileBytesRef.current, usedSlots: attachedTextFilesRef.current.length + pendingTextFileCountRef.current, }); - - const rejectedTextCandidates = files.filter((file) => !docUploadMap.has(file) && !acceptedFiles.includes(file)); + const acceptedFiles = preSelection.accepted.map((candidate) => candidate.file); + const rejectedTextCandidates = files.filter((file) => !isKnownBinaryDocumentMeta(file) && !acceptedFiles.includes(file)); if (rejectedTextCandidates.length) { attachAsFiles(rejectedTextCandidates); } + let skipTooLarge = preCandidates.filter((c) => c.isKnownDoc && c.size > MAX_ATTACHED_TEXT_BYTES).length; + let skipOverBudget = preCandidates.filter((c) => c.isKnownDoc && c.size <= MAX_ATTACHED_TEXT_BYTES && !acceptedFiles.includes(c.file)).length; - if (!acceptedFiles.length) return; + if (!acceptedFiles.length) { + const skipNotice = describeTextAttachmentSkip({ tooLarge: skipTooLarge, overBudget: skipOverBudget }); + if (skipNotice) setAttachNotice(skipNotice); + return; + } markInputEdited(); const revision = attachmentRevisionRef.current; const identityRevision = attachmentIdentityRevisionRef.current; - const reservedBytes = acceptedFiles.reduce((total, file) => total + file.size, 0); + const reservedBytes = preSelection.accepted.reduce((total, candidate) => total + candidate.size, 0); pendingTextFileCountRef.current += acceptedFiles.length; pendingTextFileBytesRef.current += reservedBytes; + setPendingTextReadCount((count) => count + acceptedFiles.length); try { type ReadCandidate = | { status: "binary"; file: File; isDoc: boolean } @@ -839,67 +868,135 @@ export const ChatInput = memo(forwardRef(function ChatIn // The composer was cleared/sent while the reads were in flight — // drop the batch instead of re-appending stale attachments. if (attachmentRevisionRef.current !== revision) return; - const sniffedDocs = readFiles + + // Exclude any document whose upload chip was removed while extraction was in flight, + // and refresh uploadId if a 410 replaced the upload ID during extraction. + const activeCandidates = readFiles.filter((candidate) => { + if (!docUploadMap.has(candidate.file)) return true; + const liveUpload = attachedUploadsRef.current.find((upload) => upload.file === candidate.file); + if (!liveUpload) return false; + if (candidate.status === "text") { + candidate.attachedFile.uploadId = liveUpload.id; + } + return true; + }); + + const sniffedDocs = activeCandidates .filter((candidate) => candidate.isDoc && !docUploadMap.has(candidate.file)) .map((candidate) => candidate.file); if (sniffedDocs.length > 0) { for (const upload of attachAsFiles(sniffedDocs)) { if (upload.file) docUploadMap.set(upload.file, upload); } - for (const candidate of readFiles) { + for (const candidate of activeCandidates) { if (candidate.status === "text" && !candidate.attachedFile.uploadId) { const upload = docUploadMap.get(candidate.file); if (upload) candidate.attachedFile.uploadId = upload.id; } } } + const fallbackAsFiles: File[] = []; - const otherInFlightBytes = Math.max(0, pendingTextFileBytesRef.current - reservedBytes); - let currentBytes = attachedTextFilesRef.current.reduce((total, file) => total + file.size, 0) + otherInFlightBytes; - const validTextFiles: AttachedTextFile[] = []; + const textCandidates: Array<{ file: File; isDoc: boolean; attachedFile: AttachedTextFile; size: number }> = []; - for (const candidate of readFiles) { + for (const candidate of activeCandidates) { if (candidate.status === "binary") { if (!candidate.isDoc) { fallbackAsFiles.push(candidate.file); + } else if (wasOversizedDocumentText(candidate.file)) { + skipTooLarge++; } continue; } - if ( - candidate.attachedFile.size > MAX_ATTACHED_TEXT_BYTES - || currentBytes + candidate.attachedFile.size > MAX_TOTAL_ATTACHED_TEXT_BYTES - ) { - if (!candidate.isDoc) { + textCandidates.push({ + file: candidate.file, + isDoc: candidate.isDoc, + attachedFile: candidate.attachedFile, + size: candidate.attachedFile.size, + }); + } + + const orderedForBudget = [ + ...textCandidates.filter((candidate) => !candidate.isDoc), + ...textCandidates.filter((candidate) => candidate.isDoc), + ]; + const baseFiles = attachedTextFilesRef.current; + const postSelection = selectTextAttachments(orderedForBudget, { + usedBytes: baseFiles.reduce((total, file) => total + file.size, 0), + usedSlots: identityRevision !== attachmentIdentityRevisionRef.current ? 0 : baseFiles.length, + }); + const acceptedSet = new Set(postSelection.accepted); + const validTextCandidates: typeof textCandidates = []; + for (const candidate of textCandidates) { + if (acceptedSet.has(candidate)) { + validTextCandidates.push(candidate); + } else { + if (!candidate.isDoc && identityRevision === attachmentIdentityRevisionRef.current) { fallbackAsFiles.push(candidate.file); } - continue; + if (candidate.isDoc || identityRevision !== attachmentIdentityRevisionRef.current) { + if (candidate.size > MAX_ATTACHED_TEXT_BYTES) { + skipTooLarge++; + } else { + skipOverBudget++; + } + } } - currentBytes += candidate.attachedFile.size; - validTextFiles.push(candidate.attachedFile); } + if (fallbackAsFiles.length > 0) { attachAsFiles(fallbackAsFiles); } + if (validTextCandidates.length > 0) { + attachedTextFilesRef.current = [...attachedTextFilesRef.current, ...validTextCandidates.map((c) => c.attachedFile)]; + } + setAttachedTextFiles((prev) => { - if (identityRevision !== attachmentIdentityRevisionRef.current) { - return [...prev, ...validTextFiles]; - } + const liveCandidates = validTextCandidates.filter((candidate) => { + if (!docUploadMap.has(candidate.file)) return true; + const liveUpload = attachedUploadsRef.current.find((upload) => upload.file === candidate.file); + if (!liveUpload) return false; + candidate.attachedFile.uploadId = liveUpload.id; + return true; + }); let committedBytes = prev.reduce((total, file) => total + file.size, 0); - const accepted = validTextFiles - .filter((file) => { - if (committedBytes + file.size > MAX_TOTAL_ATTACHED_TEXT_BYTES) return false; - committedBytes += file.size; - return true; - }) - .slice(0, Math.max(0, MAX_ATTACHED_TEXT_FILES - prev.length)); - return [...prev, ...accepted]; + const byteAccepted: typeof liveCandidates = []; + let commitRejected = 0; + for (const candidate of liveCandidates) { + if (committedBytes + candidate.attachedFile.size > MAX_TOTAL_ATTACHED_TEXT_BYTES) { + commitRejected++; + continue; + } + committedBytes += candidate.attachedFile.size; + byteAccepted.push(candidate); + } + const finalAccepted = identityRevision !== attachmentIdentityRevisionRef.current + ? byteAccepted + : byteAccepted.slice(0, Math.max(0, MAX_ATTACHED_TEXT_FILES - prev.length)); + commitRejected += byteAccepted.length - finalAccepted.length; + if (commitRejected > 0) { + const commitNotice = describeTextAttachmentSkip({ + tooLarge: skipTooLarge, + overBudget: skipOverBudget + commitRejected, + }); + if (commitNotice) setAttachNotice(commitNotice); + } + const next = [...prev, ...finalAccepted.map((c) => c.attachedFile)]; + attachedTextFilesRef.current = next; + return next; }); + + const skipNotice = describeTextAttachmentSkip({ tooLarge: skipTooLarge, overBudget: skipOverBudget }); + if (skipNotice) setAttachNotice(skipNotice); } catch { setAttachError(t("chatInput.attachmentTextReadFailed")); } finally { - pendingTextFileCountRef.current -= acceptedFiles.length; - pendingTextFileBytesRef.current -= reservedBytes; + if (attachmentRevisionRef.current === revision) { + pendingTextFileCountRef.current = Math.max(0, pendingTextFileCountRef.current - acceptedFiles.length); + pendingTextFileBytesRef.current = Math.max(0, pendingTextFileBytesRef.current - reservedBytes); + setPendingTextReadCount((count) => Math.max(0, count - acceptedFiles.length)); + } } }, [attachAsFiles, markInputEdited, t]); @@ -961,10 +1058,11 @@ export const ChatInput = memo(forwardRef(function ChatIn const removeTextFile = useCallback((target: number | AttachedTextFile) => { markInputEdited(); setAttachedTextFiles((prev) => { - if (typeof target === "number") { - return prev.filter((_, fileIndex) => fileIndex !== target); - } - return prev.filter((file) => file !== target); + const next = typeof target === "number" + ? prev.filter((_, fileIndex) => fileIndex !== target) + : prev.filter((file) => file !== target); + attachedTextFilesRef.current = next; + return next; }); setAttachError(null); }, [markInputEdited]); @@ -977,6 +1075,7 @@ export const ChatInput = memo(forwardRef(function ChatIn }, []); const clearTextFiles = useCallback(() => { + attachedTextFilesRef.current = []; setAttachedTextFiles([]); }, []); @@ -988,11 +1087,13 @@ export const ChatInput = memo(forwardRef(function ChatIn const hostId = attachedUploadsRef.current.find((upload) => upload.id === id)?.hostId; if (handle) handle.abort(); else if (hostId !== undefined) discardUpload(id, hostId); + attachedUploadsRef.current = attachedUploadsRef.current.filter((upload) => upload.id !== id); setAttachedUploads((prev) => { const removed = prev.find((upload) => upload.id === id); if (removed?.previewUrl) URL.revokeObjectURL(removed.previewUrl); return prev.filter((upload) => upload.id !== id); }); + attachedTextFilesRef.current = attachedTextFilesRef.current.filter((file) => file.uploadId !== id); setAttachedTextFiles((prev) => prev.filter((file) => file.uploadId !== id)); setAttachError(null); setAttachNotice(null); @@ -1032,8 +1133,9 @@ export const ChatInput = memo(forwardRef(function ChatIn uploadHandlesRef.current.delete(id); if (handle) handle.abort(); else discardUpload(id, upload.hostId); + attachedUploadsRef.current = attachedUploadsRef.current.filter((each) => each.id !== id); setAttachedUploads((prev) => prev.filter((each) => each.id !== id)); - setAttachedImages((prev) => [...prev, { data, mimeType: file.type, previewUrl, file }]); + setAttachedImages((prev) => [...prev, { data, mimeType: inferImageMimeType(file), previewUrl, file }]); } catch { setAttachError(t("chatInput.attachmentImageReadFailed")); } finally { @@ -1047,6 +1149,7 @@ export const ChatInput = memo(forwardRef(function ChatIn const clearUploads = useCallback(() => { for (const handle of uploadHandlesRef.current.values()) handle.abort(); uploadHandlesRef.current.clear(); + attachedUploadsRef.current = []; setAttachedUploads((prev) => { for (const upload of prev) if (upload.previewUrl) URL.revokeObjectURL(upload.previewUrl); return []; @@ -1064,6 +1167,11 @@ export const ChatInput = memo(forwardRef(function ChatIn clearTextFiles(); clearUploads(); setAttachNotice(null); + pendingImageCountRef.current = 0; + pendingImageBytesRef.current = 0; + pendingTextFileCountRef.current = 0; + pendingTextFileBytesRef.current = 0; + setPendingTextReadCount(0); // Invalidate any attachment reads still in flight. attachmentRevisionRef.current += 1; if (textareaRef.current) { @@ -1177,7 +1285,9 @@ export const ChatInput = memo(forwardRef(function ChatIn remaining.splice(index, 1); return false; }); - return [...draftFilesToAttachedFiles(draft?.files), ...added]; + const next = [...draftFilesToAttachedFiles(draft?.files), ...added]; + attachedTextFilesRef.current = next; + return next; }); // The same composer's uploads stay; the transferred draft's finished ones join them once. setAttachedUploads((current) => [ @@ -1192,6 +1302,11 @@ export const ChatInput = memo(forwardRef(function ChatIn // they cannot append onto the new session's composer, and drop any stale // validation banner along with the old draft. attachmentRevisionRef.current += 1; + pendingImageCountRef.current = 0; + pendingImageBytesRef.current = 0; + pendingTextFileCountRef.current = 0; + pendingTextFileBytesRef.current = 0; + setPendingTextReadCount(0); draftRecoveryIdentityRef.current = { key: draftKey }; setAttachError(null); setAttachNotice(null); @@ -1216,14 +1331,18 @@ export const ChatInput = memo(forwardRef(function ChatIn prev.forEach(revokeImagePreview); return draftImagesToAttachedImages(draft?.images); }); - setAttachedTextFiles(draftFilesToAttachedFiles(draft?.files)); + const restoredFiles = draftFilesToAttachedFiles(draft?.files); + attachedTextFilesRef.current = restoredFiles; + setAttachedTextFiles(restoredFiles); // shortcut: an upload still in flight is lost on a switch, as on a reload; keep its handle across drafts if users // switch chats mid-upload often. for (const handle of uploadHandlesRef.current.values()) handle.abort(); uploadHandlesRef.current.clear(); + const restoredUploads = draftUploadsToAttachedUploads(draft?.uploads); + attachedUploadsRef.current = restoredUploads; setAttachedUploads((prev) => { for (const upload of prev) if (upload.previewUrl) URL.revokeObjectURL(upload.previewUrl); - return draftUploadsToAttachedUploads(draft?.uploads); + return restoredUploads; }); }, [draftKey, draftIdentityMove]); @@ -1295,9 +1414,10 @@ export const ChatInput = memo(forwardRef(function ChatIn const uploads = attachedUploadsRef.current; const failed = uploads.filter((upload) => upload.status === "error").length; const uploading = uploads.filter((upload) => upload.status === "uploading").length; + const pending = Math.max(uploading, pendingTextFileCountRef.current); if (failed) setAttachError(t("chatInput.uploadsFailedBlock", { count: failed })); - else if (uploading) setAttachError(t("chatInput.uploadsWaiting", { count: uploading })); - return failed + uploading > 0; + else if (pending) setAttachError(t("chatInput.uploadsWaiting", { count: pending })); + return failed + pending > 0; }, [t]); /** Run a client builtin. True once handled; the composer is cleared only on @@ -1334,7 +1454,7 @@ export const ChatInput = memo(forwardRef(function ChatIn const handleSend = useCallback(async (overrideText?: string) => { const raw = overrideText ?? value; const msg = raw.trim(); - if (!msg && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length) return; + if (!msg && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length && !pendingTextFileCountRef.current) return; // `!cmd` runs right away during a run too, as in omp's terminal; it is never queued as text. const shellCommand = msg.startsWith("!") && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length; if (submissionBlockedRef.current || holdingRef.current || (isStreaming && !shellCommand)) return; @@ -1827,7 +1947,7 @@ export const ChatInput = memo(forwardRef(function ChatIn if (submissionBlockedRef.current || holdingRef.current) return; const raw = overrideText ?? value; const msg = raw.trim(); - if (!msg && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length) return; + if (!msg && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length && !pendingTextFileCountRef.current) return; if (sendSideQuestion(msg, overrideText)) return; if (rejectsPendingUploads()) return; if (msg.startsWith("!") && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length) { @@ -1898,8 +2018,11 @@ export const ChatInput = memo(forwardRef(function ChatIn // would have if the composer already held text. Keep Stop as the action // while the composer is empty and nothing is being recorded. const dictationCapturing = isRecording || isPaused || isReviewing; - const hasAttachments = attachedImages.length > 0 || attachedTextFiles.length > 0 || attachedUploads.length > 0; - const uploadingCount = attachedUploads.filter((upload) => upload.status === "uploading").length; + const hasAttachments = attachedImages.length > 0 || attachedTextFiles.length > 0 || attachedUploads.length > 0 || pendingTextReadCount > 0; + const uploadingCount = Math.max( + attachedUploads.filter((upload) => upload.status === "uploading").length, + pendingTextReadCount, + ); const failedUploadCount = attachedUploads.filter((upload) => upload.status === "error").length; const uploadsBlockSend = uploadingCount + failedUploadCount > 0; const imageUploads = attachedUploads.filter((upload) => upload.previewUrl !== null); @@ -2586,7 +2709,7 @@ export const ChatInput = memo(forwardRef(function ChatIn
)} {(() => { - const standaloneTextFiles = attachedTextFiles.filter((file) => !file.uploadId); + const standaloneTextFiles = attachedTextFiles.filter((file) => !file.uploadId || !attachedUploads.some((upload) => upload.id === file.uploadId)); return (standaloneTextFiles.length > 0 || fileUploads.length > 0) && (
{standaloneTextFiles.map((file, i) => ( diff --git a/lib/chat-attachments.test.mjs b/lib/chat-attachments.test.mjs index d73acca12..c1bd6f9c5 100644 --- a/lib/chat-attachments.test.mjs +++ b/lib/chat-attachments.test.mjs @@ -1017,3 +1017,127 @@ test("readAttachmentText exhibits parity between extension and extensionless doc assert.equal(withExtDocx, "Parity Test DOCX"); assert.equal(noExtDocx, "Parity Test DOCX"); }); + +test("isImageAttachmentFile excludes undecodable HEIC/HEIF files while accepting supported images", async () => { + const { isImageAttachmentFile, inferImageMimeType } = await loadSubject(); + + assert.equal(isImageAttachmentFile(mockFile("photo.heic", "image/heic", "x")), false); + assert.equal(isImageAttachmentFile(mockFile("photo.heif", "image/heif", "x")), false); + assert.equal(isImageAttachmentFile(mockFile("burst.heic", "image/heic-sequence", "x")), false); + assert.equal(isImageAttachmentFile(mockFile("photo.heic", "application/octet-stream", "x")), false); + assert.equal(isImageAttachmentFile(mockFile("photo.png", "image/png", "x")), true); + assert.equal(isImageAttachmentFile(mockFile("photo.png", "application/octet-stream", "x")), true); + assert.equal(inferImageMimeType(mockFile("photo.png", "application/octet-stream", "x")), "image/png"); +}); + +test("readAttachmentText extracts ODF inline text:span without spaces and escapes table pipes once", async () => { + const { readAttachmentText } = await loadSubject(); + const odtZip = createZip([ + { + name: "content.xml", + data: + `` + + `` + + `Unbroken` + + `` + + `` + + `A|B` + + `Para 1Para 2` + + `` + + `` + + ``, + }, + ]); + const result = await readAttachmentText( + mockFile("table.odt", "application/vnd.oasis.opendocument.text", odtZip), + ); + assert.ok(result.includes("Unbroken"), `Expected concatenated span 'Unbroken', got: ${result}`); + assert.ok(result.includes("| A\\|B | Para 1 Para 2 |"), `Expected single pipe escape and space-joined cell paragraphs, got: ${result}`); + assert.ok(!result.includes("\\\\|"), `Expected no double-escaped pipe, got: ${result}`); +}); + +test("readAttachmentText extracts .doc when 1Table is stored in the OLE2 mini-stream (< 4096 bytes)", async () => { + const { readAttachmentText } = await loadSubject(); + const text = "MiniStream Word 97 Table"; + const sectorSize = 512; + const miniSectorSize = 64; + + const textBuf = Buffer.from(text, "utf16le"); + // WordDocument >= 4096 bytes so it lives in regular sectors (8 sectors = 4096 bytes) + const wordDocBuf = Buffer.alloc(4096); + wordDocBuf.writeUInt16LE(0xA5EC, 0); + wordDocBuf.writeUInt16LE(0x0200, 0x000A); // fWhichTblStm = 1 (1Table) + textBuf.copy(wordDocBuf, 0x200); + + const pcdBuf = Buffer.alloc(8); + pcdBuf.writeUInt32LE(0x0200, 2); + const clxPart = Buffer.alloc(1 + 4 + 4 * 2 + 8); + clxPart[0] = 2; + clxPart.writeUInt32LE(4 * 2 + 8, 1); + clxPart.writeUInt32LE(0, 5); + clxPart.writeUInt32LE(text.length, 9); + pcdBuf.copy(clxPart, 13); + + wordDocBuf.writeUInt32LE(0, 0x01A2); // fcClx + wordDocBuf.writeUInt32LE(clxPart.length, 0x01A6); // lcbClx + + // Place 1Table at mini-sector 2 (offset 128 inside Root Entry's mini-stream) so reading regular sector 2 would fail + const miniStreamBuf = Buffer.alloc(sectorSize); + clxPart.copy(miniStreamBuf, 2 * miniSectorSize); + + const miniFatBuf = Buffer.alloc(sectorSize, 0xFF); + miniFatBuf.writeInt32LE(-2, 2 * 4); // mini-sector 2 -> ENDOFCHAIN + + // Sector layout: + // 0: FAT + // 1: Directory + // 2..9: WordDocument (8 sectors) + // 10: MiniFAT + // 11: MiniStream (Root Entry stream) + const dirBuf = Buffer.alloc(sectorSize); + function writeDirEntry(offset, name, type, startSect, size, childId = -1, leftId = -1, rightId = -1) { + const nameBuf = Buffer.from(name, "utf16le"); + nameBuf.copy(dirBuf, offset); + dirBuf.writeUInt16LE(nameBuf.length + 2, offset + 64); + dirBuf.writeUInt8(type, offset + 66); + dirBuf.writeUInt8(1, offset + 67); + dirBuf.writeInt32LE(leftId, offset + 68); + dirBuf.writeInt32LE(rightId, offset + 72); + dirBuf.writeInt32LE(childId, offset + 76); + dirBuf.writeInt32LE(startSect, offset + 116); + dirBuf.writeUInt32LE(size, offset + 120); + } + writeDirEntry(0, "Root Entry", 5, 11, miniStreamBuf.length, 1); + writeDirEntry(128, "WordDocument", 2, 2, wordDocBuf.length, -1, -1, 2); + writeDirEntry(256, "1Table", 2, 2, clxPart.length, -1, -1, -1); // startSect = mini-sector 2, size < 4096 + + const fatBuf = Buffer.alloc(sectorSize, 0xFF); + fatBuf.writeInt32LE(-3, 0 * 4); // FAT + fatBuf.writeInt32LE(-2, 1 * 4); // Dir + for (let i = 0; i < 8; i++) { + fatBuf.writeInt32LE(i === 7 ? -2 : 2 + i + 1, (2 + i) * 4); + } + fatBuf.writeInt32LE(-2, 10 * 4); // MiniFAT + fatBuf.writeInt32LE(-2, 11 * 4); // MiniStream + + const header = Buffer.alloc(512); + header.set([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1], 0); + header.writeUInt16LE(0xFFFE, 28); + header.writeUInt16LE(9, 30); + header.writeUInt16LE(6, 32); + header.writeUInt32LE(1, 44); + header.writeInt32LE(1, 48); + header.writeUInt32LE(0x1000, 56); + header.writeInt32LE(10, 60); // firstMiniFatSector = 10 + header.writeUInt32LE(1, 64); // numMiniFatSectors = 1 + header.writeInt32LE(-2, 68); + header.writeUInt32LE(0, 72); + header.writeInt32LE(0, 76); + for (let i = 1; i < 109; i++) { + header.writeInt32LE(-1, 76 + i * 4); + } + + const oleBuf = Buffer.concat([header, fatBuf, dirBuf, wordDocBuf, miniFatBuf, miniStreamBuf]); + const result = await readAttachmentText(mockFile("ministream.doc", "application/msword", oleBuf)); + assert.equal(result, text); +}); diff --git a/lib/chat-attachments.ts b/lib/chat-attachments.ts index 2368ebd25..e4fdac773 100644 --- a/lib/chat-attachments.ts +++ b/lib/chat-attachments.ts @@ -132,12 +132,20 @@ const RASTER_IMAGE_EXTENSIONS: Record = { ico: "image/x-icon", }; +const UNSUPPORTED_INLINE_IMAGE_MIME_TYPES: Record = { + "image/heic": true, + "image/heif": true, + "image/heic-sequence": true, + "image/heif-sequence": true, +}; + /** Checks whether file is candidate for image attachment by MIME type or extension. */ export function isImageAttachmentFile(file: Pick): boolean { - if (file.type && file.type.startsWith("image/")) { - return true; + const mime = file.type?.toLowerCase() ?? ""; + if (mime.startsWith("image/")) { + return !UNSUPPORTED_INLINE_IMAGE_MIME_TYPES[mime]; } - if (!file.type || file.type === "application/octet-stream") { + if (!mime || mime === "application/octet-stream") { const ext = getFileExtension(file.name); return Boolean(RASTER_IMAGE_EXTENSIONS[ext]); } @@ -206,7 +214,14 @@ export const MAX_PDF_OBJECTS = 8_192; export const MAX_OBJSTM_OBJECTS = 2_048; export const MAX_PDF_STREAM_TOKENS = 200_000; -const MAX_DECOMPRESSED_BYTES = MAX_TOTAL_ATTACHED_TEXT_BYTES * 4; +export const MAX_DECOMPRESSED_BYTES = MAX_TOTAL_ATTACHED_TEXT_BYTES * 4; + +const oversizedDocumentFiles = new WeakSet(); + +/** Whether `readAttachmentText` rejected `file` because its document content exceeded the inline text budget. */ +export function wasOversizedDocumentText(file: object): boolean { + return oversizedDocumentFiles.has(file); +} const MAX_CMAP_ENTRIES = 262144; const MAX_CMAP_RANGE_SPAN = 4096; @@ -1214,7 +1229,7 @@ async function extractDocx(entries: Map Promise>): Pro } /** Extracts worksheets and shared strings from OOXML XLSX into Markdown tables. */ -async function extractXlsx(entries: Map Promise>): Promise { +async function extractXlsx(entries: Map Promise>, state?: { oversized?: boolean }): Promise { const sharedStrings: string[] = []; const tagBudget: XmlTagBudget = { tags: 0, maxTags: MAX_XML_TAGS }; @@ -1391,7 +1406,10 @@ async function extractXlsx(entries: Map Promise>): Pro const trimmed = val.trim(); if (trimmed) { rawCellBytes += encoder.encode(trimmed).byteLength; - if (projectedBytes + rawCellBytes > MAX_ATTACHED_TEXT_BYTES) return false; + if (projectedBytes + rawCellBytes > MAX_ATTACHED_TEXT_BYTES) { + if (state) state.oversized = true; + return false; + } } rowCells.set(cellColNum, trimmed); } @@ -1419,7 +1437,10 @@ async function extractXlsx(entries: Map Promise>): Pro const heading = `### ${name}\n\n`; const sheetBytes = encoder.encode(heading).byteLength + encoder.encode(tableMd).byteLength; const sectionSeparatorBytes = sections.length > 0 ? 2 : 0; - if (projectedBytes + sectionSeparatorBytes + sheetBytes > MAX_ATTACHED_TEXT_BYTES) return null; + if (projectedBytes + sectionSeparatorBytes + sheetBytes > MAX_ATTACHED_TEXT_BYTES) { + if (state) state.oversized = true; + return null; + } projectedBytes += sectionSeparatorBytes + sheetBytes; sections.push(heading + tableMd); } @@ -1510,7 +1531,7 @@ async function extractPptx(entries: Map Promise>): Pro } /** Extracts paragraphs and tables from OpenDocument (ODT/ODS/ODP) content. */ -async function extractOdf(entries: Map Promise>): Promise { +async function extractOdf(entries: Map Promise>, state?: { oversized?: boolean }): Promise { const contentFn = entries.get("content.xml"); if (!contentFn) return null; const buf = await contentFn(); @@ -1519,6 +1540,7 @@ async function extractOdf(entries: Map Promise>): Prom const tagBudget: XmlTagBudget = { tags: 0, maxTags: MAX_XML_TAGS }; const encoder = new TextEncoder(); let outputBytes = 0; + let tableCellBytes = 0; const parts: string[] = []; let inTable = false; @@ -1541,13 +1563,18 @@ async function extractOdf(entries: Map Promise>): Prom inTable = true; tableRows = []; totalCellsInTable = 0; + tableCellBytes = 0; } else { inTable = false; + tableCellBytes = 0; if (tableRows.length > 0) { const tableMd = formatMarkdownTable(tableRows); if (tableMd === null) return false; outputBytes += encoder.encode(tableMd).byteLength + 2; - if (outputBytes > MAX_ATTACHED_TEXT_BYTES) return false; + if (outputBytes > MAX_ATTACHED_TEXT_BYTES) { + if (state) state.oversized = true; + return false; + } parts.push(tableMd); } tableRows = []; @@ -1585,9 +1612,16 @@ async function extractOdf(entries: Map Promise>): Prom } else { inCell = false; const trimmed = decodeXmlEntities(cellText.trim()); - const escaped = trimmed.replace(/\|/g, "\\|").replace(/\n/g, " "); + const normalized = trimmed.replace(/\n/g, " "); + if (normalized) { + tableCellBytes += encoder.encode(normalized).byteLength * cellRepeat; + if (outputBytes + tableCellBytes > MAX_ATTACHED_TEXT_BYTES) { + if (state) state.oversized = true; + return false; + } + } for (let i = 0; i < cellRepeat; i++) { - currentRow.push(escaped); + currentRow.push(normalized); } cellText = ""; } @@ -1598,24 +1632,40 @@ async function extractOdf(entries: Map Promise>): Prom paraText = ""; } } else { - if (!inTable && inPara) { + if (inCell) { + if (cellText && !/\s$/.test(cellText)) { + cellText += " "; + } + } else if (!inTable && inPara) { inPara = false; const trimmed = decodeXmlEntities(paraText.trim()); if (trimmed) { outputBytes += encoder.encode(trimmed).byteLength + 2; - if (outputBytes > MAX_ATTACHED_TEXT_BYTES) return false; + if (outputBytes > MAX_ATTACHED_TEXT_BYTES) { + if (state) state.oversized = true; + return false; + } parts.push(trimmed); } paraText = ""; } } + } else if (!isClose && tagName === "text:line-break") { + if (inCell) cellText += " "; + else if (inPara) paraText += "\n"; + } else if (!isClose && tagName === "text:tab") { + if (inCell) cellText += "\t"; + else if (inPara) paraText += "\t"; + } else if (!isClose && tagName === "text:s") { + if (inCell) cellText += " "; + else if (inPara) paraText += " "; } }, (text) => { if (inCell) { - cellText += (cellText ? " " : "") + text; + cellText += text; } else if (inPara) { - paraText += (paraText ? " " : "") + text; + paraText += text; } }, ); @@ -1725,9 +1775,14 @@ function extractDocText(buffer: ArrayBuffer): string | null { return null; } const sectorSize = 1 << sectorShift; + const miniSectorShift = view.getUint16(32, true); + const miniSectorSize = 1 << (miniSectorShift >= 4 && miniSectorShift <= 8 ? miniSectorShift : 6); const maxSectors = Math.floor(buffer.byteLength / sectorSize); const numFatSectors = Math.min(view.getUint32(44, true), maxSectors); const firstDirSector = view.getInt32(48, true); + const miniStreamCutoff = view.getUint32(56, true) || 0x1000; + const firstMiniFatSector = view.getInt32(60, true); + const numMiniFatSectors = Math.min(view.getUint32(64, true), maxSectors); const firstDifatSector = view.getInt32(68, true); const numDifatSectors = Math.min(view.getUint32(72, true), maxSectors); @@ -1772,7 +1827,7 @@ function extractDocText(buffer: ArrayBuffer): string | null { return chain; } - function readStream(startSector: number, size: number): Uint8Array { + function readRegularStream(startSector: number, size: number): Uint8Array { const chain = getChain(startSector); const safeSize = Math.min(size, chain.length * sectorSize, MAX_DECOMPRESSED_BYTES); const result = new Uint8Array(safeSize); @@ -1786,6 +1841,7 @@ function extractDocText(buffer: ArrayBuffer): string | null { } return result; } + const dirChain = getChain(firstDirSector); const dirBytes = new Uint8Array(dirChain.length * sectorSize); let dOff = 0; @@ -1798,18 +1854,67 @@ function extractDocText(buffer: ArrayBuffer): string | null { const dirView = new DataView(dirBytes.buffer, dirBytes.byteOffset, dirBytes.byteLength); const numEntries = dirBytes.byteLength / 128; const entries = new Map(); + let rootEntry: { startSect: number; size: number } | null = null; for (let i = 0; i < numEntries; i++) { const entryOffset = i * 128; const nameLen = dirView.getUint16(entryOffset + 64, true); if (nameLen === 0) continue; + const entryType = dirView.getUint8(entryOffset + 66); const actualLen = Math.max(0, nameLen - 2); const name = new TextDecoder("utf-16le").decode(new Uint8Array(dirBytes.buffer, entryOffset, actualLen)); const startSect = dirView.getInt32(entryOffset + 116, true); const size = dirView.getUint32(entryOffset + 120, true); + if (entryType === 5 || (i === 0 && !rootEntry)) { + rootEntry = { startSect, size }; + } entries.set(name, { startSect, size }); } + const miniFat: number[] = []; + if (firstMiniFatSector >= 0) { + const maxMiniFat = numMiniFatSectors > 0 ? numMiniFatSectors : maxSectors; + const miniFatChain = getChain(firstMiniFatSector).slice(0, maxMiniFat); + for (const sIndex of miniFatChain) { + const offset = (sIndex + 1) * sectorSize; + if (offset + sectorSize > buffer.byteLength) break; + for (let j = 0; j < sectorSize / 4; j++) { + miniFat.push(view.getInt32(offset + j * 4, true)); + } + } + } + + const miniStream = rootEntry && rootEntry.startSect >= 0 && rootEntry.size > 0 + ? readRegularStream(rootEntry.startSect, rootEntry.size) + : new Uint8Array(0); + + function readStream(startSector: number, size: number): Uint8Array { + if (size < miniStreamCutoff && miniFat.length > 0 && miniStream.byteLength > 0) { + const maxMiniSectors = Math.floor(miniStream.byteLength / miniSectorSize); + const chain: number[] = []; + const visited = new Set(); + let curr = startSector; + while (curr >= 0 && curr < miniFat.length && curr < maxMiniSectors && chain.length < maxMiniSectors && !visited.has(curr)) { + visited.add(curr); + chain.push(curr); + curr = miniFat[curr]; + if (curr === -2) break; + } + const safeSize = Math.min(size, chain.length * miniSectorSize, MAX_DECOMPRESSED_BYTES); + const result = new Uint8Array(safeSize); + let written = 0; + for (const mSect of chain) { + const offset = mSect * miniSectorSize; + const toRead = Math.min(miniSectorSize, safeSize - written); + if (toRead <= 0 || offset + toRead > miniStream.byteLength) break; + result.set(miniStream.subarray(offset, offset + toRead), written); + written += toRead; + } + return result; + } + return readRegularStream(startSector, size); + } + const wordDocEntry = entries.get("WordDocument"); if (!wordDocEntry) return null; @@ -1824,7 +1929,6 @@ function extractDocText(buffer: ArrayBuffer): string | null { const tableStream = readStream(tableEntry.startSect, tableEntry.size); const tableView = new DataView(tableStream.buffer, tableStream.byteOffset, tableStream.byteLength); - const fcClx = wordDocView.getUint32(0x01A2, true); const lcbClx = wordDocView.getUint32(0x01A6, true); if (fcClx + lcbClx > tableStream.byteLength) return null; @@ -2000,12 +2104,27 @@ export async function readAttachmentText(file: { if (buffer) { const bytes = new Uint8Array(buffer); + const state = { oversized: false }; + const finalizeDocResult = (res: string | null): string | null => { + if (res !== null && new TextEncoder().encode(res).byteLength > MAX_ATTACHED_TEXT_BYTES) { + oversizedDocumentFiles.add(file); + return null; + } + if (res === null && state.oversized) { + oversizedDocumentFiles.add(file); + } + return res; + }; // a) PDF (%PDF- magic or .pdf or application/pdf) const isPdfMagic = bytes.length >= 5 && bytes[0] === 0x25 && bytes[1] === 0x50 && bytes[2] === 0x44 && bytes[3] === 0x46 && bytes[4] === 0x2D; if (isPdfMagic || ext === "pdf" || file.type === "application/pdf") { + if (buffer.byteLength > MAX_DECOMPRESSED_BYTES) { + oversizedDocumentFiles.add(file); + return null; + } try { - return await extractPdfText(buffer); + return finalizeDocResult(await extractPdfText(buffer)); } catch { return null; } @@ -2014,22 +2133,26 @@ export async function readAttachmentText(file: { // b) ZIP-based documents (PK\x03\x04 magic) const isZipMagic = bytes.length >= 4 && bytes[0] === 0x50 && bytes[1] === 0x4B && bytes[2] === 0x03 && bytes[3] === 0x04; if (isZipMagic) { + if (buffer.byteLength > MAX_DECOMPRESSED_BYTES) { + if (isKnownDocument) oversizedDocumentFiles.add(file); + return null; + } try { const entries = await readZipEntries(buffer); if (ext === "docx" || entries.has("word/document.xml")) { - return await extractDocx(entries); + return finalizeDocResult(await extractDocx(entries)); } if (ext === "xlsx" || entries.has("xl/workbook.xml")) { - return await extractXlsx(entries); + return finalizeDocResult(await extractXlsx(entries, state)); } if (ext === "pptx" || entries.has("ppt/presentation.xml")) { - return await extractPptx(entries); + return finalizeDocResult(await extractPptx(entries)); } if (ext === "odt" || ext === "ods" || ext === "odp" || entries.has("content.xml")) { - return await extractOdf(entries); + return finalizeDocResult(await extractOdf(entries, state)); } if (ext === "epub" || entries.has("META-INF/container.xml")) { - return await extractEpub(entries); + return finalizeDocResult(await extractEpub(entries)); } } catch { return null; @@ -2041,8 +2164,12 @@ export async function readAttachmentText(file: { && bytes[0] === 0xD0 && bytes[1] === 0xCF && bytes[2] === 0x11 && bytes[3] === 0xE0 && bytes[4] === 0xA1 && bytes[5] === 0xB1 && bytes[6] === 0x1A && bytes[7] === 0xE1; if (isOleMagic || ext === "doc") { + if (buffer.byteLength > MAX_DECOMPRESSED_BYTES) { + oversizedDocumentFiles.add(file); + return null; + } try { - return extractDocText(buffer); + return finalizeDocResult(extractDocText(buffer)); } catch { return null; } From fb7fb17928673bd83d40a1349807ec71d04adf72 Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Tue, 10 Nov 2026 01:06:31 +0800 Subject: [PATCH 13/13] fix(chat): bound remaining document scanners and preserve attachment ownership across draft lifecycle --- components/ChatInput-draft-attachments.ts | 10 + .../ChatInput.queue-attachments.test.mjs | 301 ++++++++++++--- components/ChatInput.tsx | 48 ++- lib/chat-attachments.test.mjs | 63 +++ lib/chat-attachments.ts | 359 ++++++++++++++---- 5 files changed, 641 insertions(+), 140 deletions(-) diff --git a/components/ChatInput-draft-attachments.ts b/components/ChatInput-draft-attachments.ts index 36f4facd6..9a652269f 100644 --- a/components/ChatInput-draft-attachments.ts +++ b/components/ChatInput-draft-attachments.ts @@ -41,6 +41,16 @@ export function textFileToDraftFile(file: AttachedTextFile): ChatDraftFile { }; } +export function attachedTextFilesToDraftFiles( + files: AttachedTextFile[], + uploads: Array<{ id: string; status: string }>, +): ChatDraftFile[] { + const doneUploadIds = new Set(uploads.filter((upload) => upload.status === "done").map((upload) => upload.id)); + return files + .filter((file) => !file.uploadId || doneUploadIds.has(file.uploadId)) + .map(textFileToDraftFile); +} + /** Recovery and Edit relocation can merge individually valid drafts past picker * budgets. Keep every well-formed file; sending validates the composed request, * not the picker file-count or text-byte limits. */ diff --git a/components/ChatInput.queue-attachments.test.mjs b/components/ChatInput.queue-attachments.test.mjs index 5cfcd8b87..6c79d3c62 100644 --- a/components/ChatInput.queue-attachments.test.mjs +++ b/components/ChatInput.queue-attachments.test.mjs @@ -1778,96 +1778,291 @@ test("removing an upload chip also removes paired extracted text file from draft }); }); -test("removing a document chip while text extraction is in flight discards the extracted text when it resolves", async () => { +test("removing secret.docx while extraction is pending excludes its text on Enter while keeping retained batch member", async () => { setupUploadFetchMock(); + const sentMessages = []; const ref = React.createRef(); render(React.createElement(ChatInput, { ref, draftKey: KEY, isStreaming: false, onAbort() {}, - onSend: async () => ({ status: "accepted" }), + onSend: async (msg) => { + sentMessages.push(msg); + return { status: "accepted" }; + }, })); - const docxBuf = createDocxBuffer("Slow extracted text"); - let resolveBuffer; - const slowFile = new File([docxBuf], "slow-remove.docx", { + const secretBuf = createDocxBuffer("SECRET-PENDING-A1"); + const keepBuf = createDocxBuffer("KEEP-BATCH-MEMBER"); + let resolveSecret; + const secretFile = new File([secretBuf], "secret.docx", { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", }); - slowFile.arrayBuffer = () => new Promise((resolve) => { - resolveBuffer = () => resolve(docxBuf.buffer.slice(docxBuf.byteOffset, docxBuf.byteOffset + docxBuf.byteLength)); + secretFile.arrayBuffer = () => new Promise((resolve) => { + resolveSecret = () => resolve(secretBuf.buffer.slice(secretBuf.byteOffset, secretBuf.byteOffset + secretBuf.byteLength)); + }); + const keepFile = new File([keepBuf], "keep.docx", { + type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", }); await act(async () => { - ref.current.addFiles([slowFile]); + ref.current.addFiles([secretFile, keepFile]); }); - // Upload chip is visible while extraction is still pending; remove it before extraction resolves. - const removeBtn = await screen.findByLabelText(/chatInput\.removeFile|Remove file/i); - fireEvent.click(removeBtn); + const removeBtns = await screen.findAllByLabelText(/chatInput\.removeFile|Remove file/i); + assert.equal(removeBtns.length, 2); + fireEvent.click(removeBtns[0]); await act(async () => { - resolveBuffer(); + resolveSecret(); await new Promise((resolve) => setImmediate(resolve)); }); - const draft = getDraft(KEY); - assert.equal(draft?.uploads?.length ?? 0, 0, "upload remains removed"); - assert.equal(draft?.files?.length ?? 0, 0, "late-resolving extracted text is discarded"); + await waitFor(() => { + const draft = getDraft(KEY); + assert.equal(draft?.uploads?.length, 1); + assert.equal(draft?.files?.length, 1); + }); + + const textarea = screen.getByRole("textbox"); + fireEvent.change(textarea, { target: { value: "Submit after pending removal" } }); + await act(async () => { + fireEvent.keyDown(textarea, { key: "Enter" }); + }); + + assert.equal(sentMessages.length, 1); + assert.ok(!sentMessages[0].includes("SECRET-PENDING-A1"), "removed secret.docx text must not be submitted"); + assert.ok(sentMessages[0].includes("KEEP-BATCH-MEMBER"), "retained batch member text must be submitted"); }); -test("410 upload replacement updates uploadId on paired extracted document text", async () => { - let postCount = 0; - let putCount = 0; - const previousFetch = globalThis.fetch; - override(globalThis, "fetch", async (url, init = {}) => { - const method = init.method ?? "GET"; - const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); - if (url === "/api/uploads" && method === "POST") { - postCount += 1; - return json({ received: 0 }); +test("410 upload replacement relinks extracted text across all 3 variants so removing the chip never submits SECRET-A2 on Enter", async () => { + for (const variant of ["complete-before-410", "retry-before-remove", "pending-across-410"]) { + let putCount = 0; + let resolveFirstPut; + const previousFetch = globalThis.fetch; + override(globalThis, "fetch", async (url, init = {}) => { + const method = init.method ?? "GET"; + const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); + if (url === "/api/uploads" && method === "POST") { + return json({ received: 0 }); + } + if (String(url).startsWith("/api/uploads/") && method === "PUT") { + putCount += 1; + if (putCount === 1) { + if (variant === "complete-before-410") { + return await new Promise((resolve) => { + resolveFirstPut = () => resolve(json({ error: "expired" }, 410)); + }); + } + return json({ error: "expired" }, 410); + } + const offset = Number(new URL(String(url), "https://omp.test/").searchParams.get("offset") ?? 0); + return json({ received: offset + (init.body?.size ?? 0), done: true }); + } + if (String(url).startsWith("/api/uploads/") && method === "DELETE") { + return new Response(null, { status: 204 }); + } + if (previousFetch) return previousFetch(url, init); + return json({}); + }); + + const sentMessages = []; + const ref = React.createRef(); + const view = render(React.createElement(ChatInput, { + ref, + draftKey: `${KEY}-${variant}`, + isStreaming: false, + onAbort() {}, + onSend: async (msg) => { + sentMessages.push(msg); + return { status: "accepted" }; + }, + })); + + const docxBuf = createDocxBuffer("SECRET-A2"); + let resolveExtract; + const file = new File([docxBuf], "secret.docx", { + type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + }); + if (variant === "pending-across-410") { + file.arrayBuffer = () => new Promise((resolve) => { + resolveExtract = () => resolve(docxBuf.buffer.slice(docxBuf.byteOffset, docxBuf.byteOffset + docxBuf.byteLength)); + }); } - if (String(url).startsWith("/api/uploads/") && method === "PUT") { - putCount += 1; - if (putCount === 1) { - return json({ error: "expired" }, 410); + + await act(async () => { + ref.current.addFiles([file]); + await new Promise((resolve) => setImmediate(resolve)); + }); + + if (variant === "complete-before-410") { + await act(async () => { + resolveFirstPut(); + await new Promise((resolve) => setImmediate(resolve)); + }); + } + + await screen.findByLabelText(/chatInput\.retryUpload|Retry upload/i); + + if (variant === "pending-across-410") { + await act(async () => { + resolveExtract(); + await new Promise((resolve) => setImmediate(resolve)); + }); + } + + if (variant === "retry-before-remove") { + const retryBtn = await screen.findByLabelText(/chatInput\.retryUpload|Retry upload/i); + await act(async () => { + fireEvent.click(retryBtn); + }); + await waitFor(() => { + assert.equal(getDraft(`${KEY}-${variant}`)?.uploads?.length, 1); + }); + } + + const removeBtn = await screen.findByLabelText(/chatInput\.removeFile|Remove file/i); + fireEvent.click(removeBtn); + assert.equal(screen.queryAllByLabelText(/chatInput\.removeFile|Remove file/i).length, 0); + + const textarea = screen.getByRole("textbox"); + fireEvent.change(textarea, { target: { value: `Prompt ${variant}` } }); + await act(async () => { + fireEvent.keyDown(textarea, { key: "Enter" }); + }); + + assert.equal(sentMessages.length, 1, `Expected message sent in ${variant}`); + assert.ok(!sentMessages[0].includes("SECRET-A2"), `SECRET-A2 must not be sent after removing chip in ${variant}`); + view.unmount(); + } +}); + +test("extraction finishing before upload does not leak hidden SECRET-A3 across draftKey navigation or remount", async () => { + for (const mode of ["navigate", "remount"]) { + const previousFetch = globalThis.fetch; + override(globalThis, "fetch", async (url, init = {}) => { + const method = init.method ?? "GET"; + const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); + if (url === "/api/uploads" && method === "POST") { + return json({ received: 0 }); } - const offset = Number(new URL(String(url), "https://omp.test/").searchParams.get("offset") ?? 0); - return json({ received: offset + (init.body?.size ?? 0), done: true }); + if (String(url).startsWith("/api/uploads/") && method === "PUT") { + // Never finishes before navigation/remount + return await new Promise(() => {}); + } + if (previousFetch) return previousFetch(url, init); + return json({}); + }); + + const draftKey = `${KEY}-a3-${mode}`; + const sentMessages = []; + const ref = React.createRef(); + const baseProps = { + ref, + draftKey, + isStreaming: false, + onAbort() {}, + onSend: async (msg) => { + sentMessages.push(msg); + return { status: "accepted" }; + }, + }; + let view = render(React.createElement(ChatInput, baseProps)); + + const docxBuf = createDocxBuffer("SECRET-A3"); + await act(async () => { + ref.current.addFiles([ + new File([docxBuf], "secret.docx", { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }), + ]); + await new Promise((resolve) => setImmediate(resolve)); + }); + + if (mode === "navigate") { + view.rerender(React.createElement(ChatInput, { ...baseProps, draftKey: `${draftKey}-other` })); + view.rerender(React.createElement(ChatInput, baseProps)); + } else { + view.unmount(); + view = render(React.createElement(ChatInput, baseProps)); } - if (previousFetch) return previousFetch(url, init); - return json({}); - }); + assert.equal(screen.queryAllByLabelText(/chatInput\.removeFile|Remove file/i).length, 0); + const textarea = screen.getByRole("textbox"); + fireEvent.change(textarea, { target: { value: `Hello after ${mode}` } }); + await act(async () => { + fireEvent.keyDown(textarea, { key: "Enter" }); + }); + + assert.equal(sentMessages.length, 1); + assert.ok(!sentMessages[0].includes("SECRET-A3"), `SECRET-A3 must not be sent after ${mode}`); + view.unmount(); + } +}); + +test("blocks Enter while extraction is pending with warning and clears outbox draft cleanly once acknowledged", async () => { + setupUploadFetchMock(); + const sentMessages = []; + let resolveOutbox; const ref = React.createRef(); render(React.createElement(ChatInput, { ref, - draftKey: KEY, + draftKey: `${KEY}-outbox-race`, isStreaming: false, + outbox: true, onAbort() {}, - onSend: async () => ({ status: "accepted" }), + onSend: (msg) => { + sentMessages.push(msg); + return new Promise((resolve) => { + resolveOutbox = () => resolve({ status: "accepted" }); + }); + }, })); - const docxBuf = createDocxBuffer("410 recovered text"); + const docxBuf = createDocxBuffer("OUTBOX-DOC-TEXT"); + let resolveExtract; + const slowDoc = new File([docxBuf], "report.docx", { + type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + }); + slowDoc.arrayBuffer = () => new Promise((resolve) => { + resolveExtract = () => resolve(docxBuf.buffer.slice(docxBuf.byteOffset, docxBuf.byteOffset + docxBuf.byteLength)); + }); + await act(async () => { - ref.current.addFiles([ - new File([docxBuf], "retry-410.docx", { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }), - ]); + ref.current.addFiles([slowDoc]); + await new Promise((resolve) => setImmediate(resolve)); }); - // After 410, the upload settles to error with a newly minted id; the paired text file's uploadId is updated immediately, - // so there is still only 1 deduplicated chip. Clicking Retry completes the upload under the new id. - const retryBtn = await screen.findByLabelText(/chatInput\.retryUpload|Retry upload/i); - assert.equal(screen.getAllByText("retry-410.docx").length, 1, "single chip during 410 error state"); - fireEvent.click(retryBtn); + const textarea = screen.getByRole("textbox"); + fireEvent.change(textarea, { target: { value: "Send with doc" } }); - await waitFor(() => { - const draft = getDraft(KEY); - assert.equal(draft?.uploads?.length, 1); - assert.equal(draft?.files?.length, 1); - assert.equal(draft?.files[0]?.uploadId, draft?.uploads[0]?.id, "extracted text uploadId matches replacement upload id"); + // Pressing Enter while extraction is still pending must warn and block sending + await act(async () => { + fireEvent.keyDown(textarea, { key: "Enter" }); + }); + assert.equal(sentMessages.length, 0, "must not send before extraction finishes"); + assert.ok(screen.getByRole("alert"), "shows waiting warning when sending before extraction finishes"); + + // Now finish extraction and submit via outbox + await act(async () => { + resolveExtract(); + await new Promise((resolve) => setImmediate(resolve)); + }); + + await act(async () => { + fireEvent.keyDown(textarea, { key: "Enter" }); + }); + assert.equal(sentMessages.length, 1); + assert.ok(sentMessages[0].includes("OUTBOX-DOC-TEXT"), "includes extracted document text on send"); + + await act(async () => { + resolveOutbox(); + await new Promise((resolve) => setImmediate(resolve)); + }); + + assert.equal(textarea.value, "", "composer cleared after outbox storage acknowledgement"); + // A second Enter on the cleared composer must not resubmit the already-sent draft + await act(async () => { + fireEvent.keyDown(textarea, { key: "Enter" }); }); - assert.ok(postCount >= 2, "retried POST /api/uploads after 410"); - const chips = screen.getAllByText("retry-410.docx"); - assert.equal(chips.length, 1, "still renders a single deduplicated chip after 410 ID replacement"); + assert.equal(sentMessages.length, 1, "second Enter does not resubmit already-sent draft"); }); diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 9b70ba4b6..4ff1803d7 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -19,11 +19,11 @@ import { beginDraftSubmission, clearDraft, consumeDraft, endDraftSubmission, get import { expandWebSlashCommand } from "@/lib/web-slash-commands"; import type { AttachedImage, AttachedTextFile } from "./ChatInput-draft-attachments"; import { + attachedTextFilesToDraftFiles, draftFilesToAttachedFiles, draftImagesToAttachedImages, imageToDraftImage, revokeImagePreview, - textFileToDraftFile, } from "./ChatInput-draft-attachments"; import { attachedUploadsToDraftUploads, @@ -561,6 +561,17 @@ export const ChatInput = memo(forwardRef(function ChatIn const pendingTextFileCountRef = useRef(0); const pendingTextFileBytesRef = useRef(0); const pendingImageBytesRef = useRef(0); + const inFlightTextReadsRef = useRef>(new Map()); + const settleInFlightTextRead = useCallback((file: File) => { + const entry = inFlightTextReadsRef.current.get(file); + if (!entry) return; + inFlightTextReadsRef.current.delete(file); + if (attachmentRevisionRef.current === entry.revision) { + pendingTextFileCountRef.current = Math.max(0, pendingTextFileCountRef.current - 1); + pendingTextFileBytesRef.current = Math.max(0, pendingTextFileBytesRef.current - entry.bytes); + setPendingTextReadCount((count) => Math.max(0, count - 1)); + } + }, []); const attachedUploadsRef = useRef(attachedUploads); /** Uploads in flight, by id: a chip's removal aborts its handle. */ const uploadHandlesRef = useRef(new Map()); @@ -834,6 +845,9 @@ export const ChatInput = memo(forwardRef(function ChatIn const revision = attachmentRevisionRef.current; const identityRevision = attachmentIdentityRevisionRef.current; const reservedBytes = preSelection.accepted.reduce((total, candidate) => total + candidate.size, 0); + for (const candidate of preSelection.accepted) { + inFlightTextReadsRef.current.set(candidate.file, { bytes: candidate.size, revision }); + } pendingTextFileCountRef.current += acceptedFiles.length; pendingTextFileBytesRef.current += reservedBytes; setPendingTextReadCount((count) => count + acceptedFiles.length); @@ -983,6 +997,12 @@ export const ChatInput = memo(forwardRef(function ChatIn if (commitNotice) setAttachNotice(commitNotice); } const next = [...prev, ...finalAccepted.map((c) => c.attachedFile)]; + if ( + attachedTextFilesRef.current.length === next.length + && attachedTextFilesRef.current.every((item, idx) => item === next[idx]) + ) { + return attachedTextFilesRef.current; + } attachedTextFilesRef.current = next; return next; }); @@ -992,13 +1012,11 @@ export const ChatInput = memo(forwardRef(function ChatIn } catch { setAttachError(t("chatInput.attachmentTextReadFailed")); } finally { - if (attachmentRevisionRef.current === revision) { - pendingTextFileCountRef.current = Math.max(0, pendingTextFileCountRef.current - acceptedFiles.length); - pendingTextFileBytesRef.current = Math.max(0, pendingTextFileBytesRef.current - reservedBytes); - setPendingTextReadCount((count) => Math.max(0, count - acceptedFiles.length)); + for (const file of acceptedFiles) { + settleInFlightTextRead(file); } } - }, [attachAsFiles, markInputEdited, t]); + }, [attachAsFiles, markInputEdited, settleInFlightTextRead, t]); const processFiles = useCallback((files: File[]) => { const imageFiles = files.filter((file) => isImageAttachmentFile(file)); @@ -1084,7 +1102,11 @@ export const ChatInput = memo(forwardRef(function ChatIn markInputEdited(); const handle = uploadHandlesRef.current.get(id); uploadHandlesRef.current.delete(id); - const hostId = attachedUploadsRef.current.find((upload) => upload.id === id)?.hostId; + const removedUpload = attachedUploadsRef.current.find((upload) => upload.id === id); + const hostId = removedUpload?.hostId; + if (removedUpload?.file) { + settleInFlightTextRead(removedUpload.file); + } if (handle) handle.abort(); else if (hostId !== undefined) discardUpload(id, hostId); attachedUploadsRef.current = attachedUploadsRef.current.filter((upload) => upload.id !== id); @@ -1097,7 +1119,7 @@ export const ChatInput = memo(forwardRef(function ChatIn setAttachedTextFiles((prev) => prev.filter((file) => file.uploadId !== id)); setAttachError(null); setAttachNotice(null); - }, [markInputEdited]); + }, [markInputEdited, settleInFlightTextRead]); const retryUpload = useCallback((id: string) => { const upload = attachedUploadsRef.current.find((each) => each.id === id); @@ -1167,6 +1189,7 @@ export const ChatInput = memo(forwardRef(function ChatIn clearTextFiles(); clearUploads(); setAttachNotice(null); + inFlightTextReadsRef.current.clear(); pendingImageCountRef.current = 0; pendingImageBytesRef.current = 0; pendingTextFileCountRef.current = 0; @@ -1192,7 +1215,7 @@ export const ChatInput = memo(forwardRef(function ChatIn setDraft(key, { value: valueRef.current, images: images.map(imageToDraftImage), - files: files.map(textFileToDraftFile), + files: attachedTextFilesToDraftFiles(files, uploads), uploads: attachedUploadsToDraftUploads(uploads), }); } @@ -1219,7 +1242,7 @@ export const ChatInput = memo(forwardRef(function ChatIn const current: ChatDraft = { value: valueRef.current, images: attachedImagesRef.current.map(imageToDraftImage), - files: attachedTextFilesRef.current.map(textFileToDraftFile), + files: attachedTextFilesToDraftFiles(attachedTextFilesRef.current, attachedUploadsRef.current), ...(uploads.length ? { uploads } : {}), }; if (JSON.stringify(current) === JSON.stringify(snapshot)) clearInput(); @@ -1232,7 +1255,7 @@ export const ChatInput = memo(forwardRef(function ChatIn const draft = { value, images: attachedImages.map(imageToDraftImage), - files: attachedTextFiles.map(textFileToDraftFile), + files: attachedTextFilesToDraftFiles(attachedTextFiles, attachedUploads), uploads: attachedUploadsToDraftUploads(attachedUploads), }; persistedDraftRef.current = draft; @@ -1302,6 +1325,7 @@ export const ChatInput = memo(forwardRef(function ChatIn // they cannot append onto the new session's composer, and drop any stale // validation banner along with the old draft. attachmentRevisionRef.current += 1; + inFlightTextReadsRef.current.clear(); pendingImageCountRef.current = 0; pendingImageBytesRef.current = 0; pendingTextFileCountRef.current = 0; @@ -1316,7 +1340,7 @@ export const ChatInput = memo(forwardRef(function ChatIn setDraft(previousDraftKey, { value: valueRef.current, images: attachedImagesRef.current.map(imageToDraftImage), - files: attachedTextFilesRef.current.map(textFileToDraftFile), + files: attachedTextFilesToDraftFiles(attachedTextFilesRef.current, attachedUploadsRef.current), uploads: attachedUploadsToDraftUploads(attachedUploadsRef.current), }); } diff --git a/lib/chat-attachments.test.mjs b/lib/chat-attachments.test.mjs index c1bd6f9c5..039941255 100644 --- a/lib/chat-attachments.test.mjs +++ b/lib/chat-attachments.test.mjs @@ -1141,3 +1141,66 @@ test("readAttachmentText extracts .doc when 1Table is stored in the OLE2 mini-st const result = await readAttachmentText(mockFile("ministream.doc", "application/msword", oleBuf)); assert.equal(result, text); }); + +test("readAttachmentText bounds hostile unclosed XML tags in XLSX and EPUB and hostile PDF digit/string streams in linear time", async () => { + const { readAttachmentText } = await loadSubject(); + + // 1. workbook.xml.rels filled with unclosed ` + `` }, + ]); + const t0 = performance.now(); + await readAttachmentText( + mockFile("hostile-rels.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xlsxRelsZip), + ); + const relsMs = performance.now() - t0; + assert.ok(relsMs < 250, `Expected linear scan on unclosed ` + `` + + `` }, + { name: "OEBPS/content.opf", data: unclosedOpf }, + ]); + const t2 = performance.now(); + await readAttachmentText(mockFile("hostile.epub", "application/epub+zip", epubZip)); + const epubMs = performance.now() - t2; + assert.ok(epubMs < 250, `Expected linear scan on unclosed EPUB >\nstream\nBT (Fast) Tj ET\nendstream\nendobj\n`, "latin1"); + const t3 = performance.now(); + const pdfDigitRes = await readAttachmentText(mockFile("digits.pdf", "application/pdf", hostilePdfDigits)); + const pdfDigitMs = performance.now() - t3; + assert.equal(pdfDigitRes, "Fast"); + assert.ok(pdfDigitMs < 250, `Expected linear scan on 100 KB PDF digit run (< 250ms), took ${pdfDigitMs.toFixed(1)}ms`); + + // 5. PDF text stream BT followed by 200 KB of repeated unclosed escaped strings + const unclosedStreamBody = `BT (Valid) Tj ` + `(abc\\(def`.repeat(23_000) + `\nET`; + const hostilePdfStream = Buffer.from( + `%PDF-1.4\n1 0 obj\n<< /Length ${unclosedStreamBody.length} >>\nstream\n${unclosedStreamBody}\nendstream\nendobj\n`, + "latin1", + ); + const t4 = performance.now(); + const pdfStreamRes = await readAttachmentText(mockFile("unclosed-stream.pdf", "application/pdf", hostilePdfStream)); + const pdfStreamMs = performance.now() - t4; + assert.equal(pdfStreamRes, "Valid"); + assert.ok(pdfStreamMs < 250, `Expected linear scan on 200 KB unclosed PDF strings (< 250ms), took ${pdfStreamMs.toFixed(1)}ms`); +}); diff --git a/lib/chat-attachments.ts b/lib/chat-attachments.ts index e4fdac773..94e7b05a6 100644 --- a/lib/chat-attachments.ts +++ b/lib/chat-attachments.ts @@ -325,7 +325,7 @@ export function walkXml( const spaceIdx = rawTag.search(/\s/); if (spaceIdx !== -1) { name = rawTag.slice(0, spaceIdx); - attrs = rawTag.slice(spaceIdx + 1).trim(); + attrs = rawTag.slice(spaceIdx + 1, spaceIdx + 1 + 8192).trim(); } if (onTag(name, isClose, selfClosing, attrs) === false) { @@ -473,10 +473,18 @@ function parseCMap(cmapStr: string, cmapBudget: DecompressBudget): PdfCMap { const block = cmapStr.slice(contentStart, endIdx); pos = endIdx + "endcodespacerange".length; - const pairRegex = /<([0-9a-fA-F]+)>\s*<([0-9a-fA-F]+)>/g; - let pm: RegExpExecArray | null; - while ((pm = pairRegex.exec(block)) !== null) { - if (pm[1].length >= 4) codeBytes = 2; + let cPos = 0; + while (cPos < block.length) { + const lt1 = block.indexOf("<", cPos); + if (lt1 === -1) break; + const gt1 = block.indexOf(">", lt1 + 1); + if (gt1 === -1) break; + const lt2 = block.indexOf("<", gt1 + 1); + if (lt2 === -1) break; + const gt2 = block.indexOf(">", lt2 + 1); + if (gt2 === -1) break; + if (gt1 - lt1 - 1 >= 4) codeBytes = 2; + cPos = gt2 + 1; } } @@ -490,11 +498,23 @@ function parseCMap(cmapStr: string, cmapBudget: DecompressBudget): PdfCMap { const block = cmapStr.slice(contentStart, endIdx); pos = endIdx + "endbfchar".length; - const pairRegex = /<([0-9a-fA-F]+)>\s*<([0-9a-fA-F]+)>/g; - let pm: RegExpExecArray | null; - while ((pm = pairRegex.exec(block)) !== null && --cmapBudget.remaining >= 0 && ++totalEntries <= MAX_CMAP_ITERATIONS) { - if (pm[1].length >= 4) codeBytes = 2; - map.set(parseInt(pm[1], 16), decodeCMapTargetHex(pm[2])); + let cPos = 0; + while (cPos < block.length && cmapBudget.remaining > 0 && totalEntries < MAX_CMAP_ITERATIONS) { + const lt1 = block.indexOf("<", cPos); + if (lt1 === -1) break; + const gt1 = block.indexOf(">", lt1 + 1); + if (gt1 === -1) break; + const lt2 = block.indexOf("<", gt1 + 1); + if (lt2 === -1) break; + const gt2 = block.indexOf(">", lt2 + 1); + if (gt2 === -1) break; + const srcHex = block.slice(lt1 + 1, gt1).trim(); + const dstHex = block.slice(lt2 + 1, gt2).trim(); + cPos = gt2 + 1; + if (!srcHex || !dstHex) continue; + if (--cmapBudget.remaining < 0 || ++totalEntries > MAX_CMAP_ITERATIONS) break; + if (srcHex.length >= 4) codeBytes = 2; + map.set(parseInt(srcHex, 16), decodeCMapTargetHex(dstHex)); } } @@ -653,23 +673,201 @@ function bytesToBinaryString(bytes: Uint8Array): string { return out; } +function isPdfAsciiWhitespace(code: number): boolean { + return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d || code === 0x0c || code === 0x00; +} + +function isPdfAsciiDigit(code: number): boolean { + return code >= 0x30 && code <= 0x39; +} + +function isPdfAsciiWord(code: number): boolean { + return (code >= 0x30 && code <= 0x39) || (code >= 0x41 && code <= 0x5a) || (code >= 0x61 && code <= 0x7a) || code === 0x5f; +} + +/** Linear O(N) scan for ` obj` headers using indexOf("obj") with bounded lookbehind. */ +function findNextPdfObjHeader(latin1: string, fromIndex: number): { id: number; bodyStart: number } | null { + const len = latin1.length; + let pos = fromIndex; + while (pos < len) { + const objIdx = latin1.indexOf("obj", pos); + if (objIdx === -1) return null; + const bodyStart = objIdx + 3; + pos = bodyStart; + if (bodyStart < len && isPdfAsciiWord(latin1.charCodeAt(bodyStart))) continue; + let cur = objIdx - 1; + if (cur < fromIndex || !isPdfAsciiWhitespace(latin1.charCodeAt(cur))) continue; + let ws1 = 0; + while (cur >= fromIndex && ws1 < 32 && isPdfAsciiWhitespace(latin1.charCodeAt(cur))) { + cur--; + ws1++; + } + if (cur >= fromIndex && isPdfAsciiWhitespace(latin1.charCodeAt(cur))) continue; + let genDigits = 0; + while (cur >= fromIndex && genDigits <= 10 && isPdfAsciiDigit(latin1.charCodeAt(cur))) { + cur--; + genDigits++; + } + if (genDigits === 0 || genDigits > 10) continue; + if (cur < fromIndex || !isPdfAsciiWhitespace(latin1.charCodeAt(cur))) continue; + let ws2 = 0; + while (cur >= fromIndex && ws2 < 32 && isPdfAsciiWhitespace(latin1.charCodeAt(cur))) { + cur--; + ws2++; + } + if (cur >= fromIndex && isPdfAsciiWhitespace(latin1.charCodeAt(cur))) continue; + const idEnd = cur; + let idDigits = 0; + while (cur >= fromIndex && idDigits <= 10 && isPdfAsciiDigit(latin1.charCodeAt(cur))) { + cur--; + idDigits++; + } + if (idDigits === 0 || idDigits > 10) continue; + if (cur >= 0 && isPdfAsciiWord(latin1.charCodeAt(cur))) continue; + const id = parseInt(latin1.slice(cur + 1, idEnd + 1), 10); + if (!Number.isFinite(id)) continue; + return { id, bodyStart }; + } + return null; +} + +const PDF_STREAM_OPS = new Set([ + "BT", "ET", "Tf", "Tm", "Td", "TD", "TL", "Tc", "Tw", "Tz", "cm", "q", "Q", "Tj", "TJ", "T*", "'", '"', +]); + +type PdfStreamToken = + | { kind: "name"; value: string; nextPos: number } + | { kind: "literal"; value: string; nextPos: number } + | { kind: "hex"; value: string; nextPos: number } + | { kind: "bracket"; value: "[" | "]"; nextPos: number } + | { kind: "number"; value: string; nextPos: number } + | { kind: "op"; value: string; nextPos: number } + | { kind: "other"; value: string; nextPos: number }; + +/** Strictly linear O(N) PDF content stream tokenizer; never backtracks on unclosed strings or hex blocks. */ +function nextPdfStreamToken(s: string, startPos: number): PdfStreamToken | null { + const len = s.length; + let pos = startPos; + while (pos < len) { + const ch = s.charCodeAt(pos); + if (ch <= 0x20) { + pos++; + continue; + } + if (ch === 0x25) { + pos++; + while (pos < len && s.charCodeAt(pos) !== 0x0a && s.charCodeAt(pos) !== 0x0d) pos++; + continue; + } + if (ch === 0x2f) { + const nameStart = ++pos; + while (pos < len) { + const c = s.charCodeAt(pos); + if ( + (c >= 0x30 && c <= 0x39) + || (c >= 0x41 && c <= 0x5a) + || (c >= 0x61 && c <= 0x7a) + || c === 0x5f || c === 0x2e || c === 0x2d + ) { + pos++; + } else { + break; + } + } + return { kind: "name", value: s.slice(nameStart, pos), nextPos: pos }; + } + if (ch === 0x28) { + const bodyStart = ++pos; + let depth = 1; + while (pos < len && depth > 0) { + const c = s.charCodeAt(pos++); + if (c === 0x5c) { + if (pos < len) pos++; + } else if (c === 0x28) { + depth++; + } else if (c === 0x29) { + depth--; + } + } + if (depth > 0) return null; + return { kind: "literal", value: s.slice(bodyStart, pos - 1), nextPos: pos }; + } + if (ch === 0x3c) { + if (pos + 1 < len && s.charCodeAt(pos + 1) === 0x3c) { + pos += 2; + continue; + } + const hexStart = pos + 1; + const gt = s.indexOf(">", hexStart); + if (gt === -1) return null; + return { kind: "hex", value: s.slice(hexStart, gt), nextPos: gt + 1 }; + } + if (ch === 0x3e) { + pos += pos + 1 < len && s.charCodeAt(pos + 1) === 0x3e ? 2 : 1; + continue; + } + if (ch === 0x5b || ch === 0x5d) { + return { kind: "bracket", value: ch === 0x5b ? "[" : "]", nextPos: pos + 1 }; + } + if (ch === 0x27 || ch === 0x22) { + return { kind: "op", value: s[pos], nextPos: pos + 1 }; + } + if (ch === 0x2b || ch === 0x2d || ch === 0x2e || (ch >= 0x30 && ch <= 0x39)) { + const numStart = pos; + if (ch === 0x2b || ch === 0x2d) pos++; + let digits = 0; + while (pos < len && s.charCodeAt(pos) >= 0x30 && s.charCodeAt(pos) <= 0x39) { + pos++; + digits++; + } + if (pos < len && s.charCodeAt(pos) === 0x2e) { + pos++; + while (pos < len && s.charCodeAt(pos) >= 0x30 && s.charCodeAt(pos) <= 0x39) { + pos++; + digits++; + } + } + if (digits > 0) { + return { kind: "number", value: s.slice(numStart, pos), nextPos: pos }; + } + pos = numStart + 1; + continue; + } + if ((ch >= 0x41 && ch <= 0x5a) || (ch >= 0x61 && ch <= 0x7a) || ch === 0x2a) { + const opStart = pos++; + while (pos < len) { + const c = s.charCodeAt(pos); + if ((c >= 0x41 && c <= 0x5a) || (c >= 0x61 && c <= 0x7a) || c === 0x2a) { + pos++; + } else { + break; + } + } + const word = s.slice(opStart, pos); + return { kind: PDF_STREAM_OPS.has(word) ? "op" : "other", value: word, nextPos: pos }; + } + pos++; + } + return null; +} + /** Extracts text streams and character mappings from PDF file buffer. */ async function extractPdfText(buf: ArrayBuffer): Promise { const budget: DecompressBudget = { remaining: MAX_DECOMPRESSED_BYTES }; const latin1 = bytesToBinaryString(new Uint8Array(buf)); - const objHeaderRegex = /(\d+)\s+\d+\s+obj\b/g; const streamMarkerRe = />>\s*stream(?:\r?\n|\r)/g; const nonTextStreamRe = /\/Subtype\s*\/(?:Image|Type1C|CIDFontType0C|OpenType)\b|\/Length[123]\b|\/Type\s*\/(?:XRef|Metadata|EmbeddedFile)\b|\/BitsPerComponent\b/; const objects = new Map(); let totalObjStmBytes = 0; - let m: RegExpExecArray | null; - while ((m = objHeaderRegex.exec(latin1)) !== null) { + let searchPos = 0; + while (searchPos < latin1.length) { if (objects.size >= MAX_PDF_OBJECTS) break; - const id = parseInt(m[1], 10); - const bodyStart = m.index + m[0].length; + const header = findNextPdfObjHeader(latin1, searchPos); + if (!header) break; + const { id, bodyStart } = header; const endObjIdx = latin1.indexOf("endobj", bodyStart); if (endObjIdx === -1) break; - objHeaderRegex.lastIndex = endObjIdx + 6; + searchPos = endObjIdx + 6; const body = latin1.slice(bodyStart, endObjIdx); const endStreamIdx = body.indexOf("endstream"); const dictStart = endStreamIdx !== -1 ? body.indexOf("<<") : -1; @@ -837,9 +1035,6 @@ async function extractPdfText(buf: ArrayBuffer): Promise { const lines: string[] = []; let globalSeq = 0; let globalBtId = 0; - const streamTokenRe = - /\/([A-Za-z0-9_.-]+)|\((?:\\[\s\S]|[^\\()])*\)|<([0-9a-fA-F\s]+)>|(\[|\])|([-+]?(?:\d+\.?\d*|\.\d+))|(\b(?:BT|ET|Tf|Tm|Td|TD|TL|Tc|Tw|Tz|cm|q|Q|Tj|TJ)\b|\bT\*|['"])|\b([A-Za-z*]+)\b/g; - let totalStreamTokens = 0; for (const [, obj] of objects) { if (totalStreamTokens >= MAX_PDF_STREAM_TOKENS) break; @@ -898,32 +1093,33 @@ async function extractPdfText(buf: ArrayBuffer): Promise { tmMat = mulMat([1, 0, 0, 1, advText, 0], tmMat); }; - streamTokenRe.lastIndex = 0; - let tok: RegExpExecArray | null; - while ((tok = streamTokenRe.exec(obj.streamText)) !== null) { + let streamPos = 0; + let tok: PdfStreamToken | null; + while ((tok = nextPdfStreamToken(obj.streamText, streamPos)) !== null) { + streamPos = tok.nextPos; if (++totalStreamTokens > MAX_PDF_STREAM_TOKENS) break; - if (tok[1] !== undefined) { - pendingName = tok[1]; - } else if (tok[0].startsWith("(")) { + if (tok.kind === "name") { + pendingName = tok.value; + } else if (tok.kind === "literal") { if (inText) { - const bytes = decodePdfLiteralBytes(tok[0].slice(1, -1)); + const bytes = decodePdfLiteralBytes(tok.value); appendDecodedText(decodeBytesWithPdfCMap(bytes, resolveFontCMap(currentFont))); } - } else if (tok[2] !== undefined) { + } else if (tok.kind === "hex") { if (inText) { - const bytes = decodePdfHexBytes(tok[2]); + const bytes = decodePdfHexBytes(tok.value); appendDecodedText(decodeBytesWithPdfCMap(bytes, resolveFontCMap(currentFont))); } - } else if (tok[3] !== undefined) { - if (tok[3] === "[") { + } else if (tok.kind === "bracket") { + if (tok.value === "[") { inTjArray = true; numStack.length = 0; } else { inTjArray = false; numStack.length = 0; } - } else if (tok[4] !== undefined) { - const num = parseFloat(tok[4]); + } else if (tok.kind === "number") { + const num = parseFloat(tok.value); if (Number.isFinite(num)) { if (inText && inTjArray) { if (num <= -150) { @@ -936,8 +1132,8 @@ async function extractPdfText(buf: ArrayBuffer): Promise { if (numStack.length > 6) numStack.shift(); } } - } else if (tok[5] !== undefined) { - const op = tok[5]; + } else if (tok.kind === "op") { + const op = tok.value; if (op === "BT") { flushRun(); inText = true; @@ -1007,7 +1203,7 @@ async function extractPdfText(buf: ArrayBuffer): Promise { } numStack.length = 0; pendingName = null; - } else if (tok[6] !== undefined) { + } else if (tok.kind === "other") { numStack.length = 0; pendingName = null; } @@ -1271,36 +1467,40 @@ async function extractXlsx(entries: Map Promise>, stat const relsFn = entries.get("xl/_rels/workbook.xml.rels"); const relMap = new Map(); if (relsFn) { - const relBuf = await relsFn(); - const relXml = new TextDecoder("utf-8").decode(relBuf); - const relRegex = /]*)\/>/g; - let m: RegExpExecArray | null; - while ((m = relRegex.exec(relXml)) !== null) { - const idMatch = m[1].match(/\bId="([^"]+)"/); - const targetMatch = m[1].match(/\bTarget="([^"]+)"/); - if (idMatch && targetMatch) { - const target = targetMatch[1]; - relMap.set(idMatch[1], target.startsWith("/") ? target.slice(1) : (target.startsWith("xl/") ? target : `xl/${target}`)); + const relsBuf = await relsFn(); + const relsXml = new TextDecoder("utf-8").decode(relsBuf); + const ok = walkXml(relsXml, tagBudget, (tagName, isClose, _selfClosing, attrs) => { + if (!isClose && (tagName === "Relationship" || tagName.endsWith(":Relationship"))) { + const idMatch = attrs.match(/\bId="([^"]+)"/); + const targetMatch = attrs.match(/\bTarget="([^"]+)"/); + if (idMatch && targetMatch) { + let t = targetMatch[1].replace(/^\//, ""); + if (!t.startsWith("xl/")) t = "xl/" + t; + relMap.set(idMatch[1], t); + } } - } + }); + if (!ok) return null; } const wbFn = entries.get("xl/workbook.xml"); - const sheets: Array<{ name: string; target: string | null }> = []; + const sheets: Array<{ name: string; target: string }> = []; if (wbFn) { const wbBuf = await wbFn(); const wbXml = new TextDecoder("utf-8").decode(wbBuf); - const sheetRegex = /]*)\/>/g; - let m: RegExpExecArray | null; - while ((m = sheetRegex.exec(wbXml)) !== null) { - const nameMatch = m[1].match(/\bname="([^"]+)"/); - const rIdMatch = m[1].match(/\br:id="([^"]+)"/); - const name = nameMatch ? decodeXmlEntities(nameMatch[1]) : "Sheet"; - const target = rIdMatch ? relMap.get(rIdMatch[1]) || null : null; - sheets.push({ name, target }); - } + const ok = walkXml(wbXml, tagBudget, (tagName, isClose, _selfClosing, attrs) => { + if (!isClose && (tagName === "sheet" || tagName.endsWith(":sheet"))) { + const nameMatch = attrs.match(/\bname="([^"]+)"/); + const rIdMatch = attrs.match(/\br:id="([^"]+)"/); + if (nameMatch) { + const name = decodeXmlEntities(nameMatch[1]); + const target = rIdMatch ? relMap.get(rIdMatch[1]) || "" : ""; + sheets.push({ name, target }); + } + } + }); + if (!ok) return null; } - const sections: string[] = []; const visitedSheets = new Set(); const encoder = new TextEncoder(); @@ -1677,13 +1877,19 @@ async function extractOdf(entries: Map Promise>, state /** Extracts chapter text from EPUB archive spine in reading order. */ async function extractEpub(entries: Map Promise>): Promise { + const tagBudget: XmlTagBudget = { tags: 0, maxTags: MAX_XML_TAGS }; let rootFile = "OEBPS/content.opf"; const containerFn = entries.get("META-INF/container.xml"); if (containerFn) { const cBuf = await containerFn(); const cXml = new TextDecoder("utf-8").decode(cBuf); - const m = cXml.match(/full-path="([^"]+)"/); - if (m) rootFile = m[1]; + const ok = walkXml(cXml, tagBudget, (tagName, isClose, _selfClosing, attrs) => { + if (!isClose && (tagName === "rootfile" || tagName.endsWith(":rootfile"))) { + const m = attrs.match(/\bfull-path="([^"]+)"/); + if (m) rootFile = m[1]; + } + }); + if (!ok) return null; } const opfFn = entries.get(rootFile); @@ -1693,27 +1899,30 @@ async function extractEpub(entries: Map Promise>): Pro const basePath = rootFile.includes("/") ? rootFile.replace(/\/[^/]*$/, "/") : ""; const manifest = new Map(); - const itemRegex = /]*)\/>/g; - let im: RegExpExecArray | null; - while ((im = itemRegex.exec(opfXml)) !== null) { - const idMatch = im[1].match(/\bid="([^"]+)"/); - const hrefMatch = im[1].match(/\bhref="([^"]+)"/); - if (idMatch && hrefMatch) { - manifest.set(idMatch[1], hrefMatch[1]); + const spineRefs: string[] = []; + const opfOk = walkXml(opfXml, tagBudget, (tagName, isClose, _selfClosing, attrs) => { + if (isClose) return; + if (tagName === "item" || tagName.endsWith(":item")) { + const idMatch = attrs.match(/\bid="([^"]+)"/); + const hrefMatch = attrs.match(/\bhref="([^"]+)"/); + if (idMatch && hrefMatch) { + manifest.set(idMatch[1], hrefMatch[1]); + } + } else if (tagName === "itemref" || tagName.endsWith(":itemref")) { + const idrefMatch = attrs.match(/\bidref="([^"]+)"/); + if (idrefMatch) { + spineRefs.push(idrefMatch[1]); + } } - } + }); + if (!opfOk) return null; const spine: string[] = []; - const itemrefRegex = /]*)\/>/g; - let irMatch: RegExpExecArray | null; - while ((irMatch = itemrefRegex.exec(opfXml)) !== null) { - const idrefMatch = irMatch[1].match(/\bidref="([^"]+)"/); - if (idrefMatch && manifest.has(idrefMatch[1])) { - spine.push(manifest.get(idrefMatch[1])!); + for (const idref of spineRefs) { + if (manifest.has(idref)) { + spine.push(manifest.get(idref)!); } } - - const tagBudget: XmlTagBudget = { tags: 0, maxTags: MAX_XML_TAGS }; const chapters: string[] = []; const visitedChapters = new Set();