diff --git a/components/ChatInput-draft-attachments.ts b/components/ChatInput-draft-attachments.ts index 6a6bbe004..9a652269f 100644 --- a/components/ChatInput-draft-attachments.ts +++ b/components/ChatInput-draft-attachments.ts @@ -32,19 +32,43 @@ 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 } : {}), + }; +} + +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. */ 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 cf00dfbd4..79db12c9d 100644 --- a/components/ChatInput.queue-attachments.test.mjs +++ b/components/ChatInput.queue-attachments.test.mjs @@ -1397,6 +1397,53 @@ for (const holdUpload of [false, true]) { }); } +test("drops candidates expanding beyond per-file and aggregate limits post-read", async () => { + const { MAX_ATTACHED_TEXT_BYTES, MAX_TOTAL_ATTACHED_TEXT_BYTES } = await 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"); + }); +}); + 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; @@ -1462,6 +1509,573 @@ test("a completed slash builtin must not erase an attachment added while its cal 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"); + }); +}); + +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 (msg) => { + sentMessages.push(msg); + return { status: "accepted" }; + }, + })); + + 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", + }); + 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([secretFile, keepFile]); + }); + + const removeBtns = await screen.findAllByLabelText(/chatInput\.removeFile|Remove file/i); + assert.equal(removeBtns.length, 2); + fireEvent.click(removeBtns[0]); + + await act(async () => { + resolveSecret(); + await new Promise((resolve) => setImmediate(resolve)); + }); + + 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 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)); + }); + } + + 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 }); + } + 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)); + } + + 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}-outbox-race`, + isStreaming: false, + outbox: true, + onAbort() {}, + onSend: (msg) => { + sentMessages.push(msg); + return new Promise((resolve) => { + resolveOutbox = () => resolve({ status: "accepted" }); + }); + }, + })); + + 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([slowDoc]); + await new Promise((resolve) => setImmediate(resolve)); + }); + + const textarea = screen.getByRole("textbox"); + fireEvent.change(textarea, { target: { value: "Send with doc" } }); + + // 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.equal(sentMessages.length, 1, "second Enter does not resubmit already-sent draft"); +}); + test("a rejected attachment prompt retains its files rather than becoming a shell command on retry", async () => { const file = { name: "notes.txt", mimeType: "text/plain", content: "echo attachment-content", size: 23 }; setDraft(KEY, { value: "!!explain this", images: [], files: [file] }); diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 359027f91..027a35000 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -19,6 +19,7 @@ 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, @@ -62,8 +63,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, @@ -470,6 +481,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 = !promptOnly && attachedImages.length === 0 && attachedTextFiles.length === 0 && attachedUploads.length === 0 && trimmedValue.startsWith("!"); const bashExcluded = bashMode && trimmedValue.startsWith("!!"); @@ -564,6 +576,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()); @@ -580,7 +603,7 @@ export const ChatInput = memo(forwardRef(function ChatIn const draft: ChatDraft = { value: valueRef.current, images: attachedImagesRef.current.map(imageToDraftImage), - files: attachedTextFilesRef.current.map(textFileToDraftFile), + files: attachedTextFilesToDraftFiles(attachedTextFilesRef.current, uploads), ...(promptOnlyRef.current ? { promptOnly: true } : {}), uploads, }; @@ -675,7 +698,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 @@ -707,9 +735,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 => ({ @@ -721,20 +749,20 @@ 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` })); } 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. */ @@ -758,7 +786,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(); @@ -770,7 +798,7 @@ export const ChatInput = memo(forwardRef(function ChatIn try { const newImages = await Promise.all( imageFiles.map(async (file) => { - const image: AttachedImage = { data: await readBase64(file), mimeType: file.type, previewUrl: URL.createObjectURL(file), file }; + const image: AttachedImage = { data: await readBase64(file), mimeType: inferImageMimeType(file), previewUrl: URL.createObjectURL(file), file }; created.push(image); return image; }), @@ -796,62 +824,234 @@ 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]); - /** 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[]) => { - // 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)), { + 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); + } + // 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, }); - attachAsFiles(files.filter((file) => !textFiles.includes(file))); - if (!textFiles.length) return; + 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) { + const skipNotice = describeTextAttachmentSkip({ tooLarge: skipTooLarge, overBudget: skipOverBudget }); + if (skipNotice) setAttachNotice(skipNotice); + return; + } markInputEdited(); const revision = attachmentRevisionRef.current; const identityRevision = attachmentIdentityRevisionRef.current; - pendingTextFileCountRef.current += textFiles.length; - pendingTextFileBytesRef.current += textFiles.reduce((total, file) => total + file.size, 0); + 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); try { + type ReadCandidate = + | { status: "binary"; file: File; isDoc: boolean } + | { status: "text"; file: File; isDoc: boolean; attachedFile: AttachedTextFile }; + const readFiles = await Promise.all( - textFiles.map(async (file): Promise => ({ - name: file.name, - mimeType: file.type, - content: await file.text(), - size: file.size, - })), + 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", file, isDoc }; + } + const contentBytes = new TextEncoder().encode(content).byteLength; + const upload = docUploadMap.get(file); + return { + status: "text", + file, + isDoc, + attachedFile: { + name: file.name, + mimeType: file.type, + content, + size: contentBytes, + ...(upload ? { uploadId: upload.id } : {}), + }, + }; + }), ); // 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 binary = readFiles.map((file) => file.content.includes("\u0000") || file.content.includes("\uFFFD")); - const newFiles = readFiles.filter((_, index) => !binary[index]); - attachAsFiles(textFiles.filter((_, index) => binary[index])); - setAttachedTextFiles((prev) => [ - ...prev, - ...(identityRevision !== attachmentIdentityRevisionRef.current - ? newFiles - : newFiles.slice(0, Math.max(0, MAX_ATTACHED_TEXT_FILES - prev.length))), - ]); + + // 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 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 textCandidates: Array<{ file: File; isDoc: boolean; attachedFile: AttachedTextFile; size: number }> = []; + + for (const candidate of activeCandidates) { + if (candidate.status === "binary") { + if (!candidate.isDoc) { + fallbackAsFiles.push(candidate.file); + } else if (wasOversizedDocumentText(candidate.file)) { + skipTooLarge++; + } + continue; + } + 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); + } + if (candidate.isDoc || identityRevision !== attachmentIdentityRevisionRef.current) { + if (candidate.size > MAX_ATTACHED_TEXT_BYTES) { + skipTooLarge++; + } else { + skipOverBudget++; + } + } + } + } + + if (fallbackAsFiles.length > 0) { + attachAsFiles(fallbackAsFiles); + } + + if (validTextCandidates.length > 0) { + attachedTextFilesRef.current = [...attachedTextFilesRef.current, ...validTextCandidates.map((c) => c.attachedFile)]; + } + + setAttachedTextFiles((prev) => { + 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 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)]; + if ( + attachedTextFilesRef.current.length === next.length + && attachedTextFilesRef.current.every((item, idx) => item === next[idx]) + ) { + return attachedTextFilesRef.current; + } + attachedTextFilesRef.current = next; + return next; + }); + + const skipNotice = describeTextAttachmentSkip({ tooLarge: skipTooLarge, overBudget: skipOverBudget }); + if (skipNotice) setAttachNotice(skipNotice); } catch { setAttachError(t("chatInput.attachmentTextReadFailed")); } finally { - pendingTextFileCountRef.current -= textFiles.length; - pendingTextFileBytesRef.current -= textFiles.reduce((total, file) => total + file.size, 0); + for (const file of acceptedFiles) { + settleInFlightTextRead(file); + } } - }, [attachAsFiles, markInputEdited, t]); + }, [attachAsFiles, markInputEdited, settleInFlightTextRead, t]); 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]); @@ -904,9 +1104,15 @@ 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) => { + const next = typeof target === "number" + ? prev.filter((_, fileIndex) => fileIndex !== target) + : prev.filter((file) => file !== target); + attachedTextFilesRef.current = next; + return next; + }); setAttachError(null); }, [markInputEdited]); @@ -918,6 +1124,7 @@ export const ChatInput = memo(forwardRef(function ChatIn }, []); const clearTextFiles = useCallback(() => { + attachedTextFilesRef.current = []; setAttachedTextFiles([]); }, []); @@ -926,17 +1133,24 @@ 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); 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); - }, [markInputEdited]); + }, [markInputEdited, settleInFlightTextRead]); const retryUpload = useCallback((id: string) => { const upload = attachedUploadsRef.current.find((each) => each.id === id); @@ -953,7 +1167,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]); @@ -972,8 +1186,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 { @@ -987,6 +1202,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 []; @@ -1005,6 +1221,12 @@ export const ChatInput = memo(forwardRef(function ChatIn clearTextFiles(); clearUploads(); setAttachNotice(null); + inFlightTextReadsRef.current.clear(); + 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) { @@ -1103,7 +1325,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) => [ @@ -1118,6 +1342,12 @@ 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; + pendingTextFileBytesRef.current = 0; + setPendingTextReadCount(0); draftRecoveryIdentityRef.current = { key: draftKey }; setAttachError(null); setAttachNotice(null); @@ -1138,14 +1368,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, setPromptOnly, captureDraft]); @@ -1222,9 +1456,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 @@ -1261,7 +1496,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 = !promptOnlyRef.current && msg.startsWith("!") && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length; if (submissionBlockedRef.current || holdingRef.current || (isStreaming && !shellCommand)) return; @@ -1758,7 +1993,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 (!promptOnlyRef.current && msg.startsWith("!") && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length) { @@ -1829,8 +2064,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); @@ -2518,67 +2756,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 645fe5018..039941255 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(); @@ -98,3 +356,851 @@ test("formats attachment limits for the composer", async () => { assert.equal(formatAttachmentBytes(512 * 1024), "512 KB"); assert.equal(formatAttachmentBytes(4 * 1024 * 1024), "4 MB"); }); + +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); +}); + +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 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(); + + 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("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("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("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, + 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.", + ); +}); + +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"); +}); + +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); +}); + +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 559814685..94e7b05a6 100644 --- a/lib/chat-attachments.ts +++ b/lib/chat-attachments.ts @@ -27,8 +27,10 @@ export interface AttachedTextFileData { mimeType: string; content: string; size: number; + uploadId?: string; } +/** Extracts lowercased file extension without leading dot. */ function getFileExtension(name: string): string { return name.toLowerCase().replace(/\\/g, "/").split("/").pop()?.split(".").pop() ?? ""; } @@ -86,18 +88,87 @@ export function selectTextAttachments( return { accepted, tooLarge, overBudget }; } +/** Banner text for a batch that produced no usable attachments. */ +export function describeTextAttachmentSkip( + selection: Pick, "tooLarge" | "overBudget">, +): string | null { + if (selection.tooLarge > 0) { + return `${selection.tooLarge} file(s) skipped: files up to ${formatAttachmentBytes(MAX_ATTACHED_TEXT_BYTES)} are supported.`; + } + if (selection.overBudget > 0) { + return `${selection.overBudget} file(s) skipped: attachments are limited to ${formatAttachmentBytes(MAX_TOTAL_ATTACHED_TEXT_BYTES)} per message.`; + } + 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" || 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", +}; + +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 { + const mime = file.type?.toLowerCase() ?? ""; + if (mime.startsWith("image/")) { + return !UNSUPPORTED_INLINE_IMAGE_MIME_TYPES[mime]; + } + if (!mime || mime === "application/octet-stream") { + const ext = getFileExtension(file.name); + return Boolean(RASTER_IMAGE_EXTENSIONS[ext]); + } + 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; + } + const ext = getFileExtension(file.name); + 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 (extension === "md" || extension === "markdown" || extension === "mdx") return "markdown"; + 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)); @@ -115,3 +186,2242 @@ export function composeMessageWithTextAttachments( }); return [message.trim(), ...blocks].filter(Boolean).join("\n\n"); } + +/** 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; + }); +} + +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; + +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; + +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, spaceIdx + 1 + 8192).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; +} + +/** Decompresses deflate data stream while enforcing byte budget. */ +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; +} + +/** 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; + 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; +} + +/** 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) { + 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; +} + +/** 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; + 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; + + 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; + } + } + + 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; + + 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)); + } + } + + 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 && ++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 (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; + } + } + } + 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++) { + 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); +} + +/** 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); + 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; +} + +/** 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) { + 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; +} + +/** Converts byte array to binary Latin-1 string in bounded chunks. */ +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; +} + +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 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 searchPos = 0; + while (searchPos < latin1.length) { + if (objects.size >= MAX_PDF_OBJECTS) break; + const header = findNextPdfObjHeader(latin1, searchPos); + if (!header) break; + const { id, bodyStart } = header; + const endObjIdx = latin1.indexOf("endobj", bodyStart); + if (endObjIdx === -1) break; + searchPos = 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); + 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++) { + 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); + 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 }); + } + } + } + } + } 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) { + 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(dictSlice); + 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 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(dictSlice)) !== 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; + }; + + 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; + 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[] = []; + let tmMat: Mat2D = [1, 0, 0, 1, 0, 0]; + let tlmMat: Mat2D = [1, 0, 0, 1, 0, 0]; + let currentFont: string | null = null; + 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 = (): 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) => { + 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); + }; + + 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.kind === "name") { + pendingName = tok.value; + } else if (tok.kind === "literal") { + if (inText) { + const bytes = decodePdfLiteralBytes(tok.value); + appendDecodedText(decodeBytesWithPdfCMap(bytes, resolveFontCMap(currentFont))); + } + } else if (tok.kind === "hex") { + if (inText) { + const bytes = decodePdfHexBytes(tok.value); + appendDecodedText(decodeBytesWithPdfCMap(bytes, resolveFontCMap(currentFont))); + } + } else if (tok.kind === "bracket") { + if (tok.value === "[") { + inTjArray = true; + numStack.length = 0; + } else { + inTjArray = false; + numStack.length = 0; + } + } else if (tok.kind === "number") { + const num = parseFloat(tok.value); + 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.kind === "op") { + const op = tok.value; + 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 = 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 = 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.kind === "other") { + 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] }); + } + } + 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; +} + +/** 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); + 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; +} + +/** 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()) { + if (/^word\/(?:header|footer)\d*\.xml$/.test(name)) { + 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); + + 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) { + tableRows = []; + totalCellsInTable = 0; + } else { + 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; + } + } 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"; + } + }, + (text) => { + if (inT) { + const decoded = decodeXmlEntities(text); + if (inCell) { + cellText += decoded; + } else if (inPara) { + paraText += decoded; + } + } + }, + ); + 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; +} + +/** Extracts worksheets and shared strings from OOXML XLSX into Markdown tables. */ +async function extractXlsx(entries: Map Promise>, state?: { oversized?: boolean }): 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); + 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"); + const relMap = new Map(); + if (relsFn) { + 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 }> = []; + if (wbFn) { + const wbBuf = await wbFn(); + const wbXml = new TextDecoder("utf-8").decode(wbBuf); + 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(); + 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`; + 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[][] = []; + let rawCellBytes = 0; + 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; + rowCells = new Map(); + rowMaxCol = 0; + } else { + 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; + } + } + } 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) { + if (state) state.oversized = true; + 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; + } + }, + (text) => { + if (inCell && (inV || inT)) { + cellRawText += text; + } + }, + ); + + if (!ok) return null; + + if (rows.length > 0) { + 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) { + if (state) state.oversized = true; + return null; + } + projectedBytes += sectionSeparatorBytes + sheetBytes; + sections.push(heading + tableMd); + } + } + + const res = sections.join("\n\n").trim(); + 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()) { + 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 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: [] }); + const fn = entries.get(item.name); + if (!fn) continue; + const buf = await fn(); + const xml = new TextDecoder("utf-8").decode(buf); + + let inP = false; + let inT = false; + let pText = ""; + const pList: string[] = []; + + 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 { + 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; +} + +/** Extracts paragraphs and tables from OpenDocument (ODT/ODS/ODP) content. */ +async function extractOdf(entries: Map Promise>, state?: { oversized?: boolean }): Promise { + const contentFn = entries.get("content.xml"); + if (!contentFn) return null; + 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; + let tableCellBytes = 0; + const parts: string[] = []; + + 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; + 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) { + if (state) state.oversized = true; + return false; + } + parts.push(tableMd); + } + tableRows = []; + } + } 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); + } + } + } 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 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(normalized); + } + cellText = ""; + } + } else if (tagName.startsWith("text:h") || tagName.startsWith("text:p")) { + if (!isClose) { + if (!inTable) { + inPara = true; + paraText = ""; + } + } else { + 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) { + 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 += text; + } else if (inPara) { + paraText += text; + } + }, + ); + + if (!ok) return null; + const res = parts.join("\n\n").trim(); + return res || null; +} + +/** 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 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); + 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 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[] = []; + for (const idref of spineRefs) { + if (manifest.has(idref)) { + spine.push(manifest.get(idref)!); + } + } + 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 strippedHtml = stripStyleAndScriptTags(html); + + let chapterText = ""; + const ok = walkXml( + strippedHtml, + tagBudget, + (tagName, isClose) => { + 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(); + if (text) chapters.push(text); + } + + const res = chapters.join("\n\n").trim(); + 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; + 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 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); + + 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 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); + 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(); + 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; + + 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 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; + arrayBuffer?: () => Promise; + slice?: (start?: number, end?: number) => Blob; +}): Promise { + const ext = getFileExtension(file.name); + const isKnownDocument = isKnownBinaryDocumentMeta(file); + + let fallbackText: string | null = null; + if (!isKnownDocument && typeof file.text === "function") { + const text = await file.text(); + 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; + } + } + + 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); + 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 finalizeDocResult(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) { + 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 finalizeDocResult(await extractDocx(entries)); + } + if (ext === "xlsx" || entries.has("xl/workbook.xml")) { + return finalizeDocResult(await extractXlsx(entries, state)); + } + if (ext === "pptx" || entries.has("ppt/presentation.xml")) { + return finalizeDocResult(await extractPptx(entries)); + } + if (ext === "odt" || ext === "ods" || ext === "odp" || entries.has("content.xml")) { + return finalizeDocResult(await extractOdf(entries, state)); + } + if (ext === "epub" || entries.has("META-INF/container.xml")) { + return finalizeDocResult(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") { + if (buffer.byteLength > MAX_DECOMPRESSED_BYTES) { + oversizedDocumentFiles.add(file); + return null; + } + try { + return finalizeDocResult(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; + } + 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 da3641853..93d03c70f 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). */