| 1 | import assert from "node:assert/strict"; |
| 2 | import test from "node:test"; |
| 3 | import React, { act } from "react"; |
| 4 | import { createRoot } from "react-dom/client"; |
| 5 | import { JSDOM } from "jsdom"; |
| 6 | import { Composer } from "../components/Composer"; |
| 7 | import { LocaleProvider } from "../lib/i18n"; |
| 8 | import { ToastProvider } from "../lib/toast"; |
| 9 | import { flushAllSessionComposers, resumeSessionComposerEditing } from "../lib/sessionComposerPersistence"; |
| 10 | import { makeSessionUIMock } from "../lib/sessionUIMock"; |
| 11 | import { installDesktopHostStub } from "./desktopHostStub"; |
| 12 | import { createFileUploadMock, dispatchPasteFile } from "./fileUploadStub"; |
| 13 | |
| 14 | function deferred<T = void>() { |
| 15 | let resolve!: (value: T) => void; |
| 16 | const promise = new Promise<T>(done => { resolve = done; }); |
| 17 | return { promise, resolve }; |
| 18 | } |
| 19 | const tick = () => new Promise<void>(done => setImmediate(done)); |
| 20 | const textarea = () => document.querySelector<HTMLTextAreaElement>("textarea")!; |
| 21 | const sendButton = () => document.querySelector<HTMLButtonElement>(".composer__btn--send")!; |
| 22 | async function menu(index: number) { |
| 23 | await act(async () => { |
| 24 | textarea().dispatchEvent(new window.MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 20, clientY: 20 })); |
| 25 | }); |
| 26 | await act(async () => { document.querySelectorAll<HTMLButtonElement>(".context-menu__item")[index].click(); await tick(); }); |
| 27 | } |
| 28 | async function fixture(session: string, commands: Record<string, unknown> = {}, formal = true) { |
| 29 | const dom = new JSDOM("<div id='root'></div>", { url: "http://localhost/", pretendToBeVisual: true }); |
| 30 | Object.assign(globalThis, { |
| 31 | window: dom.window, document: dom.window.document, localStorage: dom.window.localStorage, |
| 32 | IS_REACT_ACT_ENVIRONMENT: true, |
| 33 | requestAnimationFrame: dom.window.requestAnimationFrame.bind(dom.window), |
| 34 | cancelAnimationFrame: dom.window.cancelAnimationFrame.bind(dom.window), |
| 35 | ResizeObserver: class { observe() {} unobserve() {} disconnect() {} }, |
| 36 | }); |
| 37 | for (const name of ["Node", "HTMLElement", "HTMLTextAreaElement", "Event", "CustomEvent", "File", "FileReader", "MutationObserver"]) { |
| 38 | Object.defineProperty(globalThis, name, { configurable: true, value: Reflect.get(dom.window, name) }); |
| 39 | } |
| 40 | Object.defineProperty(globalThis, "navigator", { configurable: true, value: dom.window.navigator }); |
| 41 | Object.defineProperty(dom.window.HTMLElement.prototype, "attachEvent", { configurable: true, value() {} }); |
| 42 | Object.defineProperty(dom.window.HTMLElement.prototype, "detachEvent", { configurable: true, value() {} }); |
| 43 | window.matchMedia = (() => ({ matches: true, addEventListener() {}, removeEventListener() {} })) as typeof window.matchMedia; |
| 44 | const backend = makeSessionUIMock(async () => {}); |
| 45 | const host = installDesktopHostStub({ |
| 46 | Commands: async () => [], Models: async () => [], ModelsForTab: async () => [], |
| 47 | ListDir: async () => [], ListDirForTab: async () => [], SearchFileRefs: async () => [], SearchFileRefsForTab: async () => [], |
| 48 | ...backend, ...commands, |
| 49 | }, { clipboardWriteResult: () => false }); |
| 50 | const ref = { hostId: "local", sessionId: session }; |
| 51 | const sent: string[] = []; |
| 52 | let props: Parameters<typeof Composer>[0] = { |
| 53 | running: false, collaborationMode: "normal", toolApprovalMode: "ask", goal: "", cwd: "/repo", |
| 54 | modelLabel: "DeepSeek-R1", tabId: session, sessionKey: session, ready: true, |
| 55 | formalSessionRef: formal ? ref : undefined, |
| 56 | onSend: async text => { sent.push(text); }, |
| 57 | onCancel: async () => ({ discardedItemIds: [] }), onCycleMode() {}, onSetMode() {}, |
| 58 | onSetCollaborationMode() {}, onSetToolApprovalMode() {}, onClearGoal() {}, onSwitchModel() {}, onSetEffort() {}, |
| 59 | }; |
| 60 | const root = createRoot(document.getElementById("root")!); |
| 61 | const paint = async (next: Partial<typeof props> = {}) => { |
| 62 | props = { ...props, ...next }; |
| 63 | await act(async () => { root.render(<LocaleProvider><ToastProvider><Composer {...props}/></ToastProvider></LocaleProvider>); await tick(); }); |
| 64 | }; |
| 65 | await paint(); |
| 66 | let insertId = 0; |
| 67 | return { ref, backend, sent, paint, |
| 68 | async insert(text: string) { await paint({ insertRequest: { id: ++insertId, text, mode: "replace" } }); }, |
| 69 | async select(from: number, to = from) { |
| 70 | await act(async () => { await new Promise<void>(done => requestAnimationFrame(() => done())); }); |
| 71 | textarea().setSelectionRange(from, to); |
| 72 | }, |
| 73 | saved: async () => JSON.parse((await backend.GetSessionComposerState(ref)).contentJson), |
| 74 | async dispose() { |
| 75 | await act(async () => { resumeSessionComposerEditing(); root.unmount(); }); |
| 76 | host.uninstall(); dom.window.close(); |
| 77 | }, |
| 78 | }; |
| 79 | } |
| 80 | |
| 81 | for (const kind of ["file", "image", "clipboard", "native"] as const) { |
| 82 | test(`accepted ${kind} input blocks sending through publication and close`, { timeout: 15000 }, async () => { |
| 83 | const entered = deferred(), release = deferred(); |
| 84 | const f = await fixture(kind, { |
| 85 | CaptureAttachmentTarget: async () => { entered.resolve(); await release.promise; return { token: "input-target", capabilities: ["attachments-v2"] }; }, |
| 86 | ReleaseAttachmentTarget: async () => {}, |
| 87 | StageImageForTarget: async () => ({ draftId: "0123456789abcdef0123456789abcdef", displayName: "accepted.png", mime: "image/png", width: 1, height: 1, bytes: 12 }), |
| 88 | SavePastedImageForComposerTarget: async () => ".reasonix/attachments/accepted.png", |
| 89 | SaveClipboardImageForTarget: async () => ".reasonix/attachments/native.png", |
| 90 | AttachmentDataURLForTarget: async () => "data:image/png;base64,aGVsbG8=", |
| 91 | ReadDraftImageForTarget: async () => "data:image/png;base64,aGVsbG8=", |
| 92 | }); |
| 93 | const restoreUpload = createFileUploadMock("input-target", { |
| 94 | ok: (value, message) => assert.ok(value, message), eq: (a, b, message) => assert.equal(a, b, message), |
| 95 | })(async () => ".reasonix/attachments/accepted.txt"); |
| 96 | Object.defineProperty(navigator, "clipboard", { configurable: true, value: { |
| 97 | read: async () => kind === "native" ? [{ types: ["image/png"] }] : [], |
| 98 | readText: async () => { entered.resolve(); await release.promise; return " ACCEPTED PASTE"; }, |
| 99 | }}); |
| 100 | try { |
| 101 | await f.insert("original message"); |
| 102 | await f.select(16); |
| 103 | if (kind === "clipboard" || kind === "native") await menu(4); |
| 104 | else await act(async () => { dispatchPasteFile(textarea(), new File(["hello"], kind === "image" ? "accepted.png" : "accepted.txt", { type: kind === "image" ? "image/png" : "text/plain" })); }); |
| 105 | await entered.promise; |
| 106 | assert.equal(sendButton().disabled, true, "send is blocked even before target capture/read completes"); |
| 107 | await act(async () => { |
| 108 | sendButton().click(); |
| 109 | textarea().dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", bubbles: true })); |
| 110 | await tick(); |
| 111 | }); |
| 112 | assert.deepEqual(f.sent, []); |
| 113 | let closed = false, closing!: Promise<void>; |
| 114 | await act(async () => { closing = flushAllSessionComposers().then(() => { closed = true; }); await tick(); }); |
| 115 | assert.equal(closed, false, "close waits for accepted input"); |
| 116 | await act(async () => { release.resolve(); await closing; }); |
| 117 | const saved = await f.saved(); |
| 118 | if (kind === "clipboard") assert.equal(saved.text, "original message ACCEPTED PASTE"); |
| 119 | else { assert.equal(saved.text, "original message"); assert.equal(saved.attachments.length, 1); } |
| 120 | await act(async () => resumeSessionComposerEditing()); |
| 121 | assert.equal(sendButton().disabled, false, "completed input releases the send guard"); |
| 122 | if (kind === "clipboard") { |
| 123 | await act(async () => { sendButton().click(); await tick(); }); |
| 124 | await act(async () => { await flushAllSessionComposers(); }); |
| 125 | assert.deepEqual(f.sent, ["original message ACCEPTED PASTE"]); |
| 126 | assert.deepEqual(await f.saved(), {}, "only the complete submitted draft is cleared"); |
| 127 | } |
| 128 | } finally { release.resolve(); restoreUpload(); await f.dispose(); } |
| 129 | }); |
| 130 | } |
| 131 | |
| 132 | for (const kind of ["changed", "unchanged", "background", "local-changed", "clipboard-failed"] as const) { |
| 133 | test(`cut preserves ${kind} content and participates in close draining`, { timeout: 15000 }, async () => { |
| 134 | const entered = deferred(), release = deferred(); |
| 135 | const f = await fixture("cut-" + kind, {}, kind !== "local-changed"); |
| 136 | let copied = ""; |
| 137 | Object.defineProperty(navigator, "clipboard", { configurable: true, value: { |
| 138 | writeText: async (text: string) => { |
| 139 | entered.resolve(); await release.promise; |
| 140 | if (kind === "clipboard-failed") throw Error("clipboard unavailable"); |
| 141 | copied = text; |
| 142 | }, |
| 143 | }}); |
| 144 | try { |
| 145 | await f.insert("abcdef"); |
| 146 | await f.select(1, 4); |
| 147 | await menu(2); |
| 148 | await entered.promise; |
| 149 | if (kind === "changed" || kind === "local-changed") await f.insert("NEW CONTENT"); |
| 150 | if (kind === "background") await f.paint({ |
| 151 | tabId: "other", sessionKey: "other", formalSessionRef: { hostId: "local", sessionId: "other" }, insertRequest: null, |
| 152 | }); |
| 153 | let closed = false, closing!: Promise<void>; |
| 154 | if (kind !== "local-changed") { |
| 155 | await act(async () => { closing = flushAllSessionComposers().then(() => { closed = true; }); await tick(); }); |
| 156 | assert.equal(closed, false, "close waits for an admitted cut"); |
| 157 | } |
| 158 | await act(async () => { release.resolve(); if (closing) await closing; else await tick(); }); |
| 159 | assert.equal(copied, kind === "clipboard-failed" ? "" : "bcd"); |
| 160 | if (kind === "local-changed") assert.equal(textarea().value, "NEW CONTENT"); |
| 161 | else { |
| 162 | const expected = kind === "changed" ? "NEW CONTENT" : kind === "clipboard-failed" ? "abcdef" : "aef"; |
| 163 | assert.equal((await f.saved()).text, expected); |
| 164 | await act(async () => resumeSessionComposerEditing()); |
| 165 | if (kind === "background") { |
| 166 | assert.equal(textarea().value, "", "background cut never mutates the current composer"); |
| 167 | await f.paint({ tabId: f.ref.sessionId, sessionKey: f.ref.sessionId, formalSessionRef: f.ref }); |
| 168 | } |
| 169 | assert.equal(textarea().value, expected); |
| 170 | } |
| 171 | } finally { release.resolve(); await f.dispose(); } |
| 172 | }); |
| 173 | } |
| 174 | |
| 175 | test("native paste fallback owns input before its timer fires", { timeout: 15000 }, async () => { |
| 176 | const entered = deferred(), release = deferred(); |
| 177 | const f = await fixture("native-timer", { |
| 178 | CaptureAttachmentTarget: async () => { entered.resolve(); await release.promise; return { token: "timer-target", capabilities: ["attachments-v2"] }; }, |
| 179 | ReleaseAttachmentTarget: async () => {}, |
| 180 | SaveClipboardImageForTarget: async () => ".reasonix/attachments/native.png", |
| 181 | AttachmentDataURLForTarget: async () => "data:image/png;base64,aGVsbG8=", |
| 182 | }); |
| 183 | const originalTimer = window.setTimeout; |
| 184 | let fire!: () => void; |
| 185 | try { |
| 186 | await f.insert("with native image"); |
| 187 | window.setTimeout = ((handler: TimerHandler, delay?: number, ...args: unknown[]) => { |
| 188 | if (delay === 160) { fire = handler as () => void; return -1; } |
| 189 | return originalTimer(handler, delay, ...args); |
| 190 | }) as typeof window.setTimeout; |
| 191 | await act(async () => { textarea().dispatchEvent(new window.KeyboardEvent("keydown", { key: "v", ctrlKey: true, bubbles: true })); }); |
| 192 | assert.equal(typeof fire, "function"); |
| 193 | assert.equal(sendButton().disabled, true); |
| 194 | let closed = false, closing!: Promise<void>; |
| 195 | await act(async () => { closing = flushAllSessionComposers().then(() => { closed = true; }); await tick(); }); |
| 196 | assert.equal(closed, false); |
| 197 | await act(async () => { fire(); await entered.promise; }); |
| 198 | assert.equal(closed, false); |
| 199 | await act(async () => { release.resolve(); await closing; }); |
| 200 | const saved = await f.saved(); |
| 201 | assert.equal(saved.text, "with native image"); |
| 202 | assert.equal(saved.attachments[0].path, ".reasonix/attachments/native.png"); |
| 203 | } finally { window.setTimeout = originalTimer; release.resolve(); await f.dispose(); } |
| 204 | }); |
| 205 |