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

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