conversation-session-model-trajectory-viewer.test.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. import { appendFile, mkdir, open, readFile } from "node:fs/promises";
  2. import { basename, join } from "node:path";
  3. import {
  4. clearAppData,
  5. getE2EAppDataPaths,
  6. setCurrentElectronRendererContentSize,
  7. } from "../helpers/desktop-app.js";
  8. import {
  9. getV4PaneSnapshot,
  10. prepareV4ConversationE2E,
  11. sendV4Prompt,
  12. waitForV4Pane,
  13. waitForV4TimelineContaining,
  14. } from "../helpers/v4-conversation.js";
  15. const paths = getE2EAppDataPaths();
  16. const LONG_MARKER = "E2E_TRJ07_VIRTUAL_FOLDED_TARGET";
  17. const SEARCH_MARKER = "E2E_TRJ06_SHARED_MATCH";
  18. const DELTA_MARKER = "E2E_TRJ02_DELTA_USER";
  19. const RECENT_TAIL_MARKER = "E2E_TRJ09_RECENT_TAIL";
  20. type ActualTrajectoryRecord = {
  21. type?: string;
  22. sessionId?: string;
  23. response?: { text?: string; reasoningText?: string };
  24. };
  25. describe("模型调用轨迹查看器 E2E", () => {
  26. after(async () => {
  27. await browser.electron.restoreAllMocks();
  28. await clearAppData();
  29. });
  30. it("TRJ01-TRJ09: 写入、投影、交互、虚拟搜索、窄布局与有界尾读", async function () {
  31. this.timeout(240_000);
  32. await prepareV4ConversationE2E();
  33. await setRendererLocale("zh-CN");
  34. await sendV4Prompt("E2E_TRJ_TASK_SEED reply with E2E_TRJ_TASK_READY");
  35. await waitForV4TimelineContaining("E2E_TRJ_TASK_READY", 45_000);
  36. await waitForV4Pane(
  37. (snapshot) => snapshot.sessionId !== null && snapshot.sessionId !== "draft",
  38. "trajectory case 没有建立真实 task/session",
  39. 45_000,
  40. );
  41. const taskId = (await getV4PaneSnapshot()).sessionId as string;
  42. const actualTrajectoryFile = await waitForActualTrajectory(taskId);
  43. expect(
  44. actualTrajectoryFile.records.some((record) => record.response?.text === "E2E_TRJ_TASK_READY"),
  45. ).toBe(true);
  46. expect(
  47. actualTrajectoryFile.records.some(
  48. (record) => record.response?.reasoningText === "E2E_TRJ_ACTUAL_REASONING",
  49. ),
  50. ).toBe(true);
  51. await seedTrajectory(taskId, actualTrajectoryFile.filePath);
  52. await seedUnreadableTrajectoryCandidate(actualTrajectoryFile.filePath);
  53. await openTrajectoryThroughTaskMenu(taskId);
  54. await waitForTrajectory();
  55. const initial = await trajectorySnapshot();
  56. expect(initial.callCount).toBeLessThan(90);
  57. expect(initial.callCount).toBeGreaterThan(0);
  58. expect(initial.expandedCount).toBeGreaterThanOrEqual(6);
  59. expect(initial.copyCount).toBeGreaterThan(0);
  60. expect(initial.sourceKinds).toContain("main");
  61. expect(initial.querySources).toContain("main_turn");
  62. expect(initial.finishReasons).toEqual(
  63. expect.arrayContaining(["length", "content-filter", "tool-calls"]),
  64. );
  65. expect(initial.expandedRoles).toEqual(
  66. expect.arrayContaining([
  67. "system",
  68. "user",
  69. "reasoning",
  70. "assistant",
  71. "tool-call",
  72. "tool-result",
  73. ]),
  74. );
  75. expect(initial.text).toContain("主会话");
  76. expect(initial.text).toContain("系统提示词");
  77. expect(initial.text).toContain("用户消息");
  78. expect(initial.text).toContain("思考过程");
  79. expect(initial.text).toContain("助手消息");
  80. expect(initial.text).toContain("工具调用");
  81. expect(initial.text).toContain("工具结果");
  82. expect(initial.text).toContain("mcp__computer-use__open_application_with_full_name");
  83. expect(initial.text).toContain("e2e_trj_0");
  84. expect(initial.text).toContain(DELTA_MARKER);
  85. expect(initial.text).not.toContain("E2E_TRJ02_OLD_ASSISTANT_INPUT");
  86. expect(initial.text).toContain("E2E_TRJ02_ERROR_VALUE");
  87. expect(initial.errorIconCount).toBeGreaterThan(0);
  88. expect(initial.callErrorCount).toBeGreaterThan(0);
  89. expect(initial.text).toContain("达到长度限制");
  90. expect(initial.text).toContain("内容过滤");
  91. expect(initial.text).toContain("custom-e2e-finish");
  92. expect(initial.text).toContain("1.25s");
  93. // TRJ02:错误投影和工具元数据必须从真实 host 文件读取链路进入 UI。
  94. // 首屏同时包含 full→delta 与错误 payload,能直接区分“仅写 fixture”与 UI 投影成功。
  95. // TRJ03:默认展开;点击整行收起再恢复,复制按钮只在展开态存在,原始换行保留。
  96. const beforeCollapse = await trajectoryRoleRowSnapshot("system");
  97. expect(beforeCollapse.state).toBe("open");
  98. expect(beforeCollapse.copyVisible).toBe(true);
  99. await installClipboardCapture();
  100. await clickFirst(
  101. '[data-trajectory-expandable-role="system"] [data-trajectory-message-copy=""]',
  102. );
  103. await browser.waitUntil(
  104. () =>
  105. browser.execute(() =>
  106. (
  107. (window as unknown as { __e2eTrajectoryClipboard?: string }).__e2eTrajectoryClipboard ??
  108. ""
  109. ).includes("SYSTEM LINE 2"),
  110. ),
  111. {
  112. timeout: 10_000,
  113. timeoutMsg: "展开态复制没有写入完整 system 正文",
  114. },
  115. );
  116. await clickFirst(
  117. '[data-trajectory-expandable-role="system"] [data-trajectory-message-trigger=""]',
  118. );
  119. const collapsed = await trajectoryRoleRowSnapshot("system");
  120. expect(collapsed.state).toBe("closed");
  121. expect(collapsed.copyVisible).toBe(false);
  122. await clickFirst(
  123. '[data-trajectory-expandable-role="system"] [data-trajectory-message-trigger=""]',
  124. );
  125. const reexpanded = await trajectoryRoleRowSnapshot("system");
  126. expect(reexpanded.state).toBe("open");
  127. expect(reexpanded.copyVisible).toBe(true);
  128. expect(reexpanded.hasOverflowToggle).toBe(true);
  129. expect(reexpanded.text).toMatch(/SYSTEM LINE 1[\s\S]*SYSTEM LINE 2/);
  130. const overflowLabel = await firstText('[data-trajectory-overflow-toggle=""]');
  131. await clickFirst('[data-trajectory-overflow-toggle=""]');
  132. await browser.waitUntil(
  133. async () => (await firstText('[data-trajectory-overflow-toggle=""]')) !== overflowLabel,
  134. { timeout: 10_000, timeoutMsg: "超长正文没有切换为完整展开态" },
  135. );
  136. await clickFirst('[data-trajectory-overflow-toggle=""]');
  137. // TRJ04:全局命令直接派生收起状态;自定义菜单分别只打开 reasoning/tool-result。
  138. await clickFirst('[data-trajectory-toggle-all=""]');
  139. await browser.waitUntil(async () => (await trajectorySnapshot()).expandedCount === 0, {
  140. timeout: 10_000,
  141. timeoutMsg: "全部收起没有覆盖六类内容",
  142. });
  143. await waitForToggleAllAction(["Expand all", "全部展开"]);
  144. await clickNative('[data-trajectory-custom-expansion=""]');
  145. await clickNative('[data-trajectory-expansion-kind="reasoning"]');
  146. await clickNative('[data-trajectory-expansion-kind="tool-result"]');
  147. await browser.keys("Escape");
  148. await browser.waitUntil(
  149. async () => {
  150. const roles = (await trajectorySnapshot()).expandedRoles;
  151. return (
  152. roles.includes("reasoning") &&
  153. roles.includes("tool-result") &&
  154. roles.every((role) => role === "reasoning" || role === "tool-result")
  155. );
  156. },
  157. { timeout: 10_000, timeoutMsg: "自定义展开没有只展开 reasoning 与 tool-result" },
  158. );
  159. // TRJ05:长列表只挂载窗口附近行;用户 override 跨真实虚拟卸载/重挂载保持。
  160. const virtual = await trajectorySnapshot();
  161. expect(virtual.callCount).toBeLessThan(80);
  162. expect(virtual.virtualRowCount).toBeLessThan(80);
  163. await verifyVirtualizedExpansionPersistence(42);
  164. // TRJ06:多匹配导航更新活动索引,清空后搜索栏关闭。
  165. await searchAndNavigate(SEARCH_MARKER);
  166. const firstSearch = await searchSnapshot();
  167. expect(firstSearch.counter).toMatch(/1\s*\/\s*2/);
  168. await waitForSearchHighlights(1, 1);
  169. await browser.keys("Enter");
  170. await browser.waitUntil(
  171. async () => (await searchSnapshot()).counter?.match(/2\s*\/\s*2/) != null,
  172. {
  173. timeout: 10_000,
  174. timeoutMsg: "下一个搜索结果没有更新活动索引",
  175. },
  176. );
  177. await browser.keys(["Shift", "Enter"]);
  178. await browser.waitUntil(
  179. async () => (await searchSnapshot()).counter?.match(/1\s*\/\s*2/) != null,
  180. {
  181. timeout: 10_000,
  182. timeoutMsg: "上一个搜索结果没有更新活动索引",
  183. },
  184. );
  185. await waitForSearchHighlights(1, 1);
  186. await setSearchValue("E2E_TRJ06_NO_MATCH");
  187. await browser.waitUntil(
  188. async () => (await searchSnapshot()).counter?.match(/0\s*\/\s*0/) != null,
  189. {
  190. timeout: 10_000,
  191. timeoutMsg: "无结果搜索没有归零计数器",
  192. },
  193. );
  194. await browser.keys("Escape");
  195. await browser.waitUntil(async () => !(await searchHighlightSnapshot()).registered, {
  196. timeout: 10_000,
  197. timeoutMsg: "关闭搜索后 CSS highlight registry 没有清空",
  198. });
  199. // TRJ07:虚拟窗口外、折叠正文中的唯一命中会自动挂载并展开。
  200. await searchAndNavigate(LONG_MARKER);
  201. await browser.waitUntil(
  202. async () => {
  203. const snapshot = await trajectorySnapshot();
  204. return snapshot.expandedText.includes(LONG_MARKER);
  205. },
  206. { timeout: 15_000, timeoutMsg: "虚拟窗口外的折叠命中没有自动展开并定位" },
  207. );
  208. // TRJ08:窄视口中共享操作列不横跳,完整 tool name 仍存在于 DOM。
  209. await setCurrentElectronRendererContentSize(760, 720);
  210. const narrow = await trajectorySnapshot();
  211. expect(narrow.text).toContain("mcp__computer-use__open_application_with_full_name");
  212. expect(narrow.pageHorizontalOverflow).toBe(false);
  213. expect(narrow.chevronRightEdgeDelta).toBeLessThanOrEqual(2);
  214. // TRJ09:稀疏扩展到 33 MiB 后只读取尾部完整记录,并显式呈现 truncated。
  215. await seedOversizedTrajectoryTail(actualTrajectoryFile.filePath, taskId);
  216. await clickFirst('[aria-label="Refresh"], [aria-label="刷新"]');
  217. await browser.waitUntil(
  218. async () => {
  219. const snapshot = await trajectorySnapshot();
  220. return snapshot.text.includes(RECENT_TAIL_MARKER) && snapshot.truncatedNoticeCount === 1;
  221. },
  222. { timeout: 20_000, timeoutMsg: "有界尾部读取没有保留 recent record 或 truncated 提示" },
  223. );
  224. });
  225. });
  226. async function seedTrajectory(taskId: string, filePath: string) {
  227. const safeTaskId = taskId
  228. .replace(/[^a-zA-Z0-9_-]+/g, "-")
  229. .replace(/^-+|-+$/g, "")
  230. .slice(0, 80);
  231. const records = Array.from({ length: 80 }, (_, index) => createRecord(taskId, index));
  232. expect(filePath.endsWith(`model-io-${safeTaskId || "no-session"}.jsonl`)).toBe(true);
  233. await appendFile(
  234. filePath,
  235. `${records.map((record) => JSON.stringify(record)).join("\n")}\n`,
  236. "utf8",
  237. );
  238. }
  239. async function seedUnreadableTrajectoryCandidate(actualFilePath: string) {
  240. const otherMode = actualFilePath.includes("/debug/") ? "rollout" : "debug";
  241. await mkdir(join(paths.storageRoot, "cli", otherMode, basename(actualFilePath)), {
  242. recursive: true,
  243. });
  244. }
  245. async function waitForActualTrajectory(taskId: string): Promise<{
  246. filePath: string;
  247. records: ActualTrajectoryRecord[];
  248. }> {
  249. const safeTaskId = taskId
  250. .replace(/[^a-zA-Z0-9_-]+/g, "-")
  251. .replace(/^-+|-+$/g, "")
  252. .slice(0, 80);
  253. const fileName = `model-io-${safeTaskId || "no-session"}.jsonl`;
  254. const candidates = ["debug", "rollout"].map((mode) =>
  255. join(paths.storageRoot, "cli", mode, fileName),
  256. );
  257. let result: { filePath: string; records: ActualTrajectoryRecord[] } | null = null;
  258. await browser.waitUntil(
  259. async () => {
  260. for (const filePath of candidates) {
  261. const records = await readTrajectoryRecords(filePath, taskId);
  262. if (
  263. records.some(
  264. (record) =>
  265. record.response?.text === "E2E_TRJ_TASK_READY" &&
  266. record.response?.reasoningText === "E2E_TRJ_ACTUAL_REASONING",
  267. )
  268. ) {
  269. result = { filePath, records };
  270. return true;
  271. }
  272. }
  273. return false;
  274. },
  275. { timeout: 20_000, timeoutMsg: "CLI 没有写出包含 reasoningText 的真实 model-io" },
  276. );
  277. return result as NonNullable<typeof result>;
  278. }
  279. async function readTrajectoryRecords(filePath: string, taskId: string) {
  280. let text: string;
  281. try {
  282. text = await readFile(filePath, "utf8");
  283. } catch {
  284. return [];
  285. }
  286. return text
  287. .split("\n")
  288. .map((line) => line.trim())
  289. .filter(Boolean)
  290. .flatMap((line) => {
  291. try {
  292. return [JSON.parse(line) as ActualTrajectoryRecord];
  293. } catch {
  294. return [];
  295. }
  296. })
  297. .filter((record) => record.type === "model_io" && record.sessionId === taskId);
  298. }
  299. function createRecord(taskId: string, index: number) {
  300. const callId = `call_e2e_trj_${index}`;
  301. const userContent =
  302. index === 55
  303. ? `folded prefix\n${LONG_MARKER}\nfolded suffix`
  304. : index === 1 || index === 42
  305. ? `user ${SEARCH_MARKER} ${index}`
  306. : `user message ${index}`;
  307. const request =
  308. index === 3
  309. ? {
  310. messagesKind: "full",
  311. messageOffset: 0,
  312. messageCount: 1,
  313. messages: [{ role: "user", content: "E2E_TRJ02_DELTA_BASELINE" }],
  314. toolNames: ["mcp__computer-use__open_application_with_full_name"],
  315. }
  316. : index === 4
  317. ? {
  318. messagesKind: "delta",
  319. messageOffset: 1,
  320. messageCount: 3,
  321. messages: [
  322. { role: "assistant", content: "E2E_TRJ02_OLD_ASSISTANT_INPUT" },
  323. { role: "user", content: DELTA_MARKER },
  324. ],
  325. toolNames: ["mcp__computer-use__open_application_with_full_name"],
  326. }
  327. : {
  328. messages:
  329. index === 0
  330. ? [
  331. {
  332. role: "system",
  333. content: `SYSTEM LINE 1\n${"overflow content line\n".repeat(80)}SYSTEM LINE 2`,
  334. },
  335. { role: "user", content: userContent },
  336. {
  337. role: "tool",
  338. content: `tool output ${index}`,
  339. toolCallId: callId,
  340. toolName: "mcp__computer-use__open_application_with_full_name",
  341. },
  342. ]
  343. : index === 2
  344. ? [
  345. { role: "user", content: userContent },
  346. {
  347. role: "tool",
  348. content: "E2E_TRJ02_ERROR_VALUE\nstack line",
  349. toolCallId: callId,
  350. toolName: "mcp__computer-use__open_application_with_full_name",
  351. isError: true,
  352. },
  353. ]
  354. : [
  355. {
  356. role: "user",
  357. content: index === 1 ? [{ type: "text", text: userContent }] : userContent,
  358. },
  359. ],
  360. toolNames: ["mcp__computer-use__open_application_with_full_name"],
  361. };
  362. return {
  363. type: "model_io",
  364. sessionId: taskId,
  365. requestId: `e2e-trj-request-${String(index).padStart(3, "0")}`,
  366. querySource: index === 42 || index === 55 ? "prompt_enhance" : "main_turn",
  367. attempt: index === 2 ? 2 : 1,
  368. startedAt: new Date(Date.UTC(2026, 7, 24, 2, 0, index)).toISOString(),
  369. completedAt: new Date(Date.UTC(2026, 7, 24, 2, 0, index, 250)).toISOString(),
  370. durationMs: index === 0 ? 1250 : 250 + index,
  371. model: { modelId: "e2e-trajectory-model", providerId: "e2e-provider" },
  372. request,
  373. response: {
  374. reasoningText: `reasoning ${index}\nsecond reasoning line`,
  375. text: `assistant message ${index}`,
  376. finishReason:
  377. index === 0
  378. ? "length"
  379. : index === 1
  380. ? "content-filter"
  381. : index === 2
  382. ? "custom-e2e-finish"
  383. : "tool-calls",
  384. usage: { inputTokens: 1000 + index, outputTokens: 20 + index },
  385. toolCalls: [
  386. {
  387. toolCallId: callId,
  388. toolName: "mcp__computer-use__open_application_with_full_name",
  389. input: { app: "Maps", index },
  390. },
  391. ],
  392. },
  393. error:
  394. index === 2
  395. ? { name: "ProviderError", message: "E2E_TRJ02_RECORD_ERROR", stack: "stack:2:1" }
  396. : undefined,
  397. };
  398. }
  399. async function openTrajectoryThroughTaskMenu(taskId: string) {
  400. await browser.waitUntil(
  401. () =>
  402. browser.execute((currentTaskId) => {
  403. const item = [...document.querySelectorAll<HTMLElement>("[data-testid]")].find((element) =>
  404. element.getAttribute("data-testid")?.endsWith(currentTaskId),
  405. );
  406. if (!item) return false;
  407. const rect = item.getBoundingClientRect();
  408. item.dispatchEvent(
  409. new MouseEvent("contextmenu", {
  410. bubbles: true,
  411. cancelable: true,
  412. button: 2,
  413. clientX: rect.left + rect.width / 2,
  414. clientY: rect.top + rect.height / 2,
  415. }),
  416. );
  417. return true;
  418. }, taskId),
  419. { timeout: 15_000, timeoutMsg: `侧栏中没有找到真实 task item: ${taskId}` },
  420. );
  421. await browser.waitUntil(
  422. () =>
  423. browser.execute(() => {
  424. const labels = new Set(["View model trajectory", "查看调用轨迹"]);
  425. const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
  426. (element) => labels.has((element.textContent ?? "").trim()),
  427. );
  428. item?.click();
  429. return Boolean(item);
  430. }),
  431. { timeout: 15_000, timeoutMsg: "task context menu 没有调用轨迹入口" },
  432. );
  433. }
  434. async function verifyVirtualizedExpansionPersistence(index: number) {
  435. let targetKey: string | null = null;
  436. let targetScrollTop = 0;
  437. await browser.waitUntil(
  438. async () => {
  439. const result = await browser.execute((targetIndex) => {
  440. const root = document.querySelector<HTMLElement>('[data-trajectory-timeline=""]');
  441. const scroller = root?.parentElement;
  442. if (!root || !scroller) return null;
  443. const resolvedIndex = Number(targetIndex);
  444. scroller.scrollTop = (scroller.scrollHeight * resolvedIndex) / 80;
  445. const row = root.querySelector<HTMLElement>(`[data-index="${resolvedIndex}"]`);
  446. const message = row?.querySelector<HTMLElement>('[data-trajectory-expandable-role="user"]');
  447. const trigger = message?.querySelector<HTMLElement>('[data-trajectory-message-trigger=""]');
  448. if (!message || !trigger) return null;
  449. trigger.click();
  450. return {
  451. key: message.dataset.trajectorySearchTargetKey ?? null,
  452. scrollTop: scroller.scrollTop,
  453. };
  454. }, index);
  455. if (!result?.key) return false;
  456. targetKey = result.key;
  457. targetScrollTop = result.scrollTop;
  458. return true;
  459. },
  460. { timeout: 15_000, timeoutMsg: `虚拟列表没有挂载第 ${index} 条调用` },
  461. );
  462. await browser.waitUntil(
  463. () =>
  464. browser.execute((key) => {
  465. const target = [
  466. ...document.querySelectorAll<HTMLElement>("[data-trajectory-search-target-key]"),
  467. ].find((element) => element.dataset.trajectorySearchTargetKey === key);
  468. return target?.dataset.state === "open";
  469. }, targetKey),
  470. { timeout: 10_000, timeoutMsg: "目标 user row 没有记录展开 override" },
  471. );
  472. await browser.execute(() => {
  473. const root = document.querySelector<HTMLElement>('[data-trajectory-timeline=""]');
  474. if (root?.parentElement) root.parentElement.scrollTop = 0;
  475. });
  476. await browser.waitUntil(
  477. () =>
  478. browser.execute(
  479. (key) =>
  480. ![...document.querySelectorAll<HTMLElement>("[data-trajectory-search-target-key]")].some(
  481. (element) => element.dataset.trajectorySearchTargetKey === key,
  482. ),
  483. targetKey,
  484. ),
  485. { timeout: 10_000, timeoutMsg: "目标 user row 没有离开虚拟挂载窗口" },
  486. );
  487. await browser.execute((scrollTop) => {
  488. const root = document.querySelector<HTMLElement>('[data-trajectory-timeline=""]');
  489. if (root?.parentElement) root.parentElement.scrollTop = scrollTop;
  490. }, targetScrollTop);
  491. await browser.waitUntil(
  492. () =>
  493. browser.execute((key) => {
  494. const target = [
  495. ...document.querySelectorAll<HTMLElement>("[data-trajectory-search-target-key]"),
  496. ].find((element) => element.dataset.trajectorySearchTargetKey === key);
  497. return target?.dataset.state === "open";
  498. }, targetKey),
  499. { timeout: 15_000, timeoutMsg: "虚拟重挂载后 user row 展开 override 丢失" },
  500. );
  501. }
  502. async function waitForTrajectory() {
  503. await browser.waitUntil(
  504. () => browser.execute(() => Boolean(document.querySelector('[data-trajectory-timeline=""]'))),
  505. { timeout: 20_000, timeoutMsg: "调用轨迹 timeline 没有渲染" },
  506. );
  507. }
  508. async function clickFirst(selector: string) {
  509. await browser.waitUntil(
  510. () =>
  511. browser.execute((value) => {
  512. const element = document.querySelector<HTMLElement>(value);
  513. element?.click();
  514. return Boolean(element);
  515. }, selector),
  516. { timeout: 10_000, timeoutMsg: `没有找到可点击元素: ${selector}` },
  517. );
  518. }
  519. async function firstText(selector: string) {
  520. return browser.execute(
  521. (value) => document.querySelector<HTMLElement>(value)?.textContent ?? "",
  522. selector,
  523. );
  524. }
  525. async function installClipboardCapture() {
  526. await browser.execute(() => {
  527. const target = window as unknown as { __e2eTrajectoryClipboard?: string };
  528. target.__e2eTrajectoryClipboard = "";
  529. Object.defineProperty(navigator, "clipboard", {
  530. configurable: true,
  531. value: {
  532. writeText: async (text: string) => {
  533. target.__e2eTrajectoryClipboard = text;
  534. },
  535. },
  536. });
  537. });
  538. }
  539. async function clickNative(selector: string) {
  540. const element = $(selector);
  541. await element.waitForDisplayed({ timeout: 10_000 });
  542. await element.click();
  543. }
  544. async function waitForToggleAllAction(labels: string[]) {
  545. await browser.waitUntil(
  546. () =>
  547. browser.execute((expectedLabels) => {
  548. const button = document.querySelector<HTMLElement>('[data-trajectory-toggle-all=""]');
  549. return expectedLabels.includes(button?.getAttribute("aria-label") ?? "");
  550. }, labels),
  551. { timeout: 10_000, timeoutMsg: `批量按钮没有切换为 ${labels.join("/")}` },
  552. );
  553. }
  554. async function searchAndNavigate(query: string) {
  555. const hasSearchBar = await browser.execute(() =>
  556. Boolean(document.querySelector('[data-trajectory-search-bar=""]')),
  557. );
  558. if (!hasSearchBar) await clickFirst('[data-trajectory-search-trigger=""]');
  559. await setSearchValue(query);
  560. await browser.waitUntil(async () => (await trajectorySnapshot()).text.includes(query), {
  561. timeout: 15_000,
  562. timeoutMsg: `搜索命中没有被虚拟列表挂载并 reveal: ${query}`,
  563. });
  564. }
  565. async function setSearchValue(query: string) {
  566. await browser.waitUntil(
  567. () =>
  568. browser.execute(() =>
  569. Boolean(document.querySelector('[data-trajectory-search-bar=""] input')),
  570. ),
  571. { timeout: 10_000, timeoutMsg: "调用轨迹搜索框没有出现" },
  572. );
  573. const input = $('[data-trajectory-search-bar=""] input');
  574. await input.setValue(query);
  575. }
  576. async function waitForSearchHighlights(expectedNormal: number, expectedActive: number) {
  577. await browser.waitUntil(
  578. async () => {
  579. const snapshot = await searchHighlightSnapshot();
  580. return snapshot.normal === expectedNormal && snapshot.active === expectedActive;
  581. },
  582. {
  583. timeout: 10_000,
  584. timeoutMsg: `搜索高亮没有达到 normal=${expectedNormal} active=${expectedActive}`,
  585. },
  586. );
  587. }
  588. async function searchHighlightSnapshot() {
  589. return browser.execute(() => {
  590. const registry = (
  591. CSS as unknown as {
  592. highlights?: {
  593. get: (name: string) => { size?: number } | undefined;
  594. has: (name: string) => boolean;
  595. };
  596. }
  597. ).highlights;
  598. const normalName = "zcode-model-trajectory-find";
  599. const activeName = "zcode-model-trajectory-find-active";
  600. return {
  601. registered: Boolean(registry?.has(normalName) || registry?.has(activeName)),
  602. normal: registry?.get(normalName)?.size ?? 0,
  603. active: registry?.get(activeName)?.size ?? 0,
  604. };
  605. });
  606. }
  607. async function seedOversizedTrajectoryTail(filePath: string, taskId: string) {
  608. const handle = await open(filePath, "r+");
  609. try {
  610. await handle.truncate(33 * 1024 * 1024);
  611. } finally {
  612. await handle.close();
  613. }
  614. const recentRecord = {
  615. type: "model_io",
  616. sessionId: taskId,
  617. requestId: "e2e-trj-recent-tail",
  618. querySource: "main_turn",
  619. startedAt: "2026-08-27T12:00:00.000Z",
  620. completedAt: "2026-08-27T12:00:00.250Z",
  621. durationMs: 250,
  622. model: { modelId: "e2e-trajectory-model", providerId: "e2e-provider" },
  623. request: {
  624. messages: [{ role: "user", content: RECENT_TAIL_MARKER }],
  625. toolNames: [],
  626. },
  627. response: {
  628. text: `${RECENT_TAIL_MARKER}_RESPONSE`,
  629. finishReason: "stop",
  630. toolCalls: [],
  631. usage: { inputTokens: 1, outputTokens: 1 },
  632. },
  633. };
  634. await appendFile(filePath, `\n${JSON.stringify(recentRecord)}\n`, "utf8");
  635. }
  636. async function trajectorySnapshot() {
  637. return browser.execute(() => {
  638. const root = document.querySelector<HTMLElement>('[data-trajectory-timeline=""]');
  639. const expanded = Array.from(
  640. document.querySelectorAll<HTMLElement>(
  641. '[data-trajectory-message-expanded=""][data-state="open"]',
  642. ),
  643. );
  644. return {
  645. callCount: document.querySelectorAll('[data-trajectory-call=""]').length,
  646. virtualRowCount: document.querySelectorAll('[data-trajectory-virtual-row=""]').length,
  647. expandedCount: expanded.length,
  648. expandedRoles: Array.from(
  649. document.querySelectorAll<HTMLElement>(
  650. '[data-trajectory-message-collapsible=""][data-state="open"]',
  651. ),
  652. ).map((item) => item.dataset.trajectoryExpandableRole ?? ""),
  653. copyCount: document.querySelectorAll('[data-trajectory-message-copy=""]').length,
  654. overflowToggleCount: document.querySelectorAll('[data-trajectory-overflow-toggle=""]').length,
  655. errorIconCount: document.querySelectorAll('[data-trajectory-payload-error-icon=""]').length,
  656. callErrorCount: document.querySelectorAll('[data-trajectory-call-error=""]').length,
  657. sourceKinds: [...document.querySelectorAll<HTMLElement>("[data-trajectory-source-kind]")].map(
  658. (element) => element.dataset.trajectorySourceKind ?? "",
  659. ),
  660. querySources: [
  661. ...document.querySelectorAll<HTMLElement>("[data-trajectory-query-source]"),
  662. ].map((element) => element.dataset.trajectoryQuerySource ?? ""),
  663. finishReasons: [
  664. ...document.querySelectorAll<HTMLElement>("[data-trajectory-finish-reason]"),
  665. ].map((element) => element.dataset.trajectoryFinishReason ?? ""),
  666. truncatedNoticeCount: [...document.querySelectorAll<HTMLElement>("p")].filter((element) =>
  667. /Too many records|记录过多/.test(element.textContent ?? ""),
  668. ).length,
  669. text: root?.textContent ?? "",
  670. expandedText: expanded.map((item) => item.textContent ?? "").join("\n"),
  671. pageHorizontalOverflow:
  672. document.documentElement.scrollWidth > document.documentElement.clientWidth + 1,
  673. chevronRightEdgeDelta: (() => {
  674. const rightEdges = Array.from(
  675. document.querySelectorAll<HTMLElement>('[data-trajectory-message-chevron-trigger=""]'),
  676. (item) => item.getBoundingClientRect().right,
  677. );
  678. return rightEdges.length > 1 ? Math.max(...rightEdges) - Math.min(...rightEdges) : 0;
  679. })(),
  680. };
  681. });
  682. }
  683. async function setRendererLocale(locale: "zh-CN") {
  684. const changed = await browser.execute((nextLocale) => {
  685. const actions = (
  686. window as typeof window & {
  687. __testActions?: Record<string, unknown>;
  688. }
  689. ).__testActions;
  690. const setLocale = actions?.setLocale;
  691. if (typeof setLocale !== "function") return false;
  692. (setLocale as (value: string) => void)(nextLocale);
  693. return true;
  694. }, locale);
  695. if (!changed) {
  696. throw new Error(`TRJ01 缺少 renderer locale test action: ${locale}`);
  697. }
  698. await browser.waitUntil(
  699. async () =>
  700. browser.execute((expectedLocale) => {
  701. const actions = (
  702. window as typeof window & {
  703. __testActions?: Record<string, unknown>;
  704. }
  705. ).__testActions;
  706. const getLocale = actions?.getLocale;
  707. return typeof getLocale === "function" && getLocale() === expectedLocale;
  708. }, locale),
  709. { timeout: 15_000, timeoutMsg: `TRJ01 renderer locale 没有切换到 ${locale}` },
  710. );
  711. }
  712. async function trajectoryRoleRowSnapshot(role: string) {
  713. return browser.execute((targetRole) => {
  714. const row = document.querySelector<HTMLElement>(
  715. `[data-trajectory-expandable-role="${targetRole}"]`,
  716. );
  717. const copy = row?.querySelector<HTMLElement>('[data-trajectory-message-copy=""]');
  718. return {
  719. state: row?.dataset.state ?? null,
  720. copyVisible: Boolean(copy && window.getComputedStyle(copy).display !== "none"),
  721. hasOverflowToggle: Boolean(row?.querySelector('[data-trajectory-overflow-toggle=""]')),
  722. text: row?.textContent ?? "",
  723. };
  724. }, role);
  725. }
  726. async function searchSnapshot() {
  727. return browser.execute(() => {
  728. const bar = document.querySelector<HTMLElement>('[data-trajectory-search-bar=""]');
  729. const counter = Array.from(bar?.querySelectorAll<HTMLElement>("span") ?? []).find((item) =>
  730. /\d+\s*\/\s*\d+/.test(item.textContent ?? ""),
  731. );
  732. return { counter: counter?.textContent ?? null };
  733. });
  734. }