| 1 | // Actual packaged shell/service, disposable home, loopback provider only. |
| 2 | // Usage: node desktop/packaging/provider-diagnostic-smoke.mjs /path/Reasonix.app |
| 3 | import assert from "node:assert/strict"; |
| 4 | import { createServer } from "node:http"; |
| 5 | import { createRequire } from "node:module"; |
| 6 | import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs"; |
| 7 | import { tmpdir } from "node:os"; |
| 8 | import { join, resolve } from "node:path"; |
| 9 | import { packagedSmokeEnv } from "./smoke-env.mjs"; |
| 10 | import { waitForSmokeCondition, parseServiceReady } from "./smoke-poll.mjs"; |
| 11 | import { closeAndVerify, processAlive, waitForProcessesToExit } from "./smoke-lifecycle.mjs"; |
| 12 | |
| 13 | const require = createRequire(new URL("../electron/package.json", import.meta.url)); |
| 14 | const { _electron } = require("playwright"); |
| 15 | const bundle = resolve(process.argv[2]); |
| 16 | const home = mkdtempSync(join(tmpdir(), "reasonix-provider-native-")); |
| 17 | const output = process.env.REASONIX_SMOKE_ARTIFACTS || home; |
| 18 | mkdirSync(output, { recursive: true }); |
| 19 | let mode = "hold", calls = 0; |
| 20 | const sockets = new Set(); |
| 21 | const server = createServer((req) => { |
| 22 | calls++; |
| 23 | // Drain first and close with FIN so the live fixture consistently produces |
| 24 | // EOF rather than a platform-dependent reset while the body is still writing. |
| 25 | if (mode === "eof") req.on("end", () => req.socket.end()); |
| 26 | req.resume(); |
| 27 | }); |
| 28 | server.on("connection", socket => { sockets.add(socket); socket.on("close", () => sockets.delete(socket)); }); |
| 29 | await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); |
| 30 | mkdirSync(join(home, "sessions")); |
| 31 | writeFileSync(join(home, "config.toml"), `default_model = "fixture/model"\n[desktop]\nprovider_access = ["fixture"]\n[[providers]]\nname = "fixture"\nkind = "openai"\nbase_url = "http://127.0.0.1:${server.address().port}/v1"\nmodels = ["model"]\ndefault = "model"\napi_key_env = "PROVIDER_FIXTURE_KEY"\n`); |
| 32 | const fixturePath = join(home, "sessions", "send-failure.jsonl"); |
| 33 | writeFileSync(fixturePath, [ |
| 34 | { role: "user", content: "Historical send failure" }, |
| 35 | { role: "tool", local_only: true, interrupted_turn: { pending: true, terminalStatus: "failed", failureDiagnostic: { kind: "request_send_timeout", providerId: "fixture", protocol: "openai" } } }, |
| 36 | ].map(v => JSON.stringify(v)).join("\n") + "\n"); |
| 37 | let application, page, passed = false; |
| 38 | const quitFailures = []; |
| 39 | const invoke = (method, args = []) => page.evaluate(({ method, args }) => window.reasonixDesktop.invoke(method, args), { method, args }); |
| 40 | async function launch() { |
| 41 | const build = JSON.parse(readFileSync(join(bundle, "Contents/Resources/build.json"), "utf8")); |
| 42 | application = await _electron.launch({ executablePath: join(bundle, "Contents/MacOS/Reasonix"), |
| 43 | env: { ...packagedSmokeEnv(process.env, home), PROVIDER_FIXTURE_KEY: "local-fixture-key" }, timeout: 60000 }); |
| 44 | await waitForSmokeCondition(async () => { |
| 45 | for (const p of application.windows()) { |
| 46 | const version = await p.evaluate(() => window.reasonixDesktop?.invoke("Version", [])).catch(() => null); |
| 47 | if (version === build.version) { page = p; return true; } |
| 48 | } |
| 49 | return false; |
| 50 | }, { timeout: 60000 }); |
| 51 | assert.equal(await invoke("Version"), build.version); |
| 52 | assert.equal(await application.evaluate(({ app }) => app.isPackaged && !process.env.REASONIX_DEV), true); |
| 53 | } |
| 54 | async function quit() { |
| 55 | const ready = readFileSync(join(home, "desktop-shell/logs/shell.log"), "utf8").split("\n").reverse().map(parseServiceReady).find(Boolean); |
| 56 | assert.ok(ready, "packaged service announced readiness"); |
| 57 | const shellPid = await application.evaluate(() => process.pid); |
| 58 | try { |
| 59 | await closeAndVerify(application, { shellPid, servicePid: ready.pid }); |
| 60 | } catch (error) { |
| 61 | console.error(`Quit verification failed: shellAlive=${processAlive(shellPid)} serviceAlive=${processAlive(ready.pid)}`); |
| 62 | quitFailures.push(error); |
| 63 | // Retain the failed verdict, but still exercise cold recovery/export after |
| 64 | // cleanup. Only these two processes were created in this disposable home. |
| 65 | for (const pid of [shellPid, ready.pid]) if (processAlive(pid)) process.kill(pid, "SIGKILL"); |
| 66 | await waitForProcessesToExit([shellPid, ready.pid]); |
| 67 | } |
| 68 | application = null; |
| 69 | } |
| 70 | async function activeTab() { return (await invoke("ListTabs")).find(t => t.active); } |
| 71 | async function exportDiagnostic(name) { |
| 72 | const path = join(output, name); |
| 73 | // Choose a deterministic destination through the real native-dialog owner. |
| 74 | await application.evaluate(({ dialog }, path) => { dialog.showSaveDialog = async () => ({ canceled: false, filePath: path }); }, path); |
| 75 | const tab = await activeTab(); |
| 76 | const handle = await invoke("BeginSessionExportForTarget", [{ sessionPath: tab.sessionPath }, tab.id, "diagnostic", "provider-smoke", ""]); |
| 77 | assert.ok(handle.exportId); |
| 78 | await invoke("FinishSessionExport", [handle.exportId]); |
| 79 | const raw = readFileSync(path, "utf8"); |
| 80 | assert.doesNotThrow(() => JSON.parse(raw)); |
| 81 | assert.ok(!raw.includes("local-fixture-key")); |
| 82 | return raw; |
| 83 | } |
| 84 | try { |
| 85 | await launch(); |
| 86 | const folder = page.locator(".project-tree__folder-main").first(); |
| 87 | await folder.waitFor(); |
| 88 | if (await folder.getAttribute("aria-expanded") !== "true") await folder.click(); |
| 89 | await page.locator(".project-tree__topic-main").filter({ has: page.getByText("send-failure", { exact: true }) }).click(); |
| 90 | await page.waitForFunction(() => document.querySelector(".chat-transcript")?.textContent?.includes("300")); |
| 91 | await page.locator(".user-error__toggle").first().click(); |
| 92 | await page.screenshot({ path: join(output, "provider-send-timeout.png") }); |
| 93 | await waitForSmokeCondition(async () => (await activeTab())?.ready === true); |
| 94 | // Legacy fixtures are read-only sources until the normal import flow prepares |
| 95 | // a canonical session. Use the same RPCs as the historical-source banner. |
| 96 | const historical = (await activeTab()).historicalSource; |
| 97 | if (historical) { |
| 98 | let preparation = await invoke("PrepareSession", [{ source: historical }]); |
| 99 | await waitForSmokeCondition(async () => { |
| 100 | preparation = await invoke("GetSessionPreparation", [preparation.operationId]); |
| 101 | assert.ok(!["failed", "blocked"].includes(preparation.status), JSON.stringify(preparation)); |
| 102 | return preparation.status === "ready"; |
| 103 | }); |
| 104 | await invoke("OpenSession", [preparation.target]); |
| 105 | await waitForSmokeCondition(async () => { |
| 106 | const current = await activeTab(); |
| 107 | return current?.ready && !current.historicalSource; |
| 108 | }); |
| 109 | } |
| 110 | const tab = await activeTab(); |
| 111 | await invoke("SubmitToTabWithID", [tab.id, "Cancellation fixture", "cancel-fixture"]); |
| 112 | await waitForSmokeCondition(() => calls > 0); |
| 113 | await invoke("CancelTab", [tab.id]); |
| 114 | await waitForSmokeCondition(async () => !(await activeTab()).running); |
| 115 | console.log("PASS packaged stop operation against a waiting loopback provider"); |
| 116 | const before = calls; |
| 117 | mode = "eof"; |
| 118 | await invoke("SubmitToTabWithID", [tab.id, "EOF fixture", "eof-fixture"]); |
| 119 | await waitForSmokeCondition(() => calls > before); |
| 120 | await page.waitForFunction(() => [...document.querySelectorAll(".user-error")].some(e => e.textContent?.includes("EOF"))); |
| 121 | await waitForSmokeCondition(async () => !(await activeTab()).running); |
| 122 | const live = await exportDiagnostic("provider-live.json"); |
| 123 | assert.match(live, /transport_eof/); |
| 124 | assert.match(live, /errorCode/); |
| 125 | await page.screenshot({ path: join(output, "provider-eof-live.png") }); |
| 126 | await quit(); |
| 127 | await launch(); |
| 128 | await page.waitForFunction(() => [...document.querySelectorAll(".user-error")].some(e => e.textContent?.includes("EOF"))); |
| 129 | const cold = await exportDiagnostic("provider-cold.json"); |
| 130 | assert.match(cold, /transport_eof/); |
| 131 | assert.match(cold, /diagnostic\/provider/); |
| 132 | assert.match(cold, /errorCode/); |
| 133 | await page.screenshot({ path: join(output, "provider-eof-reopened.png") }); |
| 134 | console.log("PASS packaged historical timeout details, live EOF, restart and safe cold export"); |
| 135 | await quit(); |
| 136 | assert.equal(quitFailures.length, 0, "normal quit failed; forced cleanup is not a passing lifecycle check"); |
| 137 | passed = true; |
| 138 | console.log("PASS packaged clean exit"); |
| 139 | } finally { |
| 140 | if (application) await quit().catch(() => application.close()); |
| 141 | for (const socket of sockets) socket.destroy(); |
| 142 | await new Promise(resolve => server.close(resolve)); |
| 143 | if (passed && output !== home) rmSync(home, { recursive: true, force: true }); |
| 144 | console.log(`Native smoke artifacts: ${output}`); |
| 145 | if (!passed) console.log(`Failed smoke home: ${home}`); |
| 146 | } |
| 147 |