conversation-session-ttft-diagnostics.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. import { startDraftFromProject } from "#e2e/helpers/project-sidebar";
  2. import { ttftReceiverUrl } from "#e2e/helpers/ttft-otlp-fixture";
  3. import { mkdir, readFile, writeFile, rm } from "node:fs/promises";
  4. import { dirname, join } from "node:path";
  5. import {
  6. TID_V4_COMPOSER_KEEP_QUEUE_SEND,
  7. TID_TASK_SETTINGS_BUTTON,
  8. TID_SETTINGS_SECTION_NAV,
  9. TID_SETTINGS_BACK_BUTTON,
  10. testId,
  11. } from "@zcode/shared/test-ids";
  12. import {
  13. DEFAULT_WORKSPACE,
  14. clickTestIdByDom,
  15. readSettings,
  16. waitForWorkspaceApp,
  17. } from "#e2e/helpers/desktop-app";
  18. import { resolveE2ERuntimePath } from "#e2e/helpers/e2e-runtime-paths";
  19. import {
  20. waitForV4PausedQueueSendDialog,
  21. clickV4QueueItemSendNow,
  22. } from "#e2e/helpers/v4-conversation";
  23. import {
  24. prepareV4ConversationE2E,
  25. sendV4Prompt,
  26. waitForV4AssistantMessageContaining,
  27. waitForV4ConversationState,
  28. getV4QueueItems,
  29. waitForV4QueueCount,
  30. clickV4Stop,
  31. } from "#e2e/helpers/v4-conversation";
  32. type Span = {
  33. name: string;
  34. traceId: string;
  35. spanId: string;
  36. startTimeUnixNano: string;
  37. endTimeUnixNano: string;
  38. attributes: Array<{
  39. key: string;
  40. value: { stringValue?: string; doubleValue?: number; intValue?: string };
  41. }>;
  42. };
  43. async function spans(): Promise<Span[]> {
  44. const response = await fetch(ttftReceiverUrl("/records"));
  45. const records = (await response.json()) as Array<{
  46. data: { resourceSpans?: Array<{ scopeSpans: Array<{ spans: Span[] }> }> };
  47. }>;
  48. return records
  49. .flatMap((record) => record.data.resourceSpans ?? [])
  50. .flatMap((resource) => resource.scopeSpans)
  51. .flatMap((scope) => scope.spans);
  52. }
  53. const attr = (span: Span, key: string) =>
  54. span.attributes.find((item) => item.key === key)?.value.stringValue;
  55. const ms = (span: Span) =>
  56. Number(BigInt(span.endTimeUnixNano) - BigInt(span.startTimeUnixNano)) / 1e6;
  57. async function waitRoot(count: number) {
  58. await browser.waitUntil(
  59. async () => (await spans()).filter((span) => span.name === "local_ttft").length >= count,
  60. { timeout: 30000, timeoutMsg: "最终 OTLP 根记录未到达" },
  61. );
  62. }
  63. // Electron bridge 移除第一个形参;形参解构会静默 ReferenceError,必须在函数体内解构。
  64. async function focus() {
  65. const nativeFocus = await browser.electron.execute((electron) => {
  66. const { BrowserWindow, app } = electron;
  67. const win = BrowserWindow.getAllWindows().find((item) => !item.isDestroyed());
  68. app.focus({ steal: true });
  69. win?.restore();
  70. win?.show();
  71. win?.focus();
  72. win?.webContents.focus();
  73. return BrowserWindow.getAllWindows().map((item) => ({
  74. id: item.id,
  75. url: item.webContents.getURL(),
  76. focused: item.isFocused(),
  77. contentsFocused: item.webContents.isFocused(),
  78. }));
  79. });
  80. console.info("TTFT native focus", nativeFocus);
  81. await browser.waitUntil(async () => browser.execute(() => document.hasFocus()), {
  82. timeout: 5000,
  83. timeoutMsg: "真实 Electron 内容未获得焦点",
  84. });
  85. }
  86. async function setInteractionBehavior(behavior: "queue" | "guide") {
  87. if ((await readSettings()).zcodeInteractionBehavior === behavior) return;
  88. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  89. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "agentBehavior"));
  90. await browser.waitUntil(
  91. async () =>
  92. browser.execute(() => {
  93. const trigger = Array.from(
  94. document.querySelectorAll<HTMLElement>('[role="combobox"]'),
  95. ).find((element) =>
  96. ["引导", "Guide", "队列", "Queue"].some((label) => element.innerText.includes(label)),
  97. );
  98. if (!trigger) return false;
  99. trigger.click();
  100. return true;
  101. }),
  102. { timeout: 15000 },
  103. );
  104. await browser.waitUntil(
  105. async () =>
  106. browser.execute(
  107. (labels) => {
  108. const option = Array.from(
  109. document.querySelectorAll<HTMLElement>('[role="option"], [data-radix-collection-item]'),
  110. ).find((element) => labels.includes(element.innerText.trim()));
  111. if (!option) return false;
  112. option.click();
  113. return true;
  114. },
  115. behavior === "guide" ? ["引导", "Guide"] : ["队列", "Queue"],
  116. ),
  117. { timeout: 15000 },
  118. );
  119. await browser.waitUntil(
  120. async () => (await readSettings()).zcodeInteractionBehavior === behavior,
  121. { timeout: 15000 },
  122. );
  123. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  124. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 30000);
  125. }
  126. describe("TTFT02 真实发送诊断到最终 OTLP", () => {
  127. const configPath = join(dirname(DEFAULT_WORKSPACE), ".zcode", "cli", "config.json");
  128. let originalConfig: string | undefined;
  129. const runtimeEvidence: unknown[] = [];
  130. beforeEach(async () => {
  131. await browser.execute(() => {
  132. const state = {
  133. heapStart: (performance as unknown as { memory?: { usedJSHeapSize: number } }).memory
  134. ?.usedJSHeapSize,
  135. longTaskCount: 0,
  136. longTaskMs: 0,
  137. };
  138. const observer = new PerformanceObserver((list) => {
  139. for (const entry of list.getEntries()) {
  140. state.longTaskCount++;
  141. state.longTaskMs += entry.duration;
  142. }
  143. });
  144. observer.observe({ entryTypes: ["longtask"] });
  145. (window as unknown as { __ttftDiagnosticPerf: unknown }).__ttftDiagnosticPerf = {
  146. state,
  147. observer,
  148. };
  149. });
  150. });
  151. afterEach(async () => {
  152. const renderer = await browser.execute(() => {
  153. const probe = (
  154. window as unknown as {
  155. __ttftDiagnosticPerf: { state: unknown; observer: PerformanceObserver };
  156. }
  157. ).__ttftDiagnosticPerf;
  158. probe.observer.disconnect();
  159. return {
  160. sample: probe.state,
  161. heapEnd: (performance as unknown as { memory?: { usedJSHeapSize: number } }).memory
  162. ?.usedJSHeapSize,
  163. focused: document.hasFocus(),
  164. visibility: document.visibilityState,
  165. };
  166. });
  167. const processes = await browser.electron.execute((electron) => electron.app.getAppMetrics());
  168. runtimeEvidence.push({ renderer, processes });
  169. const artifactDir = process.env.ZCODE_E2E_ARTIFACT_DIR;
  170. if (artifactDir)
  171. await writeFile(
  172. join(artifactDir, "ttft-diagnostics-performance.json"),
  173. JSON.stringify(runtimeEvidence, null, 2),
  174. );
  175. });
  176. before(async () => {
  177. originalConfig = await readFile(configPath, "utf8").catch((error: NodeJS.ErrnoException) => {
  178. if (error.code === "ENOENT") return undefined;
  179. throw error;
  180. });
  181. await mkdir(dirname(configPath), { recursive: true });
  182. await mkdir(resolveE2ERuntimePath("ttft-diagnostics"), { recursive: true });
  183. const hook = resolveE2ERuntimePath("ttft-diagnostics", "hook.cjs");
  184. await writeFile(
  185. hook,
  186. 'process.stdin.resume(); process.stdin.on("end", () => setTimeout(() => process.stdout.write("{}"), 300));',
  187. );
  188. await writeFile(resolveE2ERuntimePath("ttft-diagnostics", "input.txt"), "E2E_TTFT_GUIDE_FILE");
  189. await writeFile(
  190. configPath,
  191. JSON.stringify({
  192. ...(originalConfig ? JSON.parse(originalConfig) : {}),
  193. hooks: {
  194. enabled: true,
  195. events: {
  196. UserPromptSubmit: [
  197. {
  198. hooks: [
  199. { type: "command", command: `"${process.execPath}" "${hook}"`, timeoutMs: 3000 },
  200. ],
  201. },
  202. ],
  203. },
  204. },
  205. }),
  206. );
  207. });
  208. after(async () => {
  209. try {
  210. const roots = (await spans()).filter((span) => span.name === "local_ttft");
  211. type MetricPoint = { count?: string; attributes?: { key: string }[] };
  212. const metrics = async () => {
  213. const response = await fetch(ttftReceiverUrl("/records"));
  214. const records = (await response.json()) as Array<{
  215. data: {
  216. resourceMetrics?: Array<{
  217. scopeMetrics: Array<{
  218. metrics: Array<{
  219. name: string;
  220. histogram?: { dataPoints: MetricPoint[] };
  221. sum?: { dataPoints: MetricPoint[] };
  222. }>;
  223. }>;
  224. }>;
  225. };
  226. }>;
  227. return records
  228. .flatMap((record) => record.data.resourceMetrics ?? [])
  229. .flatMap((resource) => resource.scopeMetrics)
  230. .flatMap((scope) => scope.metrics)
  231. .filter((metric) => metric.name.startsWith("zcode.local_ttft."));
  232. };
  233. const count = async () =>
  234. (await metrics())
  235. .filter((metric) => metric.name === "zcode.local_ttft.duration")
  236. .flatMap((metric) => metric.histogram?.dataPoints ?? [])
  237. .reduce((sum, point) => sum + Number(point.count ?? 0), 0);
  238. await browser.waitUntil(async () => (await count()) >= roots.length, {
  239. timeout: 15000,
  240. timeoutMsg: "最终 OTLP Histogram 尚未覆盖所有成功根",
  241. });
  242. expect(await count()).toBe(roots.length);
  243. const forbidden = new Set([
  244. "observation_id",
  245. "command_id",
  246. "input_id",
  247. "query_id",
  248. "session_id",
  249. "trace_id",
  250. "request_id",
  251. "workspace_path",
  252. "workspace_id",
  253. "user_id",
  254. "cli_instance_id",
  255. ]);
  256. expect(
  257. (await metrics())
  258. .flatMap((metric) => [
  259. ...(metric.histogram?.dataPoints ?? []),
  260. ...(metric.sum?.dataPoints ?? []),
  261. ])
  262. .flatMap((point) => point.attributes ?? [])
  263. .some((attribute) => forbidden.has(attribute.key)),
  264. ).toBe(false);
  265. const artifactDir = process.env.ZCODE_E2E_ARTIFACT_DIR;
  266. if (artifactDir)
  267. await writeFile(
  268. join(artifactDir, "ttft-diagnostics-otlp.json"),
  269. JSON.stringify(
  270. {
  271. spans: (await spans()).filter((span) => span.name.startsWith("local_ttft")),
  272. metrics: await metrics(),
  273. },
  274. null,
  275. 2,
  276. ),
  277. );
  278. } finally {
  279. if (originalConfig !== undefined) await writeFile(configPath, originalConfig);
  280. else await rm(configPath, { force: true });
  281. }
  282. });
  283. it("队列转正保留原输入,后台返回仍导出首输出和独立阶段", async function () {
  284. this.timeout(180000);
  285. await fetch(ttftReceiverUrl("/reset"), { method: "POST" });
  286. await prepareV4ConversationE2E();
  287. await focus();
  288. await sendV4Prompt("E2E_TTFT_DIAG_HOLD: Reply ttft-diag-hold-ok.");
  289. await waitForV4ConversationState((state) => state.state === "streaming", "主任务未运行");
  290. await sendV4Prompt("E2E_TTFT_DIAG_QUEUE: Reply ttft-diag-queue-ok.");
  291. await waitForV4QueueCount(1);
  292. expect((await getV4QueueItems())[0]?.text).toContain("E2E_TTFT_DIAG_QUEUE");
  293. await browser.electron.execute((electron) => {
  294. const { BrowserWindow } = electron;
  295. BrowserWindow.getAllWindows()
  296. .find((win) => !win.isDestroyed())
  297. ?.minimize();
  298. });
  299. // minimize 是异步窗口操作;旧用例立即 focus,系统尚未派发 hidden 就已恢复前台。
  300. // 等真实可见性事件完成,才能验证后台返回分类,不用延时模拟后台状态。
  301. await browser.waitUntil(() => browser.execute(() => document.visibilityState === "hidden"), {
  302. timeout: 10000,
  303. timeoutMsg: "最小化后 renderer 未进入后台可见性状态",
  304. });
  305. await browser.waitUntil(
  306. async () => (await spans()).some((span) => span.name === "local_ttft.start"),
  307. { timeout: 5000 },
  308. );
  309. await focus();
  310. await waitForV4AssistantMessageContaining("ttft-diag-queue-ok");
  311. await waitRoot(2);
  312. const exported = await spans();
  313. const queued = exported.find(
  314. (span) => span.name === "local_ttft" && attr(span, "send_mode") === "queued",
  315. );
  316. expect(queued).toBeDefined();
  317. expect(
  318. exported.some(
  319. (span) => span.traceId === queued!.traceId && span.name === "local_ttft.prepare.context",
  320. ),
  321. ).toBe(true);
  322. expect(
  323. exported
  324. .filter(
  325. (span) => span.traceId === queued!.traceId && span.name === "local_ttft.prepare.hooks",
  326. )
  327. .some((span) => ms(span) >= 290),
  328. ).toBe(true);
  329. expect(attr(queued!, "visibility")).toBe("background_returned");
  330. expect(
  331. exported.filter(
  332. (span) => span.traceId === queued!.traceId && span.name === "local_ttft.execution_wait",
  333. ),
  334. ).toHaveLength(1);
  335. expect(
  336. ms(
  337. exported.find(
  338. (span) => span.traceId === queued!.traceId && span.name === "local_ttft.execution_wait",
  339. )!,
  340. ),
  341. ).toBeGreaterThan(500);
  342. });
  343. it("取消首输出前的等待,只记录明确取消,不产生成功耗时", async function () {
  344. this.timeout(120000);
  345. await waitForV4ConversationState((state) => state.state === "idle", "队列未完成");
  346. await startDraftFromProject(DEFAULT_WORKSPACE);
  347. await focus();
  348. await sendV4Prompt("E2E_TTFT_DIAG_CANCEL: Wait before answering.");
  349. await waitForV4ConversationState((state) => state.state === "streaming", "待取消任务未启动");
  350. await clickV4Stop();
  351. await browser.waitUntil(
  352. async () =>
  353. (await spans()).some(
  354. (span) => span.name === "local_ttft.excluded" && attr(span, "outcome") === "cancelled",
  355. ),
  356. { timeout: 15000 },
  357. );
  358. expect((await spans()).filter((span) => span.name === "local_ttft")).toHaveLength(2);
  359. });
  360. it("失败重试后的首输出只产生一份 TTFT,并导出两个 attempt", async function () {
  361. this.timeout(120000);
  362. await waitForV4ConversationState((state) => state.state === "idle", "取消未结束");
  363. await startDraftFromProject(DEFAULT_WORKSPACE);
  364. await focus();
  365. const before = (await spans()).filter((span) => span.name === "local_ttft").length;
  366. await sendV4Prompt("E2E_TTFT_DIAG_RETRY: Reply ttft-diag-retry-ok.");
  367. await waitForV4AssistantMessageContaining("ttft-diag-retry-ok");
  368. await waitRoot(before + 1);
  369. const all = await spans();
  370. const roots = all.filter((span) => span.name === "local_ttft");
  371. const root = roots.at(-1)!;
  372. expect(roots).toHaveLength(before + 1);
  373. const attempts = all.filter(
  374. (span) => span.traceId === root.traceId && span.name === "local_ttft.attempt",
  375. );
  376. expect(attempts).toHaveLength(2);
  377. expect(attempts.map((span) => attr(span, "detail_outcome"))).toEqual([
  378. "failed",
  379. "first_output",
  380. ]);
  381. expect(new Set(attempts.map((span) => attr(span, "request_id"))).size).toBe(2);
  382. expect(attr(root, "request_id")).toBe(attr(attempts[1]!, "request_id"));
  383. expect(
  384. all.some((span) => span.traceId === root.traceId && span.name === "local_ttft.retry_wait"),
  385. ).toBe(true);
  386. });
  387. it("明确模型失败保留已等待时间和阶段,不增加成功样本", async function () {
  388. this.timeout(120000);
  389. await waitForV4ConversationState((state) => state.state === "idle", "重试未结束");
  390. await startDraftFromProject(DEFAULT_WORKSPACE);
  391. await focus();
  392. const before = (await spans()).filter((span) => span.name === "local_ttft").length;
  393. await sendV4Prompt("E2E_TTFT_DIAG_FAIL: Fail before any output.");
  394. await browser.waitUntil(
  395. async () =>
  396. (await spans()).some(
  397. (span) => span.name === "local_ttft.excluded" && attr(span, "outcome") === "failed",
  398. ),
  399. { timeout: 20000 },
  400. );
  401. expect((await spans()).filter((span) => span.name === "local_ttft")).toHaveLength(before);
  402. });
  403. it("立即引导独立分类,不抢占主轮工具首输出", async function () {
  404. this.timeout(120000);
  405. await waitForV4ConversationState((state) => state.state === "idle", "失败轮未结束");
  406. await startDraftFromProject(DEFAULT_WORKSPACE);
  407. await focus();
  408. await setInteractionBehavior("guide");
  409. await focus();
  410. const before = (await spans()).filter((span) => span.name === "local_ttft").length;
  411. await sendV4Prompt(
  412. "E2E_TTFT_DIAG_GUIDE_PARENT: Read .zcode-e2e/ttft-diagnostics/input.txt then reply ttft-diag-guide-ok.",
  413. );
  414. await waitForV4ConversationState((state) => state.state === "streaming", "引导主轮未启动");
  415. await sendV4Prompt("E2E_TTFT_DIAG_GUIDE_INPUT: Keep the requested final answer.");
  416. await waitForV4AssistantMessageContaining("ttft-diag-guide-ok");
  417. await browser.waitUntil(
  418. async () =>
  419. (await spans()).some(
  420. (span) => span.name === "local_ttft.excluded" && attr(span, "outcome") === "guided",
  421. ),
  422. { timeout: 15000 },
  423. );
  424. await waitRoot(before + 1);
  425. expect((await spans()).filter((span) => span.name === "local_ttft")).toHaveLength(before + 1);
  426. await setInteractionBehavior("queue");
  427. });
  428. it("二次确认沿首次提交计时,send-now 保留被提升输入的关联", async function () {
  429. this.timeout(180000);
  430. await waitForV4ConversationState((state) => state.state === "idle", "引导轮未结束");
  431. await startDraftFromProject(DEFAULT_WORKSPACE);
  432. await focus();
  433. await sendV4Prompt("E2E_TTFT_DIAG_PAUSE: Wait before responding.");
  434. await waitForV4ConversationState((state) => state.state === "streaming", "暂停主轮未启动");
  435. await sendV4Prompt("E2E_TTFT_DIAG_HELD: Reply ttft-diag-held-ok.");
  436. await waitForV4QueueCount(1);
  437. const held = (await getV4QueueItems())[0]!;
  438. await clickV4Stop();
  439. await waitForV4ConversationState((state) => state.state === "idle", "暂停主轮未停止");
  440. const before = (await spans()).filter((span) => span.name === "local_ttft").length;
  441. await sendV4Prompt("E2E_TTFT_DIAG_CONFIRM: Reply ttft-diag-confirm-ok.");
  442. await waitForV4PausedQueueSendDialog();
  443. // 显式模拟用户阅读弹窗的停留,不用于业务状态同步。
  444. await browser.pause(350);
  445. await clickTestIdByDom(TID_V4_COMPOSER_KEEP_QUEUE_SEND);
  446. await waitForV4AssistantMessageContaining("ttft-diag-confirm-ok");
  447. await waitRoot(before + 1);
  448. const confirmed = (await spans()).filter((span) => span.name === "local_ttft").at(-1)!;
  449. expect(
  450. (await spans()).filter(
  451. (span) => span.traceId === confirmed.traceId && span.name === "local_ttft.start",
  452. ),
  453. ).toHaveLength(1);
  454. expect(
  455. (await spans())
  456. .filter(
  457. (span) =>
  458. span.traceId === confirmed.traceId && span.name === "local_ttft.user_confirmation",
  459. )
  460. .some((span) => ms(span) >= 350),
  461. ).toBe(true);
  462. await clickV4QueueItemSendNow(held.queueItemId);
  463. await waitForV4AssistantMessageContaining("ttft-diag-held-ok");
  464. await waitRoot(before + 2);
  465. const promoted = (await spans()).filter((span) => span.name === "local_ttft").at(-1)!;
  466. expect(held.queueItemId).toContain(attr(promoted, "command_id"));
  467. });
  468. });