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

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