| 1 | // Run: tsx src/__tests__/composer-oversize-attachment.test.tsx |
| 2 | |
| 3 | import { JSDOM } from "jsdom"; |
| 4 | import React from "react"; |
| 5 | import { act } from "react"; |
| 6 | import { createRoot } from "react-dom/client"; |
| 7 | import { Composer } from "../components/Composer"; |
| 8 | import { LocaleProvider } from "../lib/i18n"; |
| 9 | import { ToastProvider } from "../lib/toast"; |
| 10 | import type { CollaborationMode, ToolApprovalMode } from "../lib/types"; |
| 11 | import { installDesktopHostStub, type DesktopHostStubOptions } from "./desktopHostStub"; |
| 12 | |
| 13 | let passed = 0; |
| 14 | let failed = 0; |
| 15 | |
| 16 | function ok(value: boolean, label: string) { |
| 17 | if (value) { |
| 18 | process.stdout.write(` PASS ${label}\n`); |
| 19 | passed += 1; |
| 20 | } else { |
| 21 | process.stdout.write(` FAIL ${label}\n`); |
| 22 | failed += 1; |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | function eq(actual: unknown, expected: unknown, label: string) { |
| 27 | if (actual === expected) ok(true, label); |
| 28 | else ok(false, `${label}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`); |
| 29 | } |
| 30 | |
| 31 | function flushTimers(): Promise<void> { |
| 32 | return new Promise((resolve) => setTimeout(resolve, 0)); |
| 33 | } |
| 34 | |
| 35 | async function waitFor(check: () => boolean, attempts = 10): Promise<void> { |
| 36 | for (let i = 0; i < attempts; i++) { |
| 37 | if (check()) return; |
| 38 | await act(async () => { |
| 39 | await flushTimers(); |
| 40 | }); |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | class TestResizeObserver { |
| 45 | observe() {} |
| 46 | unobserve() {} |
| 47 | disconnect() {} |
| 48 | } |
| 49 | |
| 50 | function installDom() { |
| 51 | const dom = new JSDOM("<!doctype html><html><body><div id=\"root\"></div></body></html>", { |
| 52 | pretendToBeVisual: true, |
| 53 | url: "http://localhost/", |
| 54 | }); |
| 55 | (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; |
| 56 | globalThis.window = dom.window as unknown as Window & typeof globalThis; |
| 57 | globalThis.document = dom.window.document; |
| 58 | Object.defineProperty(globalThis, "navigator", { configurable: true, value: dom.window.navigator }); |
| 59 | globalThis.Node = dom.window.Node; |
| 60 | globalThis.HTMLElement = dom.window.HTMLElement; |
| 61 | globalThis.HTMLTextAreaElement = dom.window.HTMLTextAreaElement; |
| 62 | globalThis.Event = dom.window.Event; |
| 63 | globalThis.CustomEvent = dom.window.CustomEvent; |
| 64 | globalThis.KeyboardEvent = dom.window.KeyboardEvent; |
| 65 | globalThis.InputEvent = dom.window.InputEvent; |
| 66 | globalThis.MouseEvent = dom.window.MouseEvent; |
| 67 | globalThis.File = dom.window.File; |
| 68 | globalThis.FileReader = dom.window.FileReader; |
| 69 | globalThis.PointerEvent = dom.window.MouseEvent as unknown as typeof PointerEvent; |
| 70 | globalThis.MutationObserver = dom.window.MutationObserver; |
| 71 | globalThis.localStorage = dom.window.localStorage; |
| 72 | globalThis.requestAnimationFrame = dom.window.requestAnimationFrame.bind(dom.window); |
| 73 | globalThis.cancelAnimationFrame = dom.window.cancelAnimationFrame.bind(dom.window); |
| 74 | globalThis.ResizeObserver = TestResizeObserver; |
| 75 | Object.defineProperty(dom.window.HTMLElement.prototype, "attachEvent", { configurable: true, value: () => {} }); |
| 76 | Object.defineProperty(dom.window.HTMLElement.prototype, "detachEvent", { configurable: true, value: () => {} }); |
| 77 | Object.defineProperty(window, "matchMedia", { |
| 78 | configurable: true, |
| 79 | value: () => ({ |
| 80 | matches: true, |
| 81 | media: "(prefers-reduced-motion: reduce)", |
| 82 | onchange: null, |
| 83 | addEventListener() {}, |
| 84 | removeEventListener() {}, |
| 85 | addListener() {}, |
| 86 | removeListener() {}, |
| 87 | dispatchEvent: () => false, |
| 88 | }), |
| 89 | }); |
| 90 | return dom; |
| 91 | } |
| 92 | |
| 93 | function installBridgeApp(methods: Record<string, unknown>, options?: DesktopHostStubOptions) { |
| 94 | const legacySave = methods.SavePastedImageForTarget as ((token: string, dataURL: string) => Promise<string>) | undefined; |
| 95 | const legacyPreview = methods.AttachmentDataURLForTarget as ((token: string, path: string) => Promise<string>) | undefined; |
| 96 | const unscopedPreview = methods.AttachmentDataURL as ((path: string) => Promise<string>) | undefined; |
| 97 | return installDesktopHostStub({ |
| 98 | Commands: async () => [], |
| 99 | Models: async () => [], |
| 100 | ModelsForTab: async () => [], |
| 101 | CaptureAttachmentTarget: async () => ({ token: "test-attachment-target", capabilities: ["attachments-v2"] }), |
| 102 | ReleaseAttachmentTarget: async () => {}, |
| 103 | StageImageForTarget: async (token: string, _operationID: string, displayName: string, mime: string, dataURL: string) => ({ |
| 104 | draftId: "", |
| 105 | path: legacySave ? await legacySave(token, dataURL) : ".reasonix/attachments/mock.png", |
| 106 | displayName, |
| 107 | mime, |
| 108 | width: 1, |
| 109 | height: 1, |
| 110 | bytes: dataURL.length, |
| 111 | }), |
| 112 | ReadDraftImageForTarget: async () => "data:image/png;base64,iVBORw0KGgo=", |
| 113 | AttachmentDataURLForTarget: legacyPreview ?? (async () => "data:image/png;base64,iVBORw0KGgo="), |
| 114 | AttachmentDataURLForTab: async (_tabID: string, path: string) => unscopedPreview ? unscopedPreview(path) : "data:image/png;base64,iVBORw0KGgo=", |
| 115 | ...methods, |
| 116 | }, options); |
| 117 | } |
| 118 | |
| 119 | async function renderComposer(props: Partial<Parameters<typeof Composer>[0]> = {}) { |
| 120 | const rootEl = document.getElementById("root"); |
| 121 | if (!rootEl) throw new Error("missing root"); |
| 122 | const root = createRoot(rootEl); |
| 123 | let currentProps: Parameters<typeof Composer>[0] = { |
| 124 | running: false, |
| 125 | collaborationMode: "normal", |
| 126 | toolApprovalMode: "ask" as ToolApprovalMode, |
| 127 | |
| 128 | goal: "", |
| 129 | cwd: "/repo", |
| 130 | modelLabel: "DeepSeek-R1", |
| 131 | imageInputEnabled: true, |
| 132 | tabId: "single-surface-tab", |
| 133 | sessionKey: "session:project:/repo:topic-a:session-a", |
| 134 | onSend: () => {}, |
| 135 | onCancel: async () => ({ discardedItemIds: [] }), |
| 136 | onCycleMode: () => {}, |
| 137 | onSetMode: () => {}, |
| 138 | onSetCollaborationMode: (_mode: CollaborationMode) => {}, |
| 139 | onSetToolApprovalMode: () => {}, |
| 140 | onClearGoal: () => {}, |
| 141 | onSwitchModel: () => {}, |
| 142 | onSetEffort: () => {}, |
| 143 | |
| 144 | ready: true, |
| 145 | ...props, |
| 146 | }; |
| 147 | const paint = async (nextProps: Partial<Parameters<typeof Composer>[0]> = {}) => { |
| 148 | currentProps = { ...currentProps, ...nextProps }; |
| 149 | await act(async () => { |
| 150 | root.render( |
| 151 | <LocaleProvider> |
| 152 | <ToastProvider> |
| 153 | <div className="chat-pane"> |
| 154 | <Composer {...currentProps} /> |
| 155 | </div> |
| 156 | </ToastProvider> |
| 157 | </LocaleProvider>, |
| 158 | ); |
| 159 | await flushTimers(); |
| 160 | }); |
| 161 | }; |
| 162 | await paint(); |
| 163 | return { root, rerender: paint }; |
| 164 | } |
| 165 | |
| 166 | function textarea(): HTMLTextAreaElement { |
| 167 | const node = document.querySelector("textarea") as HTMLTextAreaElement | null; |
| 168 | if (!node) throw new Error("composer textarea did not render"); |
| 169 | return node; |
| 170 | } |
| 171 | |
| 172 | function sendButton(): HTMLButtonElement { |
| 173 | const node = document.querySelector(".composer__btn--send") as HTMLButtonElement | null; |
| 174 | if (!node) throw new Error("send button did not render"); |
| 175 | return node; |
| 176 | } |
| 177 | |
| 178 | function contextItemCount(): number { |
| 179 | return document.querySelectorAll(".composer-context__item").length; |
| 180 | } |
| 181 | |
| 182 | function toastText(): string { |
| 183 | const items = Array.from(document.querySelectorAll(".toast__text")); |
| 184 | return (items.at(-1)?.textContent ?? "").trim(); |
| 185 | } |
| 186 | |
| 187 | function imagePasteEvent(file: File): Event { |
| 188 | const event = new Event("paste", { bubbles: true, cancelable: true }); |
| 189 | Object.defineProperty(event, "clipboardData", { |
| 190 | configurable: true, |
| 191 | value: { |
| 192 | files: [file], |
| 193 | items: [], |
| 194 | types: [file.type], |
| 195 | getData: () => "", |
| 196 | }, |
| 197 | }); |
| 198 | return event; |
| 199 | } |
| 200 | |
| 201 | |
| 202 | |
| 203 | function pasteEvent(file: File): Event { |
| 204 | const event = new Event("paste", { bubbles: true, cancelable: true }); |
| 205 | Object.defineProperty(event, "clipboardData", { |
| 206 | configurable: true, |
| 207 | value: { files: [file], items: [], types: [file.type], getData: () => "" }, |
| 208 | }); |
| 209 | return event; |
| 210 | } |
| 211 | |
| 212 | function oversized(name: string, type: string, bytes: number): File { |
| 213 | const file = new File(["x"], name, { type, lastModified: 1 }); |
| 214 | Object.defineProperty(file, "size", { configurable: true, value: bytes }); |
| 215 | return file; |
| 216 | } |
| 217 | |
| 218 | console.log("\ncomposer oversize attachment"); |
| 219 | |
| 220 | for (const [name, type, bytes] of [ |
| 221 | ["huge.png", "image/png", 64 * 1024 * 1024 + 1], |
| 222 | ] as const) { |
| 223 | const dom = installDom(); |
| 224 | let reads = 0; |
| 225 | let digests = 0; |
| 226 | let saves = 0; |
| 227 | const origRead = dom.window.FileReader.prototype.readAsDataURL; |
| 228 | dom.window.FileReader.prototype.readAsDataURL = function (this: FileReader, blob: Blob) { |
| 229 | reads += 1; |
| 230 | return origRead.call(this, blob); |
| 231 | }; |
| 232 | Object.defineProperty(globalThis, "crypto", { |
| 233 | configurable: true, |
| 234 | value: { randomUUID: () => "id", subtle: { digest: async () => { digests += 1; return new ArrayBuffer(32); } } }, |
| 235 | }); |
| 236 | installBridgeApp({ |
| 237 | SavePastedFileForTarget: async () => { saves += 1; return ".reasonix/attachments/x.bin"; }, |
| 238 | StageImageForTarget: async () => { saves += 1; throw new Error("must not stage"); }, |
| 239 | }); |
| 240 | const { root } = await renderComposer({ imageInputEnabled: true }); |
| 241 | const file = oversized(name, type, bytes); |
| 242 | const blobRead = file.arrayBuffer; |
| 243 | let buffered = 0; |
| 244 | file.arrayBuffer = () => { buffered += 1; return blobRead.call(file); }; |
| 245 | |
| 246 | await act(async () => { |
| 247 | textarea().dispatchEvent(pasteEvent(file)); |
| 248 | await flushTimers(); |
| 249 | await flushTimers(); |
| 250 | }); |
| 251 | await waitFor(() => toastText() !== ""); |
| 252 | eq(reads, 0, `${name}: FileReader never started`); |
| 253 | eq(buffered, 0, `${name}: file bytes never buffered for hashing`); |
| 254 | eq(digests, 0, `${name}: no digest computed`); |
| 255 | eq(saves, 0, `${name}: nothing sent to the kernel`); |
| 256 | eq(contextItemCount(), 0, `${name}: no attachment added`); |
| 257 | ok(/too large/i.test(toastText()), `${name}: toast says the file is too large (got "${toastText()}")`); |
| 258 | await act(async () => root.unmount()); |
| 259 | dom.window.close(); |
| 260 | } |
| 261 | |
| 262 | for (const entry of ["pick", "paste"] as const) { |
| 263 | for (const nativePath of ["", "/repo/releases/large app.apk"]) { |
| 264 | for (const [name, type, bytes] of [ |
| 265 | ["large app.apk", "application/vnd.android.package-archive", 900 * 1024 * 1024], |
| 266 | ["pack.zip", "application/zip", 25 * 1024 * 1024 + 1], |
| 267 | ["small.zip", "application/zip", 2], |
| 268 | ] as const) { |
| 269 | const dom = installDom(); |
| 270 | const label = `${entry} ${nativePath ? "native" : "pathless"} ${name}`; |
| 271 | let reads = 0; |
| 272 | let digests = 0; |
| 273 | let buffered = 0; |
| 274 | let legacySaves = 0; |
| 275 | const nativeCalls: Array<{ token: string; path: string }> = []; |
| 276 | const uploads: Array<{ input: string; init: RequestInit }> = []; |
| 277 | const originalFetch = globalThis.fetch; |
| 278 | globalThis.fetch = async (input, init = {}) => { |
| 279 | uploads.push({ input: String(input), init }); |
| 280 | return new Response(JSON.stringify({ path: ".reasonix/attachments/uploaded.apk" }), { |
| 281 | status: 201, headers: { "content-type": "application/json" }, |
| 282 | }); |
| 283 | }; |
| 284 | const originalReader = dom.window.FileReader.prototype.readAsDataURL; |
| 285 | dom.window.FileReader.prototype.readAsDataURL = function (this: FileReader, blob: Blob) { |
| 286 | reads++; |
| 287 | return originalReader.call(this, blob); |
| 288 | }; |
| 289 | Object.defineProperty(globalThis, "crypto", { |
| 290 | configurable: true, |
| 291 | value: { randomUUID: () => "id", subtle: { digest: async () => { digests++; return new ArrayBuffer(32); } } }, |
| 292 | }); |
| 293 | installBridgeApp({ |
| 294 | SavePastedFileForTarget: async () => { legacySaves++; return ".reasonix/attachments/legacy.bin"; }, |
| 295 | AttachDroppedForTarget: async (token: string, path: string) => { |
| 296 | nativeCalls.push({ token, path }); |
| 297 | return { kind: "workspace", path: "releases/large app.apk", isDir: false }; |
| 298 | }, |
| 299 | }, { getPathForFile: () => nativePath }); |
| 300 | const { root } = await renderComposer({ imageInputEnabled: true }); |
| 301 | const file = oversized(name, type, bytes); |
| 302 | file.arrayBuffer = async () => { buffered++; return new ArrayBuffer(1); }; |
| 303 | await act(async () => { |
| 304 | if (entry === "paste") textarea().dispatchEvent(pasteEvent(file)); |
| 305 | else { |
| 306 | const input = document.querySelector<HTMLInputElement>("input[type=file]"); |
| 307 | if (!input) throw new Error("file picker did not render"); |
| 308 | Object.defineProperty(input, "files", { configurable: true, value: [file] }); |
| 309 | input.dispatchEvent(new Event("change", { bubbles: true })); |
| 310 | } |
| 311 | await flushTimers(); |
| 312 | await flushTimers(); |
| 313 | }); |
| 314 | await waitFor(() => contextItemCount() > 0); |
| 315 | eq(contextItemCount(), 1, `${label}: appears in chat context`); |
| 316 | eq(toastText(), "", `${label}: no size or upload error`); |
| 317 | eq(reads, 0, `${label}: FileReader never starts`); |
| 318 | eq(buffered, 0, `${label}: file bytes never buffered`); |
| 319 | eq(digests, 0, `${label}: no full-file digest`); |
| 320 | eq(legacySaves, 0, `${label}: no Base64 RPC`); |
| 321 | eq(nativeCalls.length, nativePath ? 1 : 0, `${label}: native reference used when available`); |
| 322 | eq(uploads.length, nativePath ? 0 : 1, `${label}: HTTP upload only for a pathless file`); |
| 323 | if (nativeCalls[0]) { |
| 324 | eq(nativeCalls[0].token, "test-attachment-target", `${label}: native reference bound to source target`); |
| 325 | eq(nativeCalls[0].path, nativePath, `${label}: original native path preserved`); |
| 326 | ok(document.body.textContent?.includes("large app.apk") === true, `${label}: workspace reference is visible`); |
| 327 | } |
| 328 | if (uploads[0]) { |
| 329 | const uploaded = uploads[0]; |
| 330 | const url = new URL(uploaded.input, "http://localhost/"); |
| 331 | eq(url.pathname, "/__reasonix_attachment_upload", `${label}: raw upload endpoint`); |
| 332 | eq(url.searchParams.get("target"), "test-attachment-target", `${label}: target token preserved`); |
| 333 | eq(url.searchParams.get("name"), name, `${label}: filename preserved`); |
| 334 | eq(uploaded.init.method, "POST", `${label}: POST upload`); |
| 335 | eq(uploaded.init.body, file, `${label}: original File is the request body`); |
| 336 | eq(new Headers(uploaded.init.headers).get("content-type"), "application/octet-stream", `${label}: raw binary content type`); |
| 337 | } |
| 338 | await act(async () => root.unmount()); |
| 339 | dom.window.close(); |
| 340 | globalThis.fetch = originalFetch; |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | console.log(`\n${passed} passed, ${failed} failed, ${passed + failed} total`); |
| 346 | if (failed > 0) process.exit(1); |
| 347 |