automationTelemetry.test.ts 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. import { describe, expect, it, vi } from "vitest";
  2. import type { ProviderSettingsView } from "@zcode/services";
  3. import {
  4. reportAutomationCreateResult,
  5. resolveAutomationModelTelemetry,
  6. sanitizeAutomationTelemetryError,
  7. } from "@/lib/automationTelemetry.js";
  8. describe("automation telemetry", () => {
  9. it.each([
  10. ["[AUTOMATION_CREATE_LIMIT_REACHED] automation limit reached", "limit"],
  11. ["ETIMEDOUT connecting to https://private.example/path?token=FAKE_SECRET", "timeout"],
  12. ["connect ECONNREFUSED 127.0.0.1:8080", "network"],
  13. ["fetch failed", "network"],
  14. ["Unauthorized: Authorization: Bearer FAKE_SECRET", "auth"],
  15. ["Invalid automation mode: FAKE_SECRET", "validation"],
  16. ["Automation 模型选择不可用,请重新选择模型与思考档位", "validation"],
  17. ["unexpected FAKE_SECRET /Users/private/file", "unknown"],
  18. ["[FAKE_SECRET] failed", "unknown"],
  19. [null, "unknown"],
  20. [undefined, "unknown"],
  21. ["", "unknown"],
  22. ])("失败分类 %s -> %s,原文不出网", async (error, errorCode) => {
  23. const reportTelemetryEvent = vi.fn(async () => {});
  24. await reportAutomationCreateResult(
  25. { reportTelemetryEvent },
  26. {
  27. cronExpr: "0 9 * * *",
  28. error,
  29. modelFields: { model_name: "", model_provider: "", provider_name: "" },
  30. },
  31. );
  32. expect(reportTelemetryEvent).toHaveBeenCalledOnce();
  33. expect(reportTelemetryEvent).toHaveBeenCalledWith(
  34. expect.objectContaining({
  35. elementName: "automation_create_result",
  36. eventExtraDetail: expect.objectContaining({
  37. status: "fail",
  38. error_code: errorCode,
  39. error_msg: error ? "[redacted]" : "",
  40. }),
  41. }),
  42. );
  43. expect(JSON.stringify(reportTelemetryEvent.mock.calls)).not.toContain("FAKE_SECRET");
  44. expect(JSON.stringify(reportTelemetryEvent.mock.calls)).not.toContain("/Users/private");
  45. });
  46. it("成功不携带过期失败分类或原文", async () => {
  47. const reportTelemetryEvent = vi.fn(async () => {});
  48. await reportAutomationCreateResult(
  49. { reportTelemetryEvent },
  50. {
  51. automationId: "automation-1",
  52. cronExpr: "0 9 * * *",
  53. error: "Unauthorized FAKE_SECRET",
  54. modelFields: { model_name: "", model_provider: "", provider_name: "" },
  55. },
  56. );
  57. expect(reportTelemetryEvent).toHaveBeenCalledWith(
  58. expect.objectContaining({
  59. eventExtraDetail: expect.objectContaining({
  60. status: "success",
  61. error_code: "",
  62. error_msg: "",
  63. }),
  64. }),
  65. );
  66. });
  67. it("只从自定义 provider endpoint 提取 hostname", () => {
  68. const providerSettingsView = createProviderSettingsView({ builtin: false });
  69. expect(
  70. resolveAutomationModelTelemetry(
  71. "custom:custom-provider-id:glm-test",
  72. undefined,
  73. providerSettingsView,
  74. ),
  75. ).toEqual({
  76. model_name: "glm-test",
  77. model_provider: "custom-provider-id",
  78. provider_name: "api.example.com",
  79. });
  80. });
  81. it("官方 Provider 不把服务地址写入自动化遥测", () => {
  82. expect(
  83. resolveAutomationModelTelemetry(
  84. "custom:custom-provider-id:glm-test",
  85. undefined,
  86. createProviderSettingsView({ builtin: true }),
  87. ),
  88. ).toEqual({
  89. model_name: "glm-test",
  90. model_provider: "custom-provider-id",
  91. provider_name: "",
  92. });
  93. });
  94. it("失败摘要移除路径、URL 和凭据并限制长度", () => {
  95. const result = sanitizeAutomationTelemetryError(
  96. `failed /Users/test/private.txt https://example.com/path?q=secret token=secret ${"x".repeat(600)}`,
  97. );
  98. expect(result).not.toContain("/Users/test");
  99. expect(result).not.toContain("q=secret");
  100. expect(result).not.toContain("token=secret");
  101. expect(result).toBe("[redacted]");
  102. expect(sanitizeAutomationTelemetryError("Authorization: Bearer FAKE_SECRET")).toBe(
  103. "[redacted]",
  104. );
  105. expect(sanitizeAutomationTelemetryError(undefined)).toBe("");
  106. });
  107. });
  108. function createProviderSettingsView({ builtin }: { builtin: boolean }): ProviderSettingsView {
  109. return {
  110. revision: 1,
  111. providerTemplates: [],
  112. providerOrder: [],
  113. providers: [
  114. {
  115. providerId: "custom-provider-id",
  116. providerName: "Custom",
  117. ...(builtin ? { templateId: "official-api" } : {}),
  118. enabled: true,
  119. executable: true,
  120. effectiveConfig: {
  121. group: "standard-personal",
  122. access: { type: "api-key", apiKey: "secret" },
  123. api: {
  124. type: "openai-chat-completions",
  125. baseUrl: "https://api.example.com/v1/messages?token=secret",
  126. },
  127. personalModelIds: [],
  128. },
  129. issues: [],
  130. models: [],
  131. },
  132. ],
  133. };
  134. }