conversation-session-gen-ui-context.test.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. import { chromium, type Browser, type Page } from "playwright-core";
  2. import { TID_TASK_ITEM, testId } from "@zcode/shared/test-ids";
  3. import { obtainUnreadPairingUrl, showMobileTaskHome } from "#e2e/helpers/web-remote-unread";
  4. import { openMobilePairingPage } from "#e2e/helpers/mobile-pairing";
  5. import { WEB_REMOTE_CONTROL_FIXTURE_CREDENTIALS } from "#e2e/helpers/web-remote-control-session-events-fixture";
  6. import { copyFile, mkdir, rm } from "node:fs/promises";
  7. import { dirname, join, resolve } from "node:path";
  8. import { clearAppData } from "#e2e/helpers/desktop-app";
  9. import { resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  10. import {
  11. startUpstreamReplayServer,
  12. type UpstreamReplayServer,
  13. } from "#e2e/helpers/upstream-replay-server";
  14. import { seedCustomAnthropicMessagesProvider } from "#e2e/helpers/custom-openai-provider-store";
  15. import {
  16. seedTurboAgentStartupModel,
  17. restartIntoWorkspacePreservingProfile,
  18. } from "#e2e/helpers/model-provider-restart";
  19. import { UPSTREAM_MODEL, UPSTREAM_PROVIDER_ID } from "#e2e/helpers/upstream-provider";
  20. import {
  21. waitForUpstreamNetworkCapture,
  22. waitForUpstreamNetworkRequestStarted,
  23. } from "#e2e/helpers/upstream-capture";
  24. import { releaseControlledReplay } from "#e2e/helpers/controlled-replay";
  25. import { reloadElectronSessionSafely } from "#e2e/helpers/e2e-electron-reload";
  26. import {
  27. prepareV4ConversationE2E,
  28. sendV4Prompt,
  29. waitForV4Pane,
  30. getV4QueueItems,
  31. waitForV4TimelineContaining,
  32. selectV4TaskById,
  33. } from "#e2e/helpers/v4-conversation";
  34. const NAME = "conversation-session-gen-ui-context";
  35. const PAGE = join(resolveE2EStorageRoot(), "v2", "visualizations", "gen-ui-context.html");
  36. let server: UpstreamReplayServer;
  37. let mobileBrowser: Browser | undefined;
  38. let mobile: Page;
  39. describe("GUC Gen UI input context", () => {
  40. before(async () => {
  41. server = await startUpstreamReplayServer({
  42. artifactPath: resolve(
  43. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts",
  44. "gen-ui-provider.json",
  45. ),
  46. fixturePaths: [resolve(`test/e2e/fixtures/upstream/conversation-session/${NAME}.json`)],
  47. fixtureVariables: { genUiContextPath: PAGE.replaceAll("\\", "/") },
  48. });
  49. process.env.E2E_PROVIDER_CAPTURE_PATH = server.artifactPath;
  50. process.env.E2E_PROVIDER_CAPTURE_MODE = "replay";
  51. process.env.E2E_PROVIDER_RUNTIME_BASE_URL = server.baseUrl;
  52. process.env.E2E_PROVIDER_EXPECTED_HOST = new URL(server.baseUrl).host;
  53. process.env.E2E_PROVIDER_EXPECTED_PROTOCOL = "http";
  54. });
  55. after(async () => {
  56. await mobileBrowser?.close();
  57. await clearAppData();
  58. await server?.stop();
  59. await rm(PAGE, { force: true });
  60. });
  61. it("真实页面状态不进入队列正文,出队与冷恢复使用输入快照", async function () {
  62. this.timeout(360_000);
  63. await seedCustomAnthropicMessagesProvider({
  64. baseURL: server.baseUrl,
  65. modelId: UPSTREAM_MODEL,
  66. providerId: UPSTREAM_PROVIDER_ID,
  67. providerName: "Gen UI Context Fixture",
  68. });
  69. await seedTurboAgentStartupModel(UPSTREAM_PROVIDER_ID, UPSTREAM_MODEL);
  70. await restartIntoWorkspacePreservingProfile();
  71. await prepareV4ConversationE2E({ skipProvider: true });
  72. await mkdir(dirname(PAGE), { recursive: true });
  73. await copyFile(resolve(`test/e2e/fixtures/fs/conversation-session/${NAME}/context.html`), PAGE);
  74. await sendV4Prompt("E2E_GEN_UI_CREATE");
  75. await waitForV4Pane(
  76. (s) => !s.canStop && Boolean(s.sessionId && s.sessionId !== "draft"),
  77. "Gen UI fixture 未完成",
  78. );
  79. await browser.waitUntil(async () => await $('[data-gen-ui-phase="ready"]').isExisting(), {
  80. timeout: 30_000,
  81. timeoutMsg: "真实 Gen UI sandbox 未就绪",
  82. });
  83. const session = await waitForV4Pane((s) => Boolean(s.sessionId), "task identity unavailable");
  84. const pairingUrl = await obtainUnreadPairingUrl();
  85. mobileBrowser = await chromium.launch({ channel: "chrome", headless: true });
  86. const mobileContext = await mobileBrowser.newContext({
  87. viewport: { width: 390, height: 844 },
  88. isMobile: true,
  89. hasTouch: true,
  90. locale: "zh-CN",
  91. });
  92. await mobileContext.addInitScript((credentials) => {
  93. for (const [key, value] of Object.entries(credentials)) localStorage.setItem(key, value);
  94. }, WEB_REMOTE_CONTROL_FIXTURE_CREDENTIALS);
  95. mobile = await mobileContext.newPage();
  96. await openMobilePairingPage(mobile, pairingUrl, {
  97. artifactDir: process.env.ZCODE_E2E_ARTIFACT_DIR!,
  98. caseMarker: NAME,
  99. phase: "queue",
  100. readySelector: '[data-testid="sidebar"], [data-mobile-page="chat"]',
  101. });
  102. await showMobileTaskHome(mobile);
  103. for (const toggle of await mobile.getByTestId("virtual-project-toggle").all()) {
  104. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  105. }
  106. await mobile.getByTestId(testId(TID_TASK_ITEM, session.sessionId!)).first().click();
  107. await mobile.locator(`[data-session-id="${session.sessionId}"]`).waitFor();
  108. await clickPageState("entry", "GEN_UI_ENTRY");
  109. await sendV4Prompt("E2E_GEN_UI_HOLD");
  110. await waitForUpstreamNetworkRequestStarted("E2E_GEN_UI_HOLD");
  111. await clickPageState("queued", "GEN_UI_QUEUED");
  112. await sendV4Prompt("E2E_GEN_UI_QUEUE");
  113. await browser.waitUntil(async () => (await getV4QueueItems()).length === 1, {
  114. timeout: 15_000,
  115. timeoutMsg: "Gen UI 输入未进入真实 CLI 队列",
  116. });
  117. expect((await getV4QueueItems())[0]?.text).toContain("E2E_GEN_UI_QUEUE");
  118. const queueText = await browser.execute(() =>
  119. Array.from(document.querySelectorAll("li[data-queue-item-id]"))
  120. .map((el) => `${el.textContent} ${el.outerHTML}`)
  121. .join("\n"),
  122. );
  123. expect(queueText).not.toContain("untrusted_gen_ui_state");
  124. expect(queueText).not.toContain("GEN_UI_QUEUED");
  125. await browser.saveScreenshot(
  126. join(process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts", "gen-ui-queue.png"),
  127. );
  128. await mobile
  129. .locator("li[data-queue-item-id]")
  130. .filter({ hasText: "E2E_GEN_UI_QUEUE" })
  131. .waitFor();
  132. await assertMobileClean();
  133. await mobile.reload({ waitUntil: "domcontentloaded" });
  134. await mobile
  135. .locator("li[data-queue-item-id]")
  136. .filter({ hasText: "E2E_GEN_UI_QUEUE" })
  137. .waitFor();
  138. await assertMobileClean();
  139. await mobile.screenshot({
  140. path: join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "gen-ui-mobile-queue.png"),
  141. });
  142. await clickPageState("later", "GEN_UI_LATER");
  143. await releaseControlledReplay("gen-ui-hold");
  144. await waitForV4TimelineContaining("GEN_UI_QUEUE_OK");
  145. const pane = await waitForV4Pane((s) => !s.canStop, "Gen UI 队列未完成");
  146. expect(await getV4QueueItems()).toHaveLength(0);
  147. const queued = (await waitForUpstreamNetworkCapture("E2E_GEN_UI_QUEUE")).requestJson;
  148. assertRequest(queued, "E2E_GEN_UI_QUEUE");
  149. expect(JSON.stringify(queued)).toContain("GEN_UI_ENTRY");
  150. expect(JSON.stringify(queued).split("GEN_UI_QUEUED")).toHaveLength(2);
  151. expect(JSON.stringify(queued)).not.toContain("GEN_UI_LATER");
  152. await mobile.getByText("GEN_UI_QUEUE_OK", { exact: false }).first().waitFor();
  153. await assertMobileClean();
  154. await reloadElectronSessionSafely(browser);
  155. await selectV4TaskById(pane.sessionId!);
  156. await waitForV4TimelineContaining("E2E_GEN_UI_QUEUE");
  157. await sendV4Prompt("E2E_GEN_UI_COLD");
  158. await waitForV4TimelineContaining("GEN_UI_COLD_OK");
  159. const cold = (await waitForUpstreamNetworkCapture("E2E_GEN_UI_COLD")).requestJson;
  160. assertRequest(cold, "E2E_GEN_UI_COLD");
  161. expect(JSON.stringify(cold).split("GEN_UI_QUEUED")).toHaveLength(2);
  162. expect(await browser.execute(() => document.body.innerText)).not.toContain(
  163. "untrusted_gen_ui_state",
  164. );
  165. });
  166. });
  167. async function clickPageState(button: string, expected: string) {
  168. // 点击真实页面按钮,状态经生产 sandbox bridge 和 Host 落盘,不直接改会话投影。
  169. await readPage(`document.getElementById(${JSON.stringify(button)}).click()`);
  170. await browser.waitUntil(
  171. async () => (await readPage("document.body.dataset.saved")) === expected,
  172. { timeout: 15_000, timeoutMsg: "Gen UI widget state 未完成真实保存" },
  173. );
  174. }
  175. async function readPage(script: string) {
  176. const id = await browser.execute(() =>
  177. (
  178. document.querySelector("webview") as unknown as { getWebContentsId(): number }
  179. ).getWebContentsId(),
  180. );
  181. return browser.electron.execute(
  182. (electron, args) => {
  183. const guest = electron.webContents.fromId(args.id);
  184. const frame = guest?.mainFrame.frames.find((frame) => frame.url.includes("/instance/"));
  185. if (!frame) throw new Error("Gen UI sandbox frame unavailable");
  186. return frame.executeJavaScript(args.script);
  187. },
  188. { id, script },
  189. );
  190. }
  191. function assertRequest(request: unknown, prompt: string) {
  192. const messages = (request as { messages: Array<{ content: unknown }> }).messages;
  193. const blocks = messages.flatMap((m) =>
  194. Array.isArray(m.content) ? m.content : [{ type: "text", text: m.content }],
  195. );
  196. expect(blocks).toContainEqual(expect.objectContaining({ type: "text", text: prompt }));
  197. expect(JSON.stringify(request)).not.toContain("GEN_UI_PRIVATE_ONLY");
  198. }
  199. async function assertMobileClean() {
  200. const markup = await mobile.locator("body").innerHTML();
  201. expect(markup).not.toContain("untrusted_gen_ui_state");
  202. expect(markup).not.toContain("GEN_UI_QUEUED");
  203. }