| 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 { useSessionComposerLifecycle } from "../app-runtime/useSessionComposerLifecycle"; |
| 7 | import { emptySessionInput, resumeSessionComposerEditing, useSessionComposerPersistence } from "../lib/sessionComposerPersistence"; |
| 8 | import { makeSessionUIMock } from "../lib/sessionUIMock"; |
| 9 | import { installDesktopHostStub } from "./desktopHostStub"; |
| 10 | import { SessionInputRecovery } from "../components/SessionInputRecovery"; |
| 11 | import { LocaleProvider } from "../lib/i18n"; |
| 12 | import type { SessionRef } from "../lib/sessionRef"; |
| 13 | |
| 14 | function deferred() { |
| 15 | let resolve!: () => void; |
| 16 | const promise = new Promise<void>(done => { resolve = done; }); |
| 17 | return { promise, resolve }; |
| 18 | } |
| 19 | const tick = () => new Promise<void>(done => setImmediate(done)); |
| 20 | |
| 21 | test("closing formal session input preserves drafts without depending on attachment capabilities", async t => { |
| 22 | const dom = new JSDOM("<div id='root'></div>", { url: "http://localhost" }); |
| 23 | Object.assign(globalThis, { window: dom.window, document: dom.window.document, IS_REACT_ACT_ENVIRONMENT: true }); |
| 24 | const root = createRoot(document.getElementById("root")!); |
| 25 | const backend = makeSessionUIMock(async () => {}); |
| 26 | let captures = 0, writes = 0, failSave = false; |
| 27 | const save: typeof backend.SaveSessionComposerState = async request => { |
| 28 | writes++; |
| 29 | if (failSave) throw Error("disk full"); |
| 30 | return backend.SaveSessionComposerState(request); |
| 31 | }; |
| 32 | const host = installDesktopHostStub({ ...backend, SaveSessionComposerState: save, |
| 33 | CaptureAttachmentTarget: async () => { captures++; throw Error("unsupported: attachments-v2"); }, |
| 34 | AttachDroppedForTarget: async () => { throw Error("must not activate attachments while loading input"); }, |
| 35 | }); |
| 36 | const ref = (sessionId: string) => ({ hostId: "local", sessionId }); |
| 37 | let editor!: ReturnType<typeof useSessionComposerPersistence>; |
| 38 | function Probe({ session }: { session: string }) { |
| 39 | useSessionComposerLifecycle(); |
| 40 | editor = useSessionComposerPersistence(ref(session), `tab-${session}`); |
| 41 | return <LocaleProvider><SessionInputRecovery input={editor} /></LocaleProvider>; |
| 42 | } |
| 43 | const paint = (session: string) => act(async () => { root.render(React.createElement(Probe, { session })); }); |
| 44 | const patch = (text: string) => { |
| 45 | const target = editor.target!; |
| 46 | target.onPatch!(target.draftId, target.generation, { text }); |
| 47 | }; |
| 48 | const attachmentError = (message = "unsupported: attachments-v2") => { |
| 49 | const target = editor.target!; |
| 50 | target.onTaskError!(target.draftId, target.generation, message); |
| 51 | }; |
| 52 | const close = () => window.__reasonixFlushSessionDraft!(); |
| 53 | const saved = async (session: string) => JSON.parse((await backend.GetSessionComposerState(ref(session))).contentJson); |
| 54 | async function resume() { await act(async () => resumeSessionComposerEditing()); } |
| 55 | |
| 56 | try { |
| 57 | await t.test("a blank window closes without saving or capturing attachments", async () => { |
| 58 | await paint("blank"); |
| 59 | const before = writes; |
| 60 | await act(async () => close()); |
| 61 | assert.equal(writes, before); |
| 62 | assert.equal(captures, 0); |
| 63 | await resume(); |
| 64 | }); |
| 65 | |
| 66 | await t.test("a failed attachment on blank input stays visible but does not veto close", async () => { |
| 67 | await paint("blank-warning"); |
| 68 | await act(async () => attachmentError("unsupported: attachments-v2\nTrace: attachment-target")); |
| 69 | assert.equal(editor.error, undefined); |
| 70 | assert.equal(document.querySelector('.user-error__summary')!.textContent, "unsupported: attachments-v2"); |
| 71 | assert.equal(document.querySelector('.user-error__detail'), null, "raw diagnostics start collapsed"); |
| 72 | await act(async () => document.querySelector<HTMLButtonElement>('.user-error__toggle')!.click()); |
| 73 | assert.match(document.querySelector('.user-error__detail')!.textContent!, /Trace: attachment-target/); |
| 74 | assert.doesNotMatch(document.body.textContent!, /Retry to recover saving/); |
| 75 | assert.equal(editor.target!.initial.text, ""); |
| 76 | try { |
| 77 | await act(async () => close()); |
| 78 | await act(async () => document.querySelector<HTMLButtonElement>('[role="alert"] > button')!.click()); |
| 79 | assert.equal(document.querySelector('[role="alert"]'), null); |
| 80 | } |
| 81 | finally { await act(async () => editor.retry()); await resume(); } |
| 82 | }); |
| 83 | |
| 84 | await t.test("reopening stored external references never requires a live attachment controller", async () => { |
| 85 | const content = { ...emptySessionInput(), workspaceRefs: [ |
| 86 | { path: "__reasonix_external_folder/hash/folder", displayPath: "/external/folder", isDir: true }, |
| 87 | ] }; |
| 88 | await backend.SaveSessionComposerState({ ref: ref("external"), expectedRevision: "0", contentVersion: 1, contentJson: JSON.stringify(content) }); |
| 89 | await paint("external"); |
| 90 | // Drain the old eager dynamic import too, so the regression observes its failure. |
| 91 | await act(async () => { await import("../lib/attachmentSubmit"); await tick(); }); |
| 92 | const external = editor; |
| 93 | try { |
| 94 | assert.equal(external.error, undefined); |
| 95 | assert.equal(external.blocked, false); |
| 96 | assert.deepEqual(external.target!.initial.workspaceRefs, content.workspaceRefs); |
| 97 | await paint("blank-after-external"); |
| 98 | await act(async () => close()); |
| 99 | assert.deepEqual(await saved("external"), content); |
| 100 | assert.equal(captures, 0); |
| 101 | } finally { await act(async () => external.retry()); await resume(); } |
| 102 | }); |
| 103 | |
| 104 | await t.test("an attachment warning cannot prevent real input from being saved", async () => { |
| 105 | await paint("text-warning"); |
| 106 | await act(async () => { patch("keep this unsent text"); attachmentError(); }); |
| 107 | try { |
| 108 | await act(async () => close()); |
| 109 | assert.equal((await saved("text-warning")).text, "keep this unsent text"); |
| 110 | } finally { await act(async () => editor.retry()); await resume(); } |
| 111 | }); |
| 112 | |
| 113 | await t.test("a true save failure blocks close even when the visible page is blank", async () => { |
| 114 | await paint("hidden-unsaved"); |
| 115 | const hidden = editor; |
| 116 | failSave = true; |
| 117 | await act(async () => { patch("never lose this draft"); attachmentError(); }); |
| 118 | await paint("blank-with-hidden-draft"); |
| 119 | try { |
| 120 | await act(async () => { await assert.rejects(close(), /disk full/); }); |
| 121 | assert.equal(editor.target!.initial.text, ""); |
| 122 | assert.equal(editor.blocked, false, "failed close resumes the visible editor"); |
| 123 | await paint("hidden-unsaved"); |
| 124 | assert.equal(editor.target!.initial.text, "never lose this draft"); |
| 125 | assert.match(document.body.textContent!, /Retry to recover saving/, "save failure takes priority over attachment feedback"); |
| 126 | assert.notEqual((await saved("hidden-unsaved")).text, "never lose this draft"); |
| 127 | } finally { failSave = false; await act(async () => hidden.retry()); } |
| 128 | await paint("blank-with-hidden-draft"); |
| 129 | await act(async () => close()); |
| 130 | assert.equal((await saved("hidden-unsaved")).text, "never lose this draft"); |
| 131 | await resume(); |
| 132 | }); |
| 133 | |
| 134 | await t.test("close waits for attachment completion and saves the resulting image-only draft", async () => { |
| 135 | await paint("pending-attachment"); |
| 136 | const release = deferred(), target = editor.target!; |
| 137 | const attachments = [{ path: "draft:temporary", recoveryPath: ".reasonix/attachments/image.png", draftId: "temporary" }]; |
| 138 | target.trackTask!(target.draftId, target.generation, release.promise.then(() => { |
| 139 | target.onPatch!(target.draftId, target.generation, { attachments }); |
| 140 | })); |
| 141 | let finished = false; |
| 142 | let closing!: Promise<void>; |
| 143 | await act(async () => { closing = close().then(() => { finished = true; }); await tick(); }); |
| 144 | assert.equal(finished, false); |
| 145 | await act(async () => { release.resolve(); await closing; }); |
| 146 | assert.deepEqual((await saved("pending-attachment")).attachments, [{ path: attachments[0].recoveryPath, recoveryPath: attachments[0].recoveryPath }]); |
| 147 | await resume(); |
| 148 | }); |
| 149 | |
| 150 | await t.test("close cannot skip a pending load that fails to read persisted input", async () => { |
| 151 | const entered = deferred(), release = deferred(); |
| 152 | host.commands.GetSessionComposerState = async () => { entered.resolve(); await release.promise; throw Error("input read failed"); }; |
| 153 | await paint("pending-read"); |
| 154 | await entered.promise; |
| 155 | let finished = false; |
| 156 | let closing!: Promise<unknown>; |
| 157 | await act(async () => { closing = close().then(() => { finished = true; }, error => error); await tick(); }); |
| 158 | try { |
| 159 | assert.equal(finished, false, "must await the initial input read before allowing close"); |
| 160 | await act(async () => { release.resolve(); }); |
| 161 | assert.match(String(await closing), /input read failed/); |
| 162 | } finally { |
| 163 | await act(async () => { release.resolve(); await closing; }); |
| 164 | host.commands.GetSessionComposerState = backend.GetSessionComposerState; |
| 165 | await act(async () => editor.retry()); await resume(); |
| 166 | } |
| 167 | }); |
| 168 | |
| 169 | await t.test("close waits for recovery to discover input that still needs saving", async () => { |
| 170 | await paint("pending-recovery"); |
| 171 | await act(async () => patch("this window input")); |
| 172 | await act(async () => close()); |
| 173 | await resume(); |
| 174 | const current = await backend.GetSessionComposerState(ref("pending-recovery")); |
| 175 | await backend.SaveSessionComposerState({ ref: current.ref, expectedRevision: current.revision, contentVersion: 1, contentJson: '{"text":"other window input"}' }); |
| 176 | const entered = deferred(), release = deferred(); |
| 177 | host.commands.GetSessionComposerState = async (value: SessionRef) => { entered.resolve(); await release.promise; return backend.GetSessionComposerState(value); }; |
| 178 | let recovery!: Promise<void>, closing!: Promise<void>, finished = false; |
| 179 | await act(async () => { recovery = editor.retry(); await entered.promise; }); |
| 180 | await act(async () => { closing = close().then(() => { finished = true; }); await tick(); }); |
| 181 | try { assert.equal(finished, false, "a clean version can become dirty during recovery"); } |
| 182 | finally { |
| 183 | await act(async () => { release.resolve(); await recovery; await closing; }); |
| 184 | host.commands.GetSessionComposerState = backend.GetSessionComposerState; |
| 185 | await resume(); |
| 186 | } |
| 187 | assert.equal((await saved("pending-recovery")).text, "this window input"); |
| 188 | }); |
| 189 | } finally { |
| 190 | await act(async () => root.unmount()); |
| 191 | host.uninstall(); dom.window.close(); |
| 192 | } |
| 193 | }); |
| 194 |