rows-main.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. import { app, protocol } from "electron";
  2. import assert from "node:assert/strict";
  3. import { writeFile } from "node:fs/promises";
  4. import { join } from "node:path";
  5. import { PLUGIN_SANDBOX_PRIVILEGED_SCHEME } from "../../src/main/pluginSandbox/index.js";
  6. import { managedEnvironment } from "./managed-environment.js";
  7. const [root, profile, node, cli] = process.argv.slice(2) as [string, string, string, string];
  8. app.setPath("userData", profile);
  9. protocol.registerSchemesAsPrivileged([PLUGIN_SANDBOX_PRIVILEGED_SCHEME]);
  10. app.on("window-all-closed", () => {});
  11. app
  12. .whenReady()
  13. .then(async () => {
  14. const env = await managedEnvironment(root, node, cli);
  15. const checks: string[] = [];
  16. const check = async (name: string, run: () => Promise<void>) => {
  17. await run();
  18. checks.push(name);
  19. process.stdout.write(`PASS ${name}\n`);
  20. };
  21. try {
  22. const scope = await env.agent.session(join(root, "rows-workspace"), "rows");
  23. const win = await env.createWindow(scope, "rows");
  24. const ui = (code: string) => win.webContents.executeJavaScript(code);
  25. const page = (code: string) => env.evalPage(win, code);
  26. const state = () => ui("window.rowsState()");
  27. const settle = () =>
  28. ui("new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))");
  29. const openRow = async () => {
  30. await ui(`document.querySelector('[data-testid="plugin-ui-open-side-pane"]').click()`);
  31. await settle();
  32. };
  33. const closeSidebar = async () => {
  34. await ui("document.getElementById('close-sidebar').click()");
  35. await settle();
  36. };
  37. const showCard = async () => {
  38. await ui(
  39. `document.querySelector('[data-tool-call-id] [data-testid="plugin-ui-card"]').scrollIntoView({block:'center'})`,
  40. );
  41. await settle();
  42. assert.equal(await ui("window.rowPageVisible()"), true);
  43. };
  44. const expandHistory = async () => {
  45. await ui(
  46. `document.querySelectorAll('button[data-history-open="false"]').forEach(e => e.click())`,
  47. );
  48. await settle();
  49. };
  50. const errors = [
  51. { id: 2, isError: true, fullscreen: true },
  52. { id: 4, isError: true, fullscreen: true },
  53. { id: 6, isError: true, fullscreen: true },
  54. { id: 7, status: "error", fullscreen: true },
  55. { id: 8, status: "cancelled", fullscreen: true },
  56. ];
  57. await check(
  58. "all failures: real timeline rows preserve records but create no App or automatic sidebar",
  59. async () => {
  60. await ui(`window.setRows(${JSON.stringify(errors)}, true)`);
  61. await expandHistory();
  62. assert.equal(
  63. await ui('document.querySelectorAll("[data-tool-call-id]").length'),
  64. errors.length,
  65. );
  66. assert.deepEqual(await state(), {
  67. cards: 0,
  68. placeholders: 0,
  69. opens: 0,
  70. sidebar: false,
  71. views: 0,
  72. owners: [],
  73. });
  74. assert.equal(env.events.history.filter((e) => e.type === "registered").length, 0);
  75. assert.equal(env.agent.events.history.filter((e) => e.type === "read").length, 0);
  76. },
  77. );
  78. await check("explicit widgetSessionId failures also cannot create App anchors", async () => {
  79. await ui(
  80. `window.setRows(${JSON.stringify(errors.map((row) => ({ ...row, widget: true })))}, true)`,
  81. );
  82. await expandHistory();
  83. assert.equal(
  84. await ui('document.querySelectorAll("[data-tool-call-id]").length'),
  85. errors.length,
  86. );
  87. const s = await state();
  88. assert.equal(s.cards, 0);
  89. assert.equal(s.placeholders, 0);
  90. assert.equal(s.opens, 0);
  91. assert.equal(s.views, 0);
  92. assert.equal(env.agent.events.history.filter((e) => e.type === "read").length, 0);
  93. });
  94. const mixed = [{ id: 1 }, errors[0], { id: 3 }, errors[1], { id: 5 }, ...errors.slice(2)];
  95. const attached = new Promise<void>((resolve) =>
  96. win.webContents.once("did-attach-webview", () => resolve()),
  97. );
  98. await ui(`window.setRows(${JSON.stringify(mixed)})`);
  99. await attached;
  100. await ui("window.waitRowsRunning()");
  101. await page("window.fixtureReady");
  102. await expandHistory();
  103. const guestId = env.guests.get(win.webContents.id)!.id;
  104. await check(
  105. "success plus three MCP errors, transport error and cancellation leaves one latest-success anchor",
  106. async () => {
  107. const s = await state();
  108. assert.equal(s.cards, 1);
  109. assert.equal(s.views, 1);
  110. assert.equal(s.opens, 0);
  111. assert.deepEqual(s.owners, ["row-5"]);
  112. await showCard();
  113. assert.equal(
  114. await ui('document.querySelectorAll("[data-tool-call-id]").length'),
  115. mixed.length,
  116. );
  117. await page("document.getElementById('counter').click()");
  118. await page("new Promise(r => requestAnimationFrame(r))");
  119. assert.equal(await page("document.getElementById('counter').textContent"), "1");
  120. },
  121. );
  122. const started = performance.now();
  123. await check(
  124. "20 real row-button inline/sidebar round trips keep one guest, one anchor and React state",
  125. async () => {
  126. for (let i = 0; i < 20; i++) {
  127. await ui(`document.querySelector('[data-testid="plugin-ui-open-side-pane"]').click()`);
  128. await settle();
  129. let s = await state();
  130. assert.equal(s.cards, 0);
  131. assert.equal(s.placeholders, 1);
  132. assert.equal(s.views, 1);
  133. assert.deepEqual(s.owners, ["row-5"]);
  134. await ui("document.getElementById('close-sidebar').click()");
  135. await settle();
  136. s = await state();
  137. assert.equal(s.cards, 1);
  138. assert.equal(s.placeholders, 0);
  139. await showCard();
  140. assert.equal(env.guests.get(win.webContents.id)!.id, guestId);
  141. }
  142. assert.equal(await page("document.getElementById('counter').textContent"), "1");
  143. assert.equal(await page("window.starts"), 1);
  144. assert.equal(env.events.history.filter((e) => e.type === "registered").length, 1);
  145. assert.equal(env.agent.events.history.filter((e) => e.type === "read").length, 1);
  146. assert.equal(env.events.history.filter((e) => e.type === "subscribed").length, 1);
  147. },
  148. );
  149. const switchesMs = performance.now() - started;
  150. await check(
  151. "timeline unmount/remount and later error preserve the good page without fullscreen stealing",
  152. async () => {
  153. await ui("window.mountRows(false)");
  154. await ui("window.mountRows(true)");
  155. await expandHistory();
  156. await ui(
  157. `window.setRows(${JSON.stringify([...mixed, { id: 9, isError: true, fullscreen: true }])})`,
  158. );
  159. await expandHistory();
  160. const s = await state();
  161. assert.equal(s.opens, 20);
  162. assert.equal(s.cards, 1);
  163. assert.deepEqual(s.owners, ["row-5"]);
  164. assert.equal(env.guests.get(win.webContents.id)!.id, guestId);
  165. assert.equal(await page("document.getElementById('counter').textContent"), "1");
  166. },
  167. );
  168. await check(
  169. "new successful fullscreen result still opens once and reuses the existing page",
  170. async () => {
  171. await ui(`window.setRows(${JSON.stringify([...mixed, { id: 10, fullscreen: true }])})`);
  172. await settle();
  173. const s = await state();
  174. assert.equal(s.opens, 21);
  175. assert.equal(s.placeholders, 1);
  176. assert.deepEqual(s.owners, ["row-10"]);
  177. assert.deepEqual(await page("window.requestDisplayMode('inline')"), {
  178. mode: "fullscreen",
  179. });
  180. assert.equal((await state()).sidebar, true);
  181. await ui("document.getElementById('close-sidebar').click()");
  182. await settle();
  183. assert.deepEqual((await state()).owners, ["row-10"]);
  184. assert.equal((await state()).cards, 0);
  185. assert.equal((await state()).placeholders, 1);
  186. assert.equal(await ui("window.rowPageVisible()"), false);
  187. assert.equal((await state()).views, 1);
  188. assert.equal(await page("window.starts"), 1);
  189. assert.equal(
  190. await page(
  191. "new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve('running'))))",
  192. ),
  193. "running",
  194. );
  195. assert.equal(env.guests.get(win.webContents.id)!.id, guestId);
  196. assert.equal(await page("document.getElementById('counter').textContent"), "1");
  197. assert.equal(env.agent.events.history.filter((e) => e.type === "read").length, 1);
  198. assert.equal(env.events.history.filter((e) => e.type === "registered").length, 1);
  199. },
  200. );
  201. await check(
  202. "closed fullscreen call stays closed after session view unmount and remount",
  203. async () => {
  204. const opens = (await state()).opens;
  205. await ui("window.mountRows(false)");
  206. await ui("window.mountRows(true)");
  207. assert.equal((await state()).sidebar, false);
  208. assert.equal((await state()).opens, opens);
  209. assert.equal((await state()).cards, 0);
  210. assert.equal((await state()).placeholders, 1);
  211. assert.equal(await ui("window.rowPageVisible()"), false);
  212. assert.equal(env.guests.get(win.webContents.id)!.id, guestId);
  213. await openRow();
  214. assert.equal((await state()).sidebar, true);
  215. assert.equal((await state()).opens, opens + 1);
  216. },
  217. );
  218. await check(
  219. "calls arriving in an open sidebar are consumed; later new calls still open",
  220. async () => {
  221. await ui(`window.setRows(${JSON.stringify([...mixed, { id: 11, fullscreen: true }])})`);
  222. const opens = (await state()).opens;
  223. await closeSidebar();
  224. await ui("window.mountRows(false)");
  225. await ui("window.mountRows(true)");
  226. assert.equal((await state()).sidebar, false);
  227. assert.equal((await state()).opens, opens);
  228. await ui(`window.setRows(${JSON.stringify([...mixed, { id: 12, fullscreen: true }])})`);
  229. assert.equal((await state()).sidebar, true);
  230. assert.equal((await state()).opens, opens + 1);
  231. assert.equal(env.guests.get(win.webContents.id)!.id, guestId);
  232. await closeSidebar();
  233. },
  234. );
  235. assert.equal((await state()).cards, 0);
  236. assert.equal(await page("window.starts"), 1);
  237. assert.equal(await page("document.getElementById('counter').textContent"), "1");
  238. await writeFile(
  239. join(root, "rows-fullscreen-preference.png"),
  240. (await win.webContents.capturePage()).toPNG(),
  241. );
  242. for (const modes of ["fullscreen", "inline", "inline,fullscreen", "pip"]) {
  243. await check(
  244. `registered modes ${modes}: handshake, entry, requests and remount`,
  245. async () => {
  246. const nextScope = await env.agent.session(
  247. join(root, `modes-${modes.replace(",", "-")}`),
  248. "rows",
  249. );
  250. const next = await env.createWindow(
  251. { ...nextScope, resourceUri: `ui://fixture/modes/${modes}` },
  252. "rows",
  253. );
  254. const run = (code: string) => next.webContents.executeJavaScript(code);
  255. const appPage = (code: string) => env.evalPage(next, code);
  256. const layout = () =>
  257. run("new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))");
  258. const loaded = new Promise<void>((resolve) =>
  259. next.webContents.once("did-attach-webview", (_event, guest) => {
  260. const onLoad = (_event: unknown, isMainFrame: boolean) => {
  261. if (
  262. isMainFrame ||
  263. !guest.mainFrame.frames.some((frame) => frame.url.includes("/instance/"))
  264. )
  265. return;
  266. guest.removeListener("did-frame-finish-load", onLoad);
  267. resolve();
  268. };
  269. guest.on("did-frame-finish-load", onLoad);
  270. }),
  271. );
  272. await run(`window.setRows([{id:1,fullscreen:${modes === "inline"}}])`);
  273. await loaded;
  274. // 页面有意延迟 initialize;真实 guest 已加载但不能先闪现 inline。
  275. assert.equal(await run("window.rowPageVisible()"), false);
  276. assert.equal((await run("window.rowsState()")).opens, 0);
  277. await appPage("window.releaseFixtureConnect()");
  278. await run("window.waitRowsRunning()");
  279. await appPage("window.fixtureReady");
  280. await layout();
  281. const state = () => run("window.rowsState()");
  282. const guest = env.guests.get(next.webContents.id)!.id;
  283. if (modes === "fullscreen") {
  284. assert.equal((await state()).cards, 0);
  285. assert.equal((await state()).placeholders, 1);
  286. assert.equal((await state()).sidebar, false);
  287. assert.equal(await run("window.rowPageVisible()"), false);
  288. assert.equal(
  289. await run("document.querySelectorAll('[data-testid=plugin-ui-pin-toggle]').length"),
  290. 0,
  291. );
  292. await run("document.querySelector('[data-testid=plugin-ui-open-side-pane]').click()");
  293. await layout();
  294. assert.equal((await state()).sidebar, true);
  295. assert.equal(await run("window.rowPageVisible()"), true);
  296. assert.deepEqual((await appPage("window.displayContext()")).availableDisplayModes, [
  297. "fullscreen",
  298. ]);
  299. assert.deepEqual(await appPage("window.requestDisplayMode('inline')"), {
  300. mode: "fullscreen",
  301. });
  302. assert.equal((await state()).sidebar, true);
  303. await run("document.getElementById('close-sidebar').click()");
  304. await layout();
  305. assert.equal((await state()).cards, 0);
  306. assert.equal((await state()).placeholders, 1);
  307. assert.equal(await run("window.rowPageVisible()"), false);
  308. await run("window.mountRows(false)");
  309. await run("window.mountRows(true)");
  310. assert.equal((await state()).sidebar, false);
  311. assert.equal((await state()).cards, 0);
  312. await run("window.setRows([{id:1},{id:2,fullscreen:true}])");
  313. await layout();
  314. assert.equal((await state()).sidebar, true);
  315. await run("document.getElementById('close-sidebar').click()");
  316. await layout();
  317. await run("window.mountRows(false)");
  318. await run("window.mountRows(true)");
  319. assert.equal((await state()).sidebar, false);
  320. assert.equal((await state()).opens, 2);
  321. assert.equal(env.guests.get(next.webContents.id)!.id, guest);
  322. await writeFile(
  323. join(root, "rows-fullscreen-card.png"),
  324. (await next.webContents.capturePage()).toPNG(),
  325. );
  326. } else if (modes === "inline") {
  327. assert.equal((await state()).cards, 1);
  328. assert.equal(
  329. await run(
  330. "document.querySelectorAll('[data-testid=plugin-ui-open-side-pane]').length",
  331. ),
  332. 0,
  333. );
  334. assert.deepEqual(await appPage("window.requestDisplayMode('fullscreen')"), {
  335. mode: "inline",
  336. });
  337. await run("window.setRows([{id:1},{id:2,fullscreen:true}])");
  338. await layout();
  339. assert.equal((await state()).opens, 0);
  340. assert.equal((await state()).cards, 1);
  341. } else if (modes === "pip") {
  342. assert.equal((await state()).cards, 0);
  343. assert.equal((await state()).placeholders, 0);
  344. assert.equal(await run("window.rowPageVisible()"), false);
  345. } else {
  346. assert.equal((await state()).cards, 1);
  347. await run("document.querySelector('[data-testid=plugin-ui-open-side-pane]').click()");
  348. await layout();
  349. assert.equal((await state()).sidebar, true);
  350. await run("document.getElementById('close-sidebar').click()");
  351. await layout();
  352. assert.equal((await state()).cards, 1);
  353. await run("window.setRows([{id:1},{id:2,fullscreen:true}])");
  354. await layout();
  355. assert.equal((await state()).sidebar, true);
  356. await run("document.getElementById('close-sidebar').click()");
  357. await layout();
  358. assert.equal((await state()).cards, 0);
  359. assert.equal((await state()).placeholders, 1);
  360. assert.equal(await run("window.rowPageVisible()"), false);
  361. assert.deepEqual((await appPage("window.displayContext()")).availableDisplayModes, [
  362. "fullscreen",
  363. ]);
  364. await run("window.mountRows(false)");
  365. await run("window.mountRows(true)");
  366. assert.equal((await state()).cards, 0);
  367. assert.equal((await state()).sidebar, false);
  368. assert.equal(env.guests.get(next.webContents.id)!.id, guest);
  369. assert.equal(await appPage("window.starts"), 1);
  370. // 后续成功调用显式改回 inline,必须复用原 guest,不能被最初的 fullscreen 选择锁死。
  371. await run("window.setRows([{id:3}])");
  372. await layout();
  373. assert.equal((await state()).cards, 1);
  374. assert.equal(env.guests.get(next.webContents.id)!.id, guest);
  375. }
  376. next.destroy();
  377. },
  378. );
  379. }
  380. await writeFile(
  381. join(root, "rows-results.json"),
  382. JSON.stringify({ checks, switchesMs, guestId, state: await state() }, null, 2),
  383. );
  384. } finally {
  385. await env.close();
  386. }
  387. app.exit(0);
  388. })
  389. .catch((error) => {
  390. process.stderr.write(String(error.stack ?? error) + "\n");
  391. app.exit(1);
  392. });