automationsSectionOffPeakTelemetry.test.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. // @vitest-environment node
  2. import { readFileSync } from "node:fs";
  3. import { describe, expect, it, vi } from "vitest";
  4. import type { IPlatformService, OffPeakTaskCreateResult } from "@zcode/shared";
  5. import {
  6. buildOffPeakCreateResultTelemetryPayload,
  7. createAndReportOffPeakTask,
  8. freezeOffPeakCreateTelemetrySnapshot,
  9. reportOffPeakCreateResult,
  10. } from "@/lib/offPeakTelemetry.js";
  11. const automationsSectionSource = readFileSync(
  12. new URL("../src/settings/AutomationsSection.tsx", import.meta.url),
  13. "utf8",
  14. );
  15. /** CR-01:闲时任务创建结果埋点接线必须从首页模板、Automations 模板、直接创建、灰度门禁失败 4 个入口
  16. * 各产生恰好 1 个 off_peak_task_create_result 事件。源契约保证接线不被悄悄删除;helper 行为
  17. * 在 packages/ui/test/offPeakTelemetry.test.ts 覆盖。 */
  18. describe("AutomationsSection off-peak create telemetry wiring (CR-01)", () => {
  19. it("从 store 引入 OffPeakCreateDraft 类型", () => {
  20. expect(automationsSectionSource).toMatch(
  21. /import \{[\s\S]*?type OffPeakCreateDraft,?[\s\S]*?\} from "@\/store\/offPeakTaskStore\.js"/,
  22. );
  23. });
  24. it("从 offPeakTelemetry.js 引入全部 3 个 helper", () => {
  25. expect(automationsSectionSource).toContain("createAndReportOffPeakTask");
  26. expect(automationsSectionSource).toContain("freezeOffPeakCreateTelemetrySnapshot");
  27. expect(automationsSectionSource).toContain("reportOffPeakCreateResult");
  28. const importBlock = automationsSectionSource.match(
  29. /import \{[\s\S]*?\} from "@\/lib\/offPeakTelemetry\.js"/,
  30. );
  31. expect(importBlock).not.toBeNull();
  32. });
  33. it("AutomationsView 的 offpeak-create 模式使用 OffPeakCreateDraft 而非收窄的内联类型", () => {
  34. const offpeakCreateLine = automationsSectionSource.match(
  35. /mode: "offpeak-create";\s*draft\?: [^\n]+/,
  36. );
  37. expect(offpeakCreateLine).not.toBeNull();
  38. expect(offpeakCreateLine?.[0]).toContain("OffPeakCreateDraft");
  39. expect(offpeakCreateLine?.[0]).not.toContain("title?: string; prompt?: string");
  40. });
  41. it("Client Scenes idle template click 在 draft 上携带 telemetrySource(Automations 模板入口)", () => {
  42. const templateSection = automationsSectionSource.slice(
  43. automationsSectionSource.indexOf("data-automations-idle-templates"),
  44. automationsSectionSource.indexOf("data-automations-scheduled-templates"),
  45. );
  46. expect(templateSection).toContain("automationTemplates.offPeak.map");
  47. expect(templateSection).toContain('eventRegion: "app.automations"');
  48. expect(templateSection).toMatch(/templateId:\s*template\.id/);
  49. });
  50. it("handleOffPeakSubmit 顶部先 freezeOffPeakCreateTelemetrySnapshot", () => {
  51. const submitBlock = automationsSectionSource.match(
  52. /const handleOffPeakSubmit = useCallback\([\s\S]*?\n \);/,
  53. );
  54. expect(submitBlock).not.toBeNull();
  55. expect(submitBlock?.[0]).toContain("freezeOffPeakCreateTelemetrySnapshot");
  56. expect(submitBlock?.[0]).toContain("current.draft?.telemetrySource");
  57. expect(submitBlock?.[0]).toContain("input.model");
  58. // 仅 offpeak-create 模式冻结 snapshot,offpeak-edit 走 offPeakUpdate 不需要埋点
  59. expect(submitBlock?.[0]).toMatch(
  60. /current\.mode === "offpeak-create"[\s\S]*?freezeOffPeakCreateTelemetrySnapshot/,
  61. );
  62. });
  63. it("灰度门禁失败时 fire-and-forget 上报 client_validation 结果", () => {
  64. const submitBlock = automationsSectionSource.match(
  65. /const handleOffPeakSubmit = useCallback\([\s\S]*?\n \);/,
  66. );
  67. expect(submitBlock).not.toBeNull();
  68. expect(submitBlock?.[0]).toContain("reportOffPeakCreateResult");
  69. expect(submitBlock?.[0]).toContain('failureStage: "client_validation"');
  70. expect(submitBlock?.[0]).toContain('errorCategory: "client_validation"');
  71. // 防止阻塞主流程,必须 fire-and-forget
  72. expect(submitBlock?.[0]).toMatch(
  73. /void reportOffPeakCreateResult\(platform, telemetrySnapshot, \{/,
  74. );
  75. // 灰度门禁失败后立即 return false,不调用 offPeakCreate
  76. expect(submitBlock?.[0]).toMatch(/reportOffPeakCreateResult[\s\S]*?return false;/);
  77. });
  78. it("创建路径用 createAndReportOffPeakTask 包裹 offPeakCreate", () => {
  79. // 三元表达式:snapshot 非空走 createAndReportOffPeakTask,否则 fallback 到原 offPeakCreate
  80. const ternaryBlock = automationsSectionSource.match(
  81. /telemetrySnapshot !== null\s*\n\s*\?\s*await createAndReportOffPeakTask\([\s\S]*?offPeakCreate\(input, offPeakTaskService\)\s*,?\s*\)\s*\n\s*:\s*await offPeakCreate\(input, offPeakTaskService\)/,
  82. );
  83. expect(ternaryBlock).not.toBeNull();
  84. expect(ternaryBlock?.[0]).toContain("createAndReportOffPeakTask");
  85. expect(ternaryBlock?.[0]).toContain("offPeakCreate(input, offPeakTaskService)");
  86. // 必须用 platform + telemetrySnapshot 喂给 createAndReportOffPeakTask
  87. expect(ternaryBlock?.[0]).toMatch(
  88. /createAndReportOffPeakTask\(platform, telemetrySnapshot, \(\) =>/,
  89. );
  90. });
  91. it("useCallback 依赖列表包含 platform", () => {
  92. const submitBlock = automationsSectionSource.match(
  93. /const handleOffPeakSubmit = useCallback\([\s\S]*?\n \);/,
  94. );
  95. expect(submitBlock).not.toBeNull();
  96. // 依赖块必须包含 platform;提交路径通过它上报
  97. expect(submitBlock?.[0]).toMatch(/\[[\s\S]*?platform,?[\s\S]*?\]/);
  98. });
  99. });
  100. /** Helper 行为在 offPeakTelemetry.test.ts 已覆盖;此处用同源类型做一次烟雾测试,
  101. * 防止 telemetry helper 自身意外回归导致接线看似存在实际不可用。 */
  102. describe("offPeakTelemetry helpers used by AutomationsSection (smoke)", () => {
  103. const successResult = {
  104. ok: true,
  105. task: {
  106. offPeakTaskId: "offpeak-stable-1",
  107. serverTicketId: "forbidden-ticket",
  108. title: "forbidden title",
  109. prompt: "forbidden prompt",
  110. permissionMode: "build",
  111. workspaceKey: "/forbidden/workspace",
  112. workspacePath: "/forbidden/workspace",
  113. status: "queued",
  114. queuedAt: 1,
  115. createdAt: 1,
  116. updatedAt: 1,
  117. },
  118. ticketInitialState: "queued",
  119. providerName: "api.example.com",
  120. } satisfies OffPeakTaskCreateResult;
  121. it("首页模板来源 (eventRegion=app.session) freeze 后能产出正确 payload", () => {
  122. const snapshot = freezeOffPeakCreateTelemetrySnapshot({
  123. source: { eventRegion: "app.session", templateId: "standupGitSummary" },
  124. model: "GLM-5.2",
  125. providerId: "account:zai-offpeak-idle-plan",
  126. });
  127. expect(snapshot).toMatchObject({
  128. eventRegion: "app.session",
  129. templateId: "standupGitSummary",
  130. modelProvider: "offpeak-idle-plan",
  131. });
  132. const payload = buildOffPeakCreateResultTelemetryPayload(snapshot, successResult);
  133. expect(payload.elementName).toBe("off_peak_task_create_result");
  134. expect(payload.eventRegion).toBe("app.session");
  135. });
  136. it("Automations 模板来源 (eventRegion=app.automations) freeze 后 templateId 透传", () => {
  137. const snapshot = freezeOffPeakCreateTelemetrySnapshot({
  138. source: { eventRegion: "app.automations", templateId: "ciFlakyReport" },
  139. model: "GLM-5.2",
  140. });
  141. expect(snapshot.templateId).toBe("ciFlakyReport");
  142. expect(snapshot.eventRegion).toBe("app.automations");
  143. });
  144. it("无 source 时回落到 app.automations + templateId=''(直接创建入口)", () => {
  145. const snapshot = freezeOffPeakCreateTelemetrySnapshot({ model: "GLM-5.2" });
  146. expect(snapshot.eventRegion).toBe("app.automations");
  147. expect(snapshot.templateId).toBe("");
  148. });
  149. it("灰度门禁失败 payload 含 failure_stage=client_validation", () => {
  150. const snapshot = freezeOffPeakCreateTelemetrySnapshot({
  151. source: { eventRegion: "app.automations", templateId: "ciFlakyReport" },
  152. model: "GLM-5.2",
  153. });
  154. const payload = buildOffPeakCreateResultTelemetryPayload(snapshot, {
  155. ok: false,
  156. failureStage: "client_validation",
  157. errorCategory: "client_validation",
  158. errorCode: "",
  159. providerName: "",
  160. });
  161. expect(payload.eventExtraDetail).toMatchObject({
  162. result: "failure",
  163. failure_stage: "client_validation",
  164. error_category: "client_validation",
  165. });
  166. });
  167. it("createAndReportOffPeakTask 触发恰好一次 reportTelemetryEvent(best-effort 边界)", async () => {
  168. const reportTelemetryEvent = vi.fn(async () => undefined);
  169. const platform = {
  170. reportTelemetryEvent,
  171. } as unknown as Pick<IPlatformService, "reportTelemetryEvent">;
  172. const create = vi.fn(async () => successResult);
  173. const snapshot = freezeOffPeakCreateTelemetrySnapshot({
  174. source: { eventRegion: "app.session", templateId: "standupGitSummary" },
  175. model: "GLM-5.2",
  176. });
  177. await createAndReportOffPeakTask(platform, snapshot, create);
  178. // fire-and-forget: 需要 microtask flush
  179. await new Promise((resolve) => setTimeout(resolve, 0));
  180. expect(reportTelemetryEvent).toHaveBeenCalledOnce();
  181. });
  182. it("reportOffPeakCreateResult reporter 拒绝被吞掉不抛", async () => {
  183. const reportTelemetryEvent = vi.fn().mockRejectedValue(new Error("network"));
  184. const platform = {
  185. reportTelemetryEvent,
  186. } as unknown as Pick<IPlatformService, "reportTelemetryEvent">;
  187. const snapshot = freezeOffPeakCreateTelemetrySnapshot({ model: "GLM-5.2" });
  188. await expect(
  189. reportOffPeakCreateResult(platform, snapshot, successResult),
  190. ).resolves.toBeUndefined();
  191. });
  192. });