background-main.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. import { app, protocol, type BrowserWindow, type WebContents } from "electron";
  2. import assert from "node:assert/strict";
  3. import { randomUUID } from "node:crypto";
  4. import { writeFile } from "node:fs/promises";
  5. import { join } from "node:path";
  6. import { PLUGIN_SANDBOX_PRIVILEGED_SCHEME } from "../../src/main/pluginSandbox/index.js";
  7. import { managedEnvironment } from "./managed-environment.js";
  8. import { evaluateGuest } from "./guest-evaluation.js";
  9. import { clickHostPoint } from "./pointer-input.js";
  10. const [root, profile, node, cli] = process.argv.slice(2) as [string, string, string, string];
  11. if (process.env.ZCODE_FIXTURE_CDP_PORT)
  12. app.commandLine.appendSwitch("remote-debugging-port", process.env.ZCODE_FIXTURE_CDP_PORT);
  13. app.setPath("userData", profile);
  14. protocol.registerSchemesAsPrivileged([PLUGIN_SANDBOX_PRIVILEGED_SCHEME]);
  15. app.on("window-all-closed", () => {});
  16. app
  17. .whenReady()
  18. .then(async () => {
  19. const env = await managedEnvironment(root, node, cli);
  20. const results: Record<string, boolean | string> = {};
  21. try {
  22. if (!process.env.ZCODE_PHOTOCRAFT_ONLY) {
  23. const admitted: Array<{ win: BrowserWindow; guest: WebContents }> = [];
  24. // 先打开外壳但没有任何会话卡片/订阅,再让真实模型调用返回 UI 工具结果。
  25. for (const source of ["admission-first", "admission-second"]) {
  26. const scope = await env.agent.uiSession(join(root, source), source);
  27. const win = await env.createWindow(scope, "background-admission");
  28. const ui = (code: string) => win.webContents.executeJavaScript(code);
  29. assert.equal(env.guests.has(win.webContents.id), false);
  30. assert.equal(
  31. env.events.history.some(
  32. (e) => e.type === "subscribed" && e.owner === win.webContents.id,
  33. ),
  34. false,
  35. );
  36. env.model.plans.push({ key: source, delayed: true, toolName: "open_editor" });
  37. await env.agent.call("v4/command", {
  38. commandId: randomUUID(),
  39. clientId: "admission-fixture",
  40. sessionId: scope.sessionId,
  41. type: "sendText",
  42. issuedAt: Date.now(),
  43. payload: {
  44. text: "Open fixture editor",
  45. mode: "yolo",
  46. modelSelection: env.model.selection,
  47. },
  48. });
  49. await env.agent.events.wait(
  50. (e) => e.source === source && e.type === "executed" && e.key === source,
  51. );
  52. assert.equal(env.guests.has(win.webContents.id), false);
  53. env.agent.release(source, source);
  54. await env.events.wait((e) => e.type === "registered" && e.owner === win.webContents.id);
  55. await ui("window.waitManagedPhase('running')");
  56. await env.evalPage(win, "window.fixtureReady");
  57. const guest = env.guests.get(win.webContents.id)!;
  58. assert.equal((await ui("window.managedState()")).visible, false);
  59. await env.evalPage(
  60. win,
  61. "new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>{window.unsavedDocument={layers:[1,2,3]};resolve(true)})))",
  62. );
  63. await ui("window.expireOffscreen()");
  64. assert.equal(guest.isDestroyed(), false);
  65. await ui("window.revealBackgroundPage()");
  66. assert.equal(env.guests.get(win.webContents.id), guest);
  67. assert.deepEqual(await env.evalPage(win, "window.unsavedDocument"), {
  68. layers: [1, 2, 3],
  69. });
  70. assert.equal(
  71. env.events.history.filter(
  72. (e) => e.type === "registered" && e.owner === win.webContents.id,
  73. ).length,
  74. 1,
  75. );
  76. // 保留两份同插件实例,确认第二份创建不会关闭第一份。
  77. admitted.push({ win, guest });
  78. process.stdout.write(
  79. `PASS ${source}: real tool result with no card/subscription, background frames, retention and reveal\n`,
  80. );
  81. }
  82. assert.equal(env.countGuests(), 2);
  83. // 两个窗口独立释放;并行等待生产 keep-warm 到期,不串行增加测试时限。
  84. await Promise.all(
  85. admitted.map(async ({ win, guest }) => {
  86. assert.equal(guest.isDestroyed(), false);
  87. assert.deepEqual(await env.evalPage(win, "window.unsavedDocument"), {
  88. layers: [1, 2, 3],
  89. });
  90. await win.webContents.executeJavaScript(
  91. "window.stopBackgroundReceiver(); window.removeTask()",
  92. );
  93. await win.webContents.executeJavaScript("window.waitConnectionsReleased()");
  94. assert.equal(guest.isDestroyed(), true);
  95. win.destroy();
  96. }),
  97. );
  98. assert.equal(env.countGuests(), 0);
  99. results.toolResultAdmissionWithoutCardOrSubscription = true;
  100. results.independentSessionsRetainedAndReleased = true;
  101. for (const mode of ["background-cold", "background-hidden", "background-cold-minimized"]) {
  102. const coldScope = await env.agent.session(join(root, mode), "background");
  103. const cold = await env.createWindow(coldScope, mode);
  104. const coldUi = (code: string) => cold.webContents.executeJavaScript(code);
  105. const coldPage = (code: string) => env.evalPage(cold, code);
  106. await coldPage("window.fixtureReady");
  107. const guest = env.guests.get(cold.webContents.id)!;
  108. const dimensions = await coldPage(`new Promise((resolve,reject)=>{
  109. const timeout=setTimeout(()=>reject(new Error('post-handshake frames stopped without a running session')),5000);
  110. requestAnimationFrame(()=>requestAnimationFrame(()=>{clearTimeout(timeout);resolve({width:innerWidth,height:innerHeight})}));
  111. })`);
  112. assert.ok(dimensions.width > 0 && dimensions.height > 0, "隐藏冷启动必须有尺寸和帧");
  113. process.stdout.write(`PASS ${mode}: initialized with nonzero background surface\n`);
  114. await coldPage(
  115. "window.unsavedDocument={layers:[1,2,3]}; window.ticks=0; (function tick(){window.ticks++;requestAnimationFrame(tick)})(); true",
  116. );
  117. await new Promise((resolve) => setTimeout(resolve, 400));
  118. const idle = await coldPage("window.ticks");
  119. await new Promise((resolve) => setTimeout(resolve, 400));
  120. assert.ok((await coldPage("window.ticks")) > idle, "插件内部工作不能因 session 空闲停帧");
  121. process.stdout.write(`PASS ${mode}: internal frames continue without session activity\n`);
  122. if (mode === "background-hidden") {
  123. await coldUi(`document.querySelector('#sidebar-anchor').style.display='block';
  124. new Promise(resolve=>{const check=()=>window.managedState().visible?resolve():setTimeout(check,20);check()})`);
  125. assert.equal(env.guests.get(cold.webContents.id), guest);
  126. }
  127. cold.minimize();
  128. await coldUi(`document.hidden || new Promise(resolve=>document.addEventListener('visibilitychange',function changed(){
  129. if(document.hidden){document.removeEventListener('visibilitychange',changed);resolve()}
  130. }))`);
  131. process.stdout.write(`PASS ${mode}: owner document hidden\n`);
  132. assert.equal(
  133. await coldPage(
  134. "new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve(true))))",
  135. ),
  136. true,
  137. );
  138. process.stdout.write(`PASS ${mode}: minimized execution completed\n`);
  139. await coldUi("window.expireOffscreen()");
  140. assert.equal(guest.isDestroyed(), false);
  141. assert.deepEqual(await coldPage("window.unsavedDocument"), { layers: [1, 2, 3] });
  142. cold.restore();
  143. await coldUi("window.removeTask()");
  144. await coldUi("window.waitConnectionsReleased()");
  145. assert.equal(guest.isDestroyed(), true);
  146. cold.destroy();
  147. process.stdout.write(
  148. `PASS ${mode}: cold boot, post-handshake frames, minimized execution, retention and deletion\n`,
  149. );
  150. }
  151. const scope = await env.agent.session(join(root, "background-workspace"), "background");
  152. const win = await env.createWindow(scope, "background");
  153. const ui = (code: string) => win.webContents.executeJavaScript(code);
  154. const page = (code: string) => env.evalPage(win, code);
  155. await page("window.fixtureReady");
  156. await ui(
  157. "document.querySelector('#inline-scroll').scrollTop=900; new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))",
  158. );
  159. assert.equal((await ui("window.managedState()")).visible, false);
  160. await page(
  161. "new Promise((resolve,reject)=>{const timeout=setTimeout(()=>reject(new Error('offscreen inline frames stopped')),5000);requestAnimationFrame(()=>requestAnimationFrame(()=>{clearTimeout(timeout);resolve(true)}))})",
  162. );
  163. await ui(
  164. "document.querySelector('#inline-scroll').scrollTop=0; new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))",
  165. );
  166. const command = (type: string, payload: unknown) =>
  167. env.agent.call("v4/command", {
  168. commandId: randomUUID(),
  169. clientId: "background-fixture",
  170. sessionId: scope.sessionId,
  171. type,
  172. payload,
  173. issuedAt: Date.now(),
  174. });
  175. const start = async (key: string) => {
  176. env.model.plans.push({ key, delayed: false, holdStream: true });
  177. await command("sendText", {
  178. text: `fixture ${key}`,
  179. modelSelection: env.model.selection,
  180. mode: "build",
  181. });
  182. await env.model.requests.wait((r) => r.plan?.key === key);
  183. };
  184. const stop = async () => {
  185. const after = env.agent.notifications.history.length;
  186. await command("stop", {});
  187. await env.agent.notifications.wait(
  188. (e) =>
  189. e.method === "v4/telemetry/event" &&
  190. e.params.kind === "turn.terminal" &&
  191. e.params.sessionId === scope.sessionId,
  192. after,
  193. );
  194. };
  195. const original = env.guests.get(win.webContents.id)!;
  196. const handle = env.handles.get(win.webContents.id);
  197. await assert.rejects(
  198. ui(
  199. `window.zcodePluginSandbox.setExecutionActive(${JSON.stringify(handle.sandboxId)}, ${handle.initId + 1}, true)`,
  200. ),
  201. /no longer available/,
  202. );
  203. const foreign = await env.createWindow(scope, "web");
  204. await assert.rejects(
  205. foreign.webContents.executeJavaScript(
  206. `window.zcodePluginSandbox.setExecutionActive(${JSON.stringify(handle.sandboxId)}, ${handle.initId}, true)`,
  207. ),
  208. /no longer available/,
  209. );
  210. foreign.destroy();
  211. const siblingHandle = env.native.registerFromHost({
  212. instance: { ...handle.instance, token: randomUUID() },
  213. ownerWebContentsId: win.webContents.id,
  214. sessionId: scope.sessionId,
  215. pluginId: scope.pluginId,
  216. serverName: scope.serverName,
  217. scopeId: "idle-sibling",
  218. html: "<html><body><script>window.ticks=0;function tick(){window.ticks++;requestAnimationFrame(tick)}tick()</script></body></html>",
  219. });
  220. const attached = new Promise<WebContents>((resolve) =>
  221. win.webContents.once("did-attach-webview", (_event, guest) => resolve(guest)),
  222. );
  223. await ui(
  224. `(() => { const guest = document.createElement('webview'); guest.id='idle-sibling'; guest.src=${JSON.stringify(siblingHandle.shellUrl)}; guest.partition=${JSON.stringify(siblingHandle.partition)}; guest.style.cssText='display:flex;width:200px;height:100px'; document.body.append(guest); })()`,
  225. );
  226. const sibling = await attached;
  227. env.guests.set(win.webContents.id, original);
  228. await new Promise<void>((resolve) => {
  229. const check = () => {
  230. if (!sibling.mainFrame.frames.some((frame) => frame.url.includes("/instance/"))) return;
  231. sibling.removeListener("did-frame-finish-load", check);
  232. resolve();
  233. };
  234. sibling.on("did-frame-finish-load", check);
  235. check();
  236. });
  237. await evaluateGuest(
  238. sibling,
  239. "new Promise(resolve => requestAnimationFrame(() => resolve(window.ticks)))",
  240. );
  241. await ui("document.querySelector('#idle-sibling').style.display='none'");
  242. // 此处测量隐藏 guest 是否跑帧,观察窗口是测试本身的负向断言,不承担产品状态同步。
  243. await new Promise((resolve) => setTimeout(resolve, 400));
  244. const siblingBefore = await evaluateGuest(sibling, "window.ticks");
  245. await start("background-first");
  246. await ui("window.setAnchors(false, false)");
  247. assert.equal(await ui("window.suspendManaged()"), false, "运行中的 session 不得回收");
  248. const frames = await page(
  249. "new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve('frames-completed'))))",
  250. );
  251. assert.equal(frames, "frames-completed");
  252. assert.equal(env.guests.get(win.webContents.id), original);
  253. assert.equal(
  254. await ui(
  255. "Boolean(document.elementFromPoint(25,25)?.closest('[data-sandbox-page-root]'))",
  256. ),
  257. false,
  258. );
  259. const hidden = await ui(
  260. "({display:getComputedStyle(document.querySelector('[data-sandbox-page-root]')).display,inert:document.querySelector('[data-sandbox-page-root]').inert})",
  261. );
  262. assert.equal(hidden.inert, true);
  263. assert.equal(
  264. await evaluateGuest(sibling, "window.ticks"),
  265. siblingBefore,
  266. "目标执行不能唤醒同窗空闲 guest",
  267. );
  268. await ui(
  269. `window.zcodePluginSandbox.disposeSandbox(${JSON.stringify(siblingHandle.sandboxId)}, ${siblingHandle.initId})`,
  270. );
  271. await ui("document.querySelector('#idle-sibling').remove()");
  272. await writeFile(
  273. join(root, "background-hidden.png"),
  274. (await win.webContents.capturePage()).toPNG(),
  275. );
  276. process.stdout.write(
  277. "PASS hidden running guest keeps frames and does not intercept clicks\n",
  278. );
  279. await page(
  280. "window.unsavedDocument={name:'retained draft',layers:[1,2,3]}; window.backgroundTicks=0; (function tick(){window.backgroundTicks++;requestAnimationFrame(tick)})(); true",
  281. );
  282. await stop();
  283. const stoppedTicks = await page("window.backgroundTicks");
  284. await page(
  285. "new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve(true))))",
  286. );
  287. assert.ok(
  288. (await page("window.backgroundTicks")) > stoppedTicks,
  289. "session 停止不能冻结插件内部工作",
  290. );
  291. assert.equal(original.isDestroyed(), false);
  292. await ui("window.expireOffscreen()");
  293. assert.equal(await ui("window.suspendManaged()"), false, "空闲 MCP 页面也不得自动回收");
  294. assert.equal(original.isDestroyed(), false);
  295. assert.deepEqual(await page("window.unsavedDocument"), {
  296. name: "retained draft",
  297. layers: [1, 2, 3],
  298. });
  299. process.stdout.write(
  300. "PASS MCP guest keeps internal frames and retains unsaved state past deadline\n",
  301. );
  302. await start("background-expiry");
  303. await page("new Promise(resolve => requestAnimationFrame(() => resolve(true)))");
  304. await ui("window.expireOffscreen()");
  305. assert.equal(await ui("window.suspendManaged()"), false);
  306. await stop();
  307. assert.equal(await ui("window.suspendManaged()"), false);
  308. assert.equal(original.isDestroyed(), false);
  309. // 卡片仍未挂载;下一轮必须唤醒同一 guest,不能靠重建恢复编辑状态。
  310. await start("background-reopen");
  311. assert.equal(env.guests.get(win.webContents.id), original);
  312. assert.equal(env.countGuests(), 1);
  313. assert.equal(
  314. await page(
  315. "new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve(true))))",
  316. ),
  317. true,
  318. );
  319. assert.deepEqual(await page("window.unsavedDocument"), {
  320. name: "retained draft",
  321. layers: [1, 2, 3],
  322. });
  323. process.stdout.write("PASS next turn wakes the same MCP guest without a mounted card\n");
  324. await stop();
  325. await ui("window.removeTask()");
  326. await ui("window.waitConnectionsReleased()");
  327. assert.equal(env.countGuests(), 0);
  328. Object.assign(results, {
  329. coldBootWithoutAnchor: true,
  330. retainedHiddenTabBoot: true,
  331. minimizedVisibleOwner: true,
  332. coldBootWhileMinimized: true,
  333. retainedDuringRun: true,
  334. hiddenFrames: frames,
  335. independentOfSessionActivity: true,
  336. retainedAfterIdleDeadline: true,
  337. unsavedStatePreserved: true,
  338. idleSiblingPreserved: true,
  339. staleAndForeignRequestsRejected: true,
  340. resumedWithoutAnchor: true,
  341. removed: true,
  342. });
  343. }
  344. if (process.env.ZCODE_PHOTOCRAFT_SERVER) {
  345. // 仅此隔离 workspace 内的真实插件测试批准工具,仍经过生产 Agent 权限链路。
  346. env.agent.client.onRequest((request) => {
  347. if (request.method === "interaction/requestPermission")
  348. void env.agent.respond(request, "allow");
  349. });
  350. const craftScope = await env.agent.uiSession(
  351. join(root, "photocraft-workspace"),
  352. "photocraft",
  353. {
  354. serverScript: process.env.ZCODE_PHOTOCRAFT_SERVER,
  355. resourceUri: "ui://photocraft/panel.html",
  356. surface: "editor",
  357. },
  358. );
  359. const craft = await env.createWindow(craftScope, "background-admission-minimized");
  360. const craftUi = (code: string) => craft.webContents.executeJavaScript(code);
  361. const craftPage = (code: string) => env.evalPage(craft, code);
  362. assert.equal(env.guests.has(craft.webContents.id), false);
  363. env.model.plans.push({
  364. key: "photocraft-open",
  365. delayed: false,
  366. toolName: "open_editor",
  367. arguments: {},
  368. });
  369. await env.agent.call("v4/command", {
  370. commandId: randomUUID(),
  371. clientId: "photocraft-admission",
  372. sessionId: craftScope.sessionId,
  373. type: "sendText",
  374. issuedAt: Date.now(),
  375. payload: {
  376. text: "Open the image editor",
  377. mode: "yolo",
  378. modelSelection: env.model.selection,
  379. },
  380. });
  381. await env.events.wait((e) => e.type === "registered" && e.owner === craft.webContents.id);
  382. await craftUi("window.waitManagedPhase('running')");
  383. const boot = await craftPage(`new Promise((resolve,reject)=>{
  384. const check=()=>{const state=window.__craftPlugin;
  385. if(state?.error)reject(new Error(state.error));
  386. else if(state?.automationReady)resolve(state);
  387. else setTimeout(check,100);
  388. };check();
  389. })`);
  390. assert.equal(boot.loaded, true);
  391. process.stdout.write(
  392. "PASS real PhotoCraft: WASM initialized from a real tool result while minimized, without a card\n",
  393. );
  394. const craftGuest = env.guests.get(craft.webContents.id)!;
  395. const craftHandle = env.handles.get(craft.webContents.id);
  396. const call = async (toolName: string, args: Record<string, unknown> = {}) => {
  397. const result = await env.agent.call("mcp/uiCallTool", {
  398. workspace: craftScope.workspace,
  399. sessionId: craftScope.sessionId,
  400. pluginId: craftScope.pluginId,
  401. serverName: craftScope.serverName,
  402. instance: craftHandle.instance,
  403. callId: randomUUID(),
  404. toolName,
  405. arguments: args,
  406. });
  407. assert.ok(!result.isError, JSON.stringify(result));
  408. return result;
  409. };
  410. await call("doc_new", {
  411. width: 64,
  412. height: 48,
  413. name: "Background retained draft",
  414. background: "white",
  415. });
  416. craft.minimize();
  417. await call("command_run", { id: "layer.new.layer", params: { name: "Background layer" } });
  418. const document = await call("doc_inspect");
  419. assert.match(JSON.stringify(document), /Background layer/);
  420. process.stdout.write("PASS real PhotoCraft: minimized document and layer operations\n");
  421. await craftUi("window.expireOffscreen()");
  422. assert.equal(craftGuest.isDestroyed(), false);
  423. assert.deepEqual(await call("doc_inspect"), document);
  424. assert.equal(env.guests.get(craft.webContents.id), craftGuest);
  425. craft.restore();
  426. craft.show();
  427. await craftUi("window.revealBackgroundPage()");
  428. await craftPage(
  429. "new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve(true))))",
  430. );
  431. const canvas = await craftPage(
  432. "(()=>{const canvas=document.querySelector('#craft-stage canvas');return {width:canvas.width,height:canvas.height}})()",
  433. );
  434. assert.ok(canvas.width > 0 && canvas.height > 0);
  435. assert.equal(env.guests.get(craft.webContents.id), craftGuest);
  436. const switchMainPage = async () => {
  437. const point = await craftUi(`(() => {
  438. const r = document.querySelector('#switch-main-page').getBoundingClientRect();
  439. return {x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2)};
  440. })()`);
  441. await clickHostPoint(craft, point);
  442. };
  443. await switchMainPage();
  444. const hidden = await craftUi(`(() => {
  445. const root = document.querySelector('[data-sandbox-page-root]');
  446. return {visible: window.managedState().visible, inert: root.inert,
  447. opacity: getComputedStyle(root).opacity, hit: document.elementFromPoint(600, 200)?.tagName};
  448. })()`);
  449. assert.equal(hidden.visible, false, JSON.stringify(hidden));
  450. assert.equal(hidden.inert, true);
  451. assert.ok(Number(hidden.opacity) <= 0.001);
  452. assert.notEqual(hidden.hit, "WEBVIEW");
  453. await writeFile(
  454. join(root, "photocraft-page-hidden.png"),
  455. (await craft.webContents.capturePage()).toPNG(),
  456. );
  457. // 原始插件不做任何适配:切主页面后仍执行编辑,返回同一 guest 显示新图层。
  458. await call("command_run", { id: "layer.new.layer", params: { name: "Hidden page layer" } });
  459. const hiddenDocument = await call("doc_inspect");
  460. assert.match(JSON.stringify(hiddenDocument), /Hidden page layer/);
  461. await switchMainPage();
  462. assert.equal((await craftUi("window.managedState()")).visible, true);
  463. assert.equal(env.guests.get(craft.webContents.id), craftGuest);
  464. assert.deepEqual(await call("doc_inspect"), hiddenDocument);
  465. await craftPage(
  466. "new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))",
  467. );
  468. results.photocraftHiddenPageExecution = true;
  469. await writeFile(
  470. join(root, "photocraft-restored.png"),
  471. (await craftGuest.capturePage()).toPNG(),
  472. );
  473. process.stdout.write(
  474. "PASS real PhotoCraft: restored the same guest to a visible canvas; captured photocraft-restored.png\n",
  475. );
  476. await craftUi("window.stopBackgroundReceiver(); window.removeTask()");
  477. await craftUi("window.waitConnectionsReleased()");
  478. assert.equal(craftGuest.isDestroyed(), true);
  479. assert.equal(env.countGuests(), 0);
  480. craft.destroy();
  481. results.photoCraft = true;
  482. process.stdout.write(
  483. "PASS real PhotoCraft: background WASM boot, minimized document/layer operations, retained draft and deletion\n",
  484. );
  485. }
  486. await writeFile(join(root, "background-results.json"), JSON.stringify(results));
  487. process.stdout.write(
  488. "PASS MCP page survives idle deadlines, executes in background and releases on deletion\n",
  489. );
  490. } finally {
  491. await env.close();
  492. }
  493. app.exit(0);
  494. })
  495. .catch((error) => {
  496. process.stderr.write(String(error.stack ?? error) + "\n");
  497. app.exit(1);
  498. });