showcase-main.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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 { randomUUID } from "node:crypto";
  6. import { PLUGIN_SANDBOX_PRIVILEGED_SCHEME } from "../../src/main/pluginSandbox/index.js";
  7. import { managedEnvironment } from "./managed-environment.js";
  8. const [root, profile, node, cli, serverScript] = process.argv.slice(2) as [
  9. string,
  10. string,
  11. string,
  12. string,
  13. string,
  14. ];
  15. app.setPath("userData", profile);
  16. protocol.registerSchemesAsPrivileged([PLUGIN_SANDBOX_PRIVILEGED_SCHEME]);
  17. app.on("window-all-closed", () => {});
  18. app
  19. .whenReady()
  20. .then(async () => {
  21. const env = await managedEnvironment(root, node, cli);
  22. const checks: string[] = [];
  23. try {
  24. // 独立 fixture 只批准本测试的两个演示工具;审批仍通过真实 Agent/宿主链路。
  25. env.agent.client.onRequest((request) => {
  26. const input = (request.params as any)?.input;
  27. if (
  28. request.method === "interaction/requestPermission" &&
  29. (input?.durationMs === 10_000 ||
  30. input?.filter === "all" ||
  31. String(input?.key).startsWith("showcase-page"))
  32. )
  33. void env.agent.respond(request, "allow");
  34. });
  35. const scope = await env.agent.session(
  36. join(root, "showcase-workspace"),
  37. "showcase",
  38. "showcase",
  39. undefined,
  40. {
  41. serverScript,
  42. resourceUri: "ui://showcase/cases.html",
  43. },
  44. );
  45. await env.agent.call("session/setModel", {
  46. sessionId: scope.sessionId,
  47. model: env.model.selection,
  48. });
  49. const win = await env.createWindow(scope, "sampling");
  50. const page = (code: string) => env.evalPage(win, code);
  51. const ui = (code: string) => win.webContents.executeJavaScript(code);
  52. const click = (id: string) => page(`document.getElementById(${JSON.stringify(id)}).click()`);
  53. const value = (id: string, text: string) =>
  54. page(`document.getElementById(${JSON.stringify(id)}).value=${JSON.stringify(text)}`);
  55. const read = (id: string) =>
  56. page(`document.getElementById(${JSON.stringify(id)}).textContent`);
  57. // DOM 事件驱动观察实际按钮处理的终态,不用睡眠代替请求完成。
  58. const phase = (id: string, wanted: string) =>
  59. page(`new Promise(resolve => {
  60. const node=document.getElementById(${JSON.stringify(id)});
  61. const check=()=>{if(node.dataset.phase===${JSON.stringify(wanted)}){observer.disconnect();resolve(node.textContent)}};
  62. const observer=new MutationObserver(check);observer.observe(node,{attributes:true,childList:true,subtree:true});check();
  63. })`);
  64. const check = async (name: string, run: () => Promise<void>) => {
  65. let timer: ReturnType<typeof setTimeout> | undefined;
  66. try {
  67. await Promise.race([
  68. run(),
  69. new Promise<never>((_, reject) => {
  70. timer = setTimeout(() => reject(new Error(`Timed out: ${name}`)), 20_000);
  71. }),
  72. ]);
  73. checks.push(name);
  74. process.stdout.write(`PASS Showcase ${name}\n`);
  75. } finally {
  76. clearTimeout(timer);
  77. }
  78. };
  79. await check("built HTML connects once and all 53 cases have reachable details", async () => {
  80. assert.equal(await page("document.querySelectorAll('[data-case-id]').length"), 53);
  81. assert.match(await read("connection"), /Connected|已连接/);
  82. assert.equal(await page("document.querySelectorAll('[data-case-id]').length"), 53);
  83. for (let index = 1; index <= 53; index++) {
  84. const id = `SC${String(index).padStart(2, "0")}`;
  85. await page(`document.querySelector('[data-case-id="${id}"]').click()`);
  86. assert.match(await read("case-detail"), new RegExp(id));
  87. }
  88. await value("case-mode", "pending");
  89. await page("document.getElementById('case-mode').dispatchEvent(new Event('change'))");
  90. assert.equal(await page("document.querySelectorAll('[data-case-id]').length"), 2);
  91. assert.equal(await page("document.getElementById('send-demo').disabled"), true);
  92. await value("case-mode", "all");
  93. await page("document.getElementById('case-mode').dispatchEvent(new Event('change'))");
  94. });
  95. await check("page heap, input, local scroll and guest survive twenty moves", async () => {
  96. const boot = await read("boot-id");
  97. const guest = env.guests.get(win.webContents.id)!.id;
  98. await click("heap-bump");
  99. await value("heap-input", "retained by the actual Showcase page");
  100. await page("document.getElementById('heap-scroll').scrollTop=90");
  101. for (let i = 0; i < 20; i++) await ui(`window.setAnchors(${i % 2 !== 0},${i % 2 === 0})`);
  102. assert.equal(env.guests.get(win.webContents.id)!.id, guest);
  103. assert.equal(await read("boot-id"), boot);
  104. assert.equal(await read("heap-count"), "1");
  105. assert.equal(
  106. await page("document.getElementById('heap-input').value"),
  107. "retained by the actual Showcase page",
  108. );
  109. assert.equal(await page("document.getElementById('heap-scroll').scrollTop"), 90);
  110. });
  111. await check(
  112. "real storage buttons round-trip, rebuild and delete only lab samples",
  113. async () => {
  114. await value("storage-value", "persistent sample");
  115. await click("storage-write");
  116. assert.deepEqual(JSON.parse(await phase("storage-result", "complete")), {
  117. localStorage: "persistent sample",
  118. indexedDB: "persistent sample",
  119. });
  120. const oldBoot = await read("boot-id");
  121. const oldGuest = env.guests.get(win.webContents.id)!;
  122. const destroyed = new Promise<void>((resolve) => oldGuest.once("destroyed", resolve));
  123. await ui("window.retryManaged()");
  124. await destroyed;
  125. await ui("window.waitManagedPhase('running')");
  126. await page("window.showcaseReady");
  127. assert.notEqual(await read("boot-id"), oldBoot);
  128. await click("storage-read");
  129. assert.deepEqual(JSON.parse(await phase("storage-result", "complete")), {
  130. localStorage: "persistent sample",
  131. indexedDB: "persistent sample",
  132. });
  133. await click("storage-delete");
  134. assert.deepEqual(JSON.parse(await phase("storage-result", "complete")), {
  135. localStorage: null,
  136. indexedDB: null,
  137. });
  138. },
  139. );
  140. await check(
  141. "actual App long-tool button cancels through Agent and can complete a new call",
  142. async () => {
  143. const after = env.events.history.length;
  144. await click("check-start");
  145. await phase("check-status", "running");
  146. await click("check-cancel");
  147. await phase("check-status", "cancelled");
  148. await env.events.wait(
  149. (event) => event.type === "bridge" && event.method === "cancelToolCall",
  150. after,
  151. );
  152. await click("check-start");
  153. assert.match(await phase("check-status", "complete"), /completed/);
  154. },
  155. );
  156. const before = await env.agent.call("session/read", { sessionId: scope.sessionId });
  157. await check(
  158. "sampling buttons send completed page history and demo image, not main chat",
  159. async () => {
  160. for (let i = 0; i < 2; i++) {
  161. env.model.plans.push({ key: `showcase-${i}`, delayed: false });
  162. await value("sampling-prompt", `question ${i}`);
  163. if (i === 1) await click("sampling-image");
  164. await click("sampling-send");
  165. assert.match(await phase("sampling-status", "complete"), /gpt-4o/);
  166. assert.equal(env.model.requests.history.at(-1).body.messages.length, i * 2 + 1);
  167. }
  168. assert.match(
  169. JSON.stringify(env.model.requests.history.at(-1).body.messages),
  170. /data:image\/png;base64/,
  171. );
  172. assert.match(await read("sampling-history"), /answer:showcase-1/);
  173. const after = await env.agent.call("session/read", { sessionId: scope.sessionId });
  174. assert.deepEqual(after.messages, before.messages);
  175. await click("sampling-reset");
  176. assert.equal(await read("sampling-history"), "");
  177. },
  178. );
  179. await check(
  180. "actual sampling cancellation aborts provider and excludes failed history",
  181. async () => {
  182. env.model.plans.push({ key: "showcase-cancel", delayed: true });
  183. await value("sampling-prompt", "cancel this request");
  184. await click("sampling-send");
  185. await env.model.requests.wait((event) => event.plan?.key === "showcase-cancel");
  186. await click("sampling-cancel");
  187. await phase("sampling-status", "cancelled");
  188. await env.model.aborted.wait((key) => key === "showcase-cancel");
  189. env.model.release("showcase-cancel");
  190. assert.equal(await read("sampling-history"), "");
  191. },
  192. );
  193. await check("unsupported sampling controls reject before reaching the provider", async () => {
  194. const requests = env.model.requests.history.length;
  195. for (const invalid of ["temperature", "tools", "audio"]) {
  196. await value("sampling-invalid", invalid);
  197. await click("sampling-reject");
  198. await phase("sampling-status", "rejected");
  199. }
  200. assert.equal(env.model.requests.history.length, requests);
  201. assert.equal(await read("sampling-history"), "");
  202. });
  203. await check(
  204. "failure controls prepare the selected model tool without sending automatically",
  205. async () => {
  206. await value("failure-mode", "fullscreen");
  207. await click("failure-throw");
  208. await click("failure-prepare");
  209. const prompt = await page("document.getElementById('demo-prompt').value");
  210. assert.match(prompt, /show_failure_fullscreen/);
  211. assert.match(prompt, /"throwError":true/);
  212. },
  213. );
  214. await check(
  215. "live host context switches Chinese/dark at 320px without horizontal overflow",
  216. async () => {
  217. const boot = await read("boot-id");
  218. await ui("window.setShowcasePresentation('dark','zh-CN',320)");
  219. assert.equal(await page("document.documentElement.lang"), "zh-CN");
  220. assert.equal(await page("document.documentElement.style.colorScheme"), "dark");
  221. assert.equal(
  222. await page("getComputedStyle(document.body).backgroundColor"),
  223. "rgb(23, 25, 28)",
  224. );
  225. assert.match(await read("connection"), /已连接/);
  226. assert.match(await read("case-detail"), /SC35/);
  227. assert.match(await read("sampling-capability"), /宿主声明/);
  228. assert.equal(await read("boot-id"), boot);
  229. assert.equal(
  230. await page("document.documentElement.scrollWidth <= window.innerWidth"),
  231. true,
  232. );
  233. await writeFile(
  234. join(root, "showcase-dark-320.png"),
  235. (await win.webContents.capturePage()).toPNG(),
  236. );
  237. await ui("window.setShowcasePresentation('light','en-US',400)");
  238. },
  239. );
  240. await check(
  241. "real model discovers page tool, completes on click and cancels without changing the note",
  242. async () => {
  243. const command = (type: string, payload: unknown) =>
  244. env.agent.call("v4/command", {
  245. commandId: randomUUID(),
  246. clientId: "showcase-e2e",
  247. sessionId: scope.sessionId,
  248. type,
  249. payload,
  250. issuedAt: Date.now(),
  251. });
  252. for (const cancel of [false, true]) {
  253. const key = cancel ? "showcase-page-cancel" : "showcase-page-complete";
  254. const after = env.agent.notifications.history.length;
  255. env.model.plans.push({ key, delayed: true });
  256. const ack = await command("sendText", {
  257. text: key,
  258. modelSelection: env.model.selection,
  259. mode: "build",
  260. });
  261. assert.equal(ack.status, "accepted");
  262. await phase("page-tool-status", "running");
  263. if (cancel) {
  264. await command("stop", {});
  265. await phase("page-tool-status", "cancelled");
  266. } else {
  267. await click("page-tool-finish");
  268. await phase("page-tool-status", "complete");
  269. }
  270. await env.agent.notifications.wait(
  271. (event) =>
  272. event.method === "v4/telemetry/event" &&
  273. event.params.kind === "turn.terminal" &&
  274. event.params.sessionId === scope.sessionId,
  275. after,
  276. );
  277. assert.equal(await read("page-note"), "showcase-page-complete");
  278. }
  279. },
  280. );
  281. await check(
  282. "legacy dashboard still handshakes and its real refresh button renders four services",
  283. async () => {
  284. const legacy = await env.createWindow(
  285. { ...scope, resourceUri: "ui://showcase/dashboard.html" },
  286. "sampling",
  287. );
  288. await env.evalPage(legacy, "window.zcode.ready()");
  289. await env.evalPage(
  290. legacy,
  291. `document.getElementById('refresh').click(); new Promise(resolve => {
  292. const rows=document.getElementById('rows');const check=()=>{if(rows.children.length===4){observer.disconnect();resolve(true)}};
  293. const observer=new MutationObserver(check);observer.observe(rows,{childList:true});check();
  294. })`,
  295. );
  296. assert.equal(
  297. await env.evalPage(legacy, "document.querySelectorAll('#rows tr').length"),
  298. 4,
  299. );
  300. assert.equal(await env.evalPage(legacy, "typeof window.openai.callTool"), "function");
  301. await env.evalPage(
  302. legacy,
  303. "new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))",
  304. );
  305. await writeFile(
  306. join(root, "showcase-legacy.png"),
  307. (await legacy.webContents.capturePage()).toPNG(),
  308. );
  309. },
  310. );
  311. await writeFile(
  312. join(root, "showcase-lab.png"),
  313. (await win.webContents.capturePage()).toPNG(),
  314. );
  315. await writeFile(
  316. join(root, "showcase-results.json"),
  317. JSON.stringify(
  318. {
  319. checks,
  320. modelRequests: env.model.requests.history.length,
  321. approvals: env.agent.approvals.history.length,
  322. },
  323. null,
  324. 2,
  325. ),
  326. );
  327. } finally {
  328. await env.close();
  329. }
  330. app.exit(0);
  331. })
  332. .catch((error) => {
  333. process.stderr.write(String(error.stack ?? error) + "\n");
  334. app.exit(1);
  335. });