| 1 | // Native window close + the real renderer and Go store, using disposable data. |
| 2 | // Build frontend, service and shell first; no provider or clipboard is used. |
| 3 | import assert from "node:assert/strict"; |
| 4 | import { mkdtempSync, writeFileSync } from "node:fs"; |
| 5 | import { tmpdir } from "node:os"; |
| 6 | import { resolve, join } from "node:path"; |
| 7 | import { fileURLToPath } from "node:url"; |
| 8 | import { setTimeout as delay } from "node:timers/promises"; |
| 9 | import { _electron } from "playwright"; |
| 10 | |
| 11 | const root = resolve(fileURLToPath(new URL("..", import.meta.url))); |
| 12 | const home = mkdtempSync(join(tmpdir(), "reasonix-composer-close-")); |
| 13 | writeFileSync(join(home, "config.toml"), ""); |
| 14 | const report = { home, platform: process.platform, checks: [] }; |
| 15 | const check = name => { report.checks.push(name); console.log(`PASS ${name}`); }; |
| 16 | const rpc = (page, name, ...args) => page.evaluate(({ name, args }) => window.reasonixDesktop.invoke(name, args), { name, args }); |
| 17 | const inputSelector = "textarea.composer__input:not([aria-hidden=true])"; |
| 18 | let shell; |
| 19 | let shellStderr = ""; |
| 20 | function terminateFixture() { |
| 21 | // Playwright launches a dedicated process group on POSIX. Include its |
| 22 | // helpers so an orphaned network service cannot retain the CDP connection. |
| 23 | try { |
| 24 | if (process.platform === "win32") shell.process().kill("SIGKILL"); |
| 25 | else process.kill(-shell.process().pid, "SIGKILL"); |
| 26 | } catch (error) { if (error.code !== "ESRCH") throw error; } |
| 27 | } |
| 28 | async function launch() { |
| 29 | shell = await _electron.launch({ args: [root, `--user-data-dir=${join(home, "electron")}`], env: { |
| 30 | ...process.env, REASONIX_HOME: home, REASONIX_STATE_HOME: home, REASONIX_CACHE_HOME: join(home, "cache"), |
| 31 | REASONIX_DEV: "1", REASONIX_DESKTOP_SERVICE: resolve(root, "../build/bin/reasonix-desktop-service" + (process.platform === "win32" ? ".exe" : "")), |
| 32 | }, timeout: 60000 }); |
| 33 | shellStderr = ""; |
| 34 | shell.process().stderr.on("data", chunk => { shellStderr += chunk; }); |
| 35 | const page = await shell.firstWindow(); |
| 36 | page.setDefaultTimeout(30000); |
| 37 | await page.waitForURL("reasonix://app/index.html", { timeout: 60000 }); |
| 38 | await page.waitForFunction(() => Boolean(window.__reasonixFlushSessionDraft) && !document.querySelector(".boot-shell")); |
| 39 | await page.addLocatorHandler(page.locator(".management-screen__back:visible"), button => button.click()); |
| 40 | await page.locator(".sidebar__quick-action:visible").first().click({ trial: true }); |
| 41 | return page; |
| 42 | } |
| 43 | async function closeWindow() { |
| 44 | const page = await shell.firstWindow(); |
| 45 | const mainWindow = await shell.browserWindow(page); |
| 46 | const closed = page.waitForEvent("close", { timeout: 30000 }); |
| 47 | // BrowserWindow.close dispatches the same native close event as the titlebar. |
| 48 | await mainWindow.evaluate(win => win.close()); |
| 49 | await closed; |
| 50 | // Native shutdown must destroy the window first. Only then detach |
| 51 | // Playwright's Node inspector, which otherwise keeps Electron alive at exit. |
| 52 | const closing = shell.close(); |
| 53 | const detached = await Promise.race([closing.then(() => true), delay(5000).then(() => false)]); |
| 54 | if (!detached) { |
| 55 | assert.match(shellStderr, /shutdown complete .*reason=user_quit/, "native service shutdown must finish before fixture cleanup"); |
| 56 | assert.match(shellStderr, /resources cleaned; requesting final shell exit/, "native resource cleanup must finish before fixture cleanup"); |
| 57 | assert.match(shellStderr, /Waiting for the debugger to disconnect|Debugger ending on/, "only debugger teardown may need fixture cleanup after native shutdown"); |
| 58 | terminateFixture(); |
| 59 | await closing; |
| 60 | console.log("INFO cleaned up debugger-held fixture after native window close"); |
| 61 | } |
| 62 | shell = undefined; |
| 63 | } |
| 64 | async function composer(page) { |
| 65 | const input = page.locator(inputSelector); |
| 66 | await input.waitFor(); |
| 67 | await page.waitForFunction(selector => !document.querySelector(selector)?.disabled, inputSelector); |
| 68 | return input; |
| 69 | } |
| 70 | |
| 71 | try { |
| 72 | let page = await launch(); |
| 73 | await rpc(page, "SetCloseBehavior", "background"); |
| 74 | const mainWindow = await shell.browserWindow(page); |
| 75 | await mainWindow.evaluate(win => new Promise((resolve, reject) => { |
| 76 | const timer = setTimeout(() => { clearInterval(poll); reject(new Error("Window did not hide after close")); }, 30000); |
| 77 | const poll = setInterval(() => { if (!win.isVisible()) { clearInterval(poll); clearTimeout(timer); resolve(); } }, 50); |
| 78 | win.close(); |
| 79 | })); |
| 80 | check("empty welcome closes to background without a save error"); |
| 81 | await mainWindow.evaluate(win => win.show()); |
| 82 | // Exercise full shutdown and disk recovery independently of the hide preference. |
| 83 | await rpc(page, "SetCloseBehavior", "quit"); |
| 84 | await closeWindow(); |
| 85 | check("empty welcome closes through the native window event"); |
| 86 | |
| 87 | page = await launch(); |
| 88 | await page.locator(".sidebar__quick-action:visible").first().click(); |
| 89 | let input = await composer(page); |
| 90 | assert.equal(await input.inputValue(), ""); |
| 91 | await closeWindow(); |
| 92 | check("an empty formal session closes without a save error"); |
| 93 | |
| 94 | page = await launch(); |
| 95 | input = await composer(page); |
| 96 | const tab = (await rpc(page, "ListTabs")).find(item => item.active); |
| 97 | assert.ok(tab?.sessionId); |
| 98 | const ref = { hostId: "local", sessionId: tab.sessionId }; |
| 99 | const text = "Keep the latest unsent draft 中文"; |
| 100 | await input.fill(text); |
| 101 | // Do not wait for the 250 ms autosave or invoke the renderer flush manually. |
| 102 | await closeWindow(); |
| 103 | page = await launch(); |
| 104 | input = await composer(page); |
| 105 | assert.equal(await input.inputValue(), text); |
| 106 | assert.equal(JSON.parse((await rpc(page, "GetSessionComposerState", ref)).contentJson).text, text); |
| 107 | check("immediate native close saves the latest text and restores it after restart"); |
| 108 | |
| 109 | const external = join(home, "external.txt"); |
| 110 | writeFileSync(external, "disposable external file reference"); |
| 111 | await page.locator(".composer-content-file-input").setInputFiles(external); |
| 112 | // waitForFunction treats an async predicate's Promise as truthy before |
| 113 | // its result is known. Poll awaited RPCs and retain the matching snapshot. |
| 114 | let content; |
| 115 | const deadline = Date.now() + 30000; |
| 116 | while (Date.now() < deadline) { |
| 117 | const candidate = JSON.parse((await rpc(page, "GetSessionComposerState", ref)).contentJson); |
| 118 | if (candidate.workspaceRefs?.some(item => item.path.endsWith("external.txt"))) { content = candidate; break; } |
| 119 | await delay(50); |
| 120 | } |
| 121 | assert.ok(content, "external reference must be saved before restart"); |
| 122 | assert.equal(content.text, text, "saving a reference must preserve the existing text"); |
| 123 | await closeWindow(); |
| 124 | page = await launch(); |
| 125 | await composer(page); |
| 126 | assert.deepEqual(JSON.parse((await rpc(page, "GetSessionComposerState", ref)).contentJson), content); |
| 127 | await page.locator(".composer-context__item").first().waitFor(); |
| 128 | await closeWindow(); |
| 129 | check("external references survive restart and another normal close without losing saved input"); |
| 130 | } catch (error) { |
| 131 | report.error = String(error); |
| 132 | if (shell) { |
| 133 | const page = shell.windows()[0]; |
| 134 | if (page && !page.isClosed()) writeFileSync(join(home, "failure.txt"), await page.locator("body").innerText().catch(() => "renderer unavailable")); |
| 135 | } |
| 136 | throw error; |
| 137 | } finally { |
| 138 | // Only terminate this isolated fixture after a failed normal-close check. |
| 139 | if (shell) terminateFixture(); |
| 140 | writeFileSync(join(home, "results.json"), JSON.stringify(report, null, 2)); |
| 141 | console.log(`Evidence: ${join(home, "results.json")}`); |
| 142 | } |
| 143 |