session-details.test.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. import assert from "node:assert/strict";
  2. import { test } from "node:test";
  3. import { fileURLToPath } from "node:url";
  4. import { mkdir } from "node:fs/promises";
  5. import { join } from "node:path";
  6. import { createServer } from "vite";
  7. import react from "@vitejs/plugin-react";
  8. import tailwindcss from "@tailwindcss/vite";
  9. import { chromium } from "playwright-core";
  10. // 真实会话 renderer:验证单卡片、分区复制、状态更新和窄屏布局。
  11. test("session tools summary and details", { timeout: 240000 }, async () => {
  12. const root = fileURLToPath(new URL("../../../../../../", import.meta.url));
  13. const entry = "/packages/ui/test/browser/manual-review/pending/session-details.fixture.tsx";
  14. const artifacts = join(root, "packages/desktop/.e2e-artifacts/session-details");
  15. await mkdir(artifacts, { recursive: true });
  16. const server = await createServer({
  17. root,
  18. configFile: false,
  19. plugins: [
  20. {
  21. name: "session-details",
  22. configureServer(vite) {
  23. vite.middlewares.use(async (req, res, next) => {
  24. if (!req.url?.startsWith("/fixture?")) return next();
  25. res.setHeader("Content-Type", "text/html");
  26. res.end(
  27. await vite.transformIndexHtml(
  28. req.url,
  29. `<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1" /></head><body><div id="root"></div><script type="module" src="${entry}"></script></body></html>`,
  30. ),
  31. );
  32. });
  33. },
  34. },
  35. react(),
  36. tailwindcss(),
  37. ],
  38. resolve: { alias: { "@": join(root, "packages/ui/src") } },
  39. optimizeDeps: { entries: [entry.slice(1)] },
  40. server: { host: "127.0.0.1", port: 0, hmr: false },
  41. });
  42. let browser;
  43. try {
  44. await server.listen();
  45. browser = await chromium.launch(
  46. process.env.CHROME_EXECUTABLE_PATH
  47. ? { executablePath: process.env.CHROME_EXECUTABLE_PATH }
  48. : { channel: "chrome" },
  49. );
  50. // 使用生产序列化器生成超限结果,避免手写 envelope 掩盖协议变化。
  51. const { serializeOutput } = await server.ssrLoadModule(
  52. "/apps/zcode-cli/packages/core/src/tool/executor/result-serialization.ts",
  53. );
  54. const budgetCases = [];
  55. const largeText = "Large message\n".repeat(4000);
  56. const session = { kind: "app", sessionId: "example-session" };
  57. for (const name of ["ListSessions", "ReadSession", "SendToSession", "WaitSessions"]) {
  58. for (const persisted of [true, false]) {
  59. const result = await serializeOutput(
  60. {
  61. sessionId: "example",
  62. artifactStore: {
  63. writeToolResultArtifact: async () => {
  64. if (!persisted) throw new Error("Disk unavailable");
  65. return { path: "/tmp/session-output.json", uri: "file:///tmp/session-output.json" };
  66. },
  67. },
  68. },
  69. name === "ListSessions"
  70. ? { sessions: [{ session, title: largeText, status: "idle" }] }
  71. : name === "WaitSessions"
  72. ? {
  73. status: "timed_out",
  74. operations: [{ operation: { session }, status: "running", reason: largeText }],
  75. }
  76. : name === "SendToSession"
  77. ? { session, admission: "rejected", reason: largeText }
  78. : { view: "messages", session, messages: [{ role: "assistant", text: largeText }] },
  79. {
  80. metadata: { name },
  81. resultBudget: {
  82. maxInlineBytes: 32768,
  83. maxModelBytes: 32768,
  84. strategy: "artifact",
  85. preview: { direction: "head" },
  86. artifact: { enabled: true, retention: "session" },
  87. },
  88. },
  89. {},
  90. "example-call",
  91. new AbortController().signal,
  92. );
  93. assert.ok(result.originalBytes > 32768);
  94. assert.match(result.content, persisted ? /<persisted-output>/ : /Tool output truncated/);
  95. budgetCases.push({ id: `${name}-${persisted}`, name, output: result.content });
  96. }
  97. }
  98. const page = await browser.newPage();
  99. await page.addInitScript((cases) => {
  100. window.__sessionBudgetCases = cases;
  101. }, budgetCases);
  102. const errors = [];
  103. page.on("pageerror", (error) => {
  104. errors.push(String(error));
  105. process.stderr.write(`${error}\n`);
  106. });
  107. await page.addInitScript(() => {
  108. window.__copied = [];
  109. Object.defineProperty(navigator, "clipboard", {
  110. value: {
  111. writeText: async (text) => {
  112. if (window.__copyFail) throw new Error("Clipboard denied");
  113. window.__copied.push(text);
  114. },
  115. },
  116. });
  117. });
  118. for (const width of [390, 1200])
  119. for (const theme of ["light", "dark"])
  120. for (const locale of ["zh-CN", "en-US"]) {
  121. await page.setViewportSize({ width, height: 950 });
  122. await page.goto(`${server.resolvedUrls.local[0]}fixture?theme=${theme}&locale=${locale}`);
  123. for (const id of [
  124. "list",
  125. "read",
  126. "summary",
  127. "send",
  128. "rejected",
  129. "wait",
  130. "running",
  131. "failed",
  132. "stopped",
  133. "denied",
  134. "unknown",
  135. "legacy",
  136. "budget-live",
  137. "budget-legacy",
  138. ...budgetCases.map((row) => row.id),
  139. ]) {
  140. const row = page.locator(`[data-case="${id}"]`);
  141. await row.locator("svg.lucide-book-open-text").waitFor();
  142. await row.locator("[aria-expanded]").click();
  143. await row.locator("[data-session-details]").waitFor();
  144. }
  145. assert.equal(
  146. await page.locator('[data-case="other"] svg.lucide-book-open-text').count(),
  147. 0,
  148. );
  149. const en = locale === "en-US";
  150. assert.match(await page.locator('[data-case="list"]').innerText(), /Project analysis/);
  151. assert.match(
  152. await page.locator('[data-case="list"]').innerText(),
  153. en ? /Search coverage is incomplete/ : /搜索范围不完整/,
  154. );
  155. assert.match(
  156. await page.locator('[data-case="list"]').innerText(),
  157. en ? /More results available/ : /还有更多结果/,
  158. );
  159. assert.match(
  160. await page.locator('[data-case="send"]').innerText(),
  161. en ? /Queued/ : /已排队/,
  162. );
  163. assert.match(
  164. await page.locator('[data-case="rejected"]').innerText(),
  165. /Permission denied/,
  166. );
  167. assert.match(
  168. await page.locator('[data-case="wait"]').innerText(),
  169. en ? /Wait timed out/ : /等待超时/,
  170. );
  171. assert.match(await page.locator('[data-case="wait"]').innerText(), /Choose a target/);
  172. for (const id of ["failed", "stopped", "denied"])
  173. assert.ok(
  174. !(await page.locator(`[data-case="${id}"]`).innerText()).includes(
  175. en ? "Queued" : "已排队",
  176. ),
  177. );
  178. assert.match(
  179. await page.locator('[data-case="unknown"]').innerText(),
  180. en ? /Outcome unknown/ : /结果未知/,
  181. );
  182. assert.match(await page.locator('[data-case="legacy"]').innerText(), /\{broken JSON/);
  183. for (const row of budgetCases) {
  184. const item = page.locator(`[data-case="${row.id}"]`);
  185. const visible = await item.innerText();
  186. assert.ok(visible.includes(row.output), `${row.id}: original result preserved`);
  187. assert.ok(!visible.includes(en ? "No result available" : "暂无可展示结果"));
  188. assert.ok(!visible.includes(en ? "Pending" : "等待中"));
  189. await item
  190. .getByRole("button", { name: en ? "Copy Result" : "复制 结果", exact: true })
  191. .click();
  192. assert.equal(await page.evaluate(() => window.__copied.at(-1)), row.output);
  193. }
  194. const send = page.locator('[data-case="send"]');
  195. await send
  196. .getByRole("button", { name: en ? "Copy Message" : "复制 消息", exact: true })
  197. .click();
  198. assert.equal(await page.evaluate(() => window.__copied.at(-1)), "Please inspect reuse");
  199. const scroll = page.locator('[data-case="read"] [data-fallback-scroll]').nth(1);
  200. assert.ok(
  201. await scroll.evaluate(
  202. (el) => el.scrollHeight > el.clientHeight && el.clientHeight <= 240,
  203. ),
  204. );
  205. await page.getByTestId("complete").click();
  206. await page
  207. .locator('[data-case="running"] [data-session-details]')
  208. .getByText("Project analysis", { exact: true })
  209. .waitFor();
  210. const live = page.locator('[data-case="budget-live"] [data-session-details]');
  211. await live.getByText(budgetCases[0].output, { exact: true }).waitFor();
  212. assert.ok(
  213. (await page.locator('[data-case="budget-legacy"]').innerText()).includes(
  214. budgetCases[0].output,
  215. ),
  216. );
  217. await send.locator("[aria-expanded]").click();
  218. await send.locator("[data-session-details]").waitFor({ state: "hidden" });
  219. await send.locator("[aria-expanded]").click();
  220. await send.locator("[data-session-details]").waitFor();
  221. const text = await page.locator("main").innerText();
  222. for (const hidden of [
  223. "/private/internal-path",
  224. "internal-source",
  225. "private-command",
  226. "private-cursor",
  227. ])
  228. assert.ok(!text.includes(hidden));
  229. assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
  230. await page.locator('[data-case="list"]').scrollIntoViewIfNeeded();
  231. await page.screenshot({ path: join(artifacts, `${width}-${theme}-${locale}.png`) });
  232. await page.goto(
  233. `${server.resolvedUrls.local[0]}fixture?theme=${theme}&locale=${locale}&restored=1`,
  234. );
  235. const restored = page.locator('[data-case="budget-live"]');
  236. await restored.locator("[aria-expanded]").click();
  237. await restored.locator("[data-session-details]").waitFor();
  238. assert.ok((await restored.innerText()).includes(budgetCases[0].output));
  239. await restored.screenshot({
  240. path: join(artifacts, `large-result-${width}-${theme}-${locale}.png`),
  241. });
  242. }
  243. assert.deepEqual(errors, []);
  244. } finally {
  245. await browser?.close();
  246. await server.close();
  247. }
  248. });