background-notification-usage.ts 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { readFile, readdir } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { TID_CHAT_CONTEXT_USAGE_TRIGGER } from "@zcode/shared/test-ids";
  4. import { getV4PaneSnapshot } from "./v4-conversation.js";
  5. import { sel } from "./selectors.js";
  6. type UsageCategory = { source: string; chars: number };
  7. /** V4 不使用 legacy task store 的 usage;读取同一 session 的实际请求统计。 */
  8. export async function readBackgroundContextUsage(): Promise<UsageCategory[]> {
  9. const { sessionId } = await getV4PaneSnapshot();
  10. const logDir = process.env.ZCODE_LOG_DIR;
  11. if (!sessionId || sessionId === "draft" || !logDir) {
  12. throw new Error("BG36 缺少已绑定 session 或 worker 日志目录");
  13. }
  14. const records: Array<{ timestamp: string; context: { categories: UsageCategory[] } }> = [];
  15. for (const file of (await readdir(logDir)).filter((name) => name.endsWith(".jsonl"))) {
  16. const content = await readFile(join(logDir, file), "utf8");
  17. // 日志按行追加;只解析已完整写入的行,避免读取后台 child 正在写入的末行。
  18. for (const line of content.split("\n").slice(0, -1)) {
  19. if (!line.includes("context_usage_snapshot") || !line.includes(sessionId)) continue;
  20. const record = JSON.parse(line);
  21. if (
  22. record.event === "context_usage_snapshot" &&
  23. record.sessionId === sessionId &&
  24. record.context?.querySource === "main_turn"
  25. ) {
  26. records.push(record);
  27. }
  28. }
  29. }
  30. const latest = records
  31. .sort((left, right) => left.timestamp.localeCompare(right.timestamp))
  32. .at(-1);
  33. expect(latest).toBeDefined();
  34. return latest!.context.categories.map(({ source, chars }) => ({ source, chars }));
  35. }
  36. /** 用当前 V4 面板显示的占比核对 CLI 分类结果,不引入新的测试专用状态接口。 */
  37. export async function assertBackgroundUsageInV4(categories: UsageCategory[]): Promise<void> {
  38. const messageChars = categories.find((item) => item.source === "messages")!.chars;
  39. const totalChars = categories.reduce((sum, item) => sum + item.chars, 0);
  40. const expectedPercent = Math.round((messageChars / totalChars) * 1000) / 10;
  41. await $(sel(TID_CHAT_CONTEXT_USAGE_TRIGGER)).moveTo();
  42. let actualPercent: number | null = null;
  43. await browser.waitUntil(
  44. async () => {
  45. actualPercent = await browser.execute(() => {
  46. const panel = document.querySelector(
  47. '[aria-label="Context sources"], [aria-label="上下文来源"]',
  48. );
  49. const row = Array.from(panel?.firstElementChild?.children ?? []).find((element) =>
  50. Array.from(element.children).some((label) =>
  51. ["Messages", "消息"].includes(label.textContent?.trim() ?? ""),
  52. ),
  53. );
  54. const text = row?.lastElementChild?.textContent?.trim();
  55. return text ? Number(text.replace("%", "")) : null;
  56. });
  57. return actualPercent === expectedPercent;
  58. },
  59. { timeout: 10000, timeoutMsg: `BG36 V4 Messages 占比应为 ${expectedPercent}%` },
  60. );
  61. expect(actualPercent).toBe(expectedPercent);
  62. }