telemetryService.test.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. import { mkdirSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  5. import { setDataBaseDir } from "../src/paths.js";
  6. const originalHome = process.env.HOME;
  7. const originalCrypto = globalThis.crypto;
  8. const tempHomes: string[] = [];
  9. function makeTempHome(): string {
  10. const home = mkdtempSync(join(tmpdir(), "zcode-telemetry-home-"));
  11. tempHomes.push(home);
  12. // Bugfix: paths.ts 会在模块加载时固定默认 dataBaseDir,测试隔离必须显式覆盖。
  13. setDataBaseDir(home);
  14. return home;
  15. }
  16. async function waitForCalls(
  17. mock: ReturnType<typeof vi.fn<typeof fetch>>,
  18. expectedCalls: number,
  19. ): Promise<void> {
  20. for (let attempt = 0; attempt < 20; attempt += 1) {
  21. if (mock.mock.calls.length === expectedCalls) {
  22. return;
  23. }
  24. await new Promise((resolve) => setTimeout(resolve, 10));
  25. }
  26. expect(mock).toHaveBeenCalledTimes(expectedCalls);
  27. }
  28. beforeEach(() => {
  29. Object.defineProperty(globalThis, "crypto", {
  30. value: originalCrypto,
  31. configurable: true,
  32. });
  33. });
  34. afterEach(() => {
  35. process.env.HOME = originalHome;
  36. setDataBaseDir(null);
  37. Object.defineProperty(globalThis, "crypto", {
  38. value: originalCrypto,
  39. configurable: true,
  40. });
  41. vi.restoreAllMocks();
  42. while (tempHomes.length > 0) {
  43. const home = tempHomes.pop();
  44. if (home) {
  45. rmSync(home, { recursive: true, force: true });
  46. }
  47. }
  48. });
  49. describe("telemetryCore", () => {
  50. it.each(["onboarding-user", ""])(
  51. "onboarding events use common user/device fields for %s",
  52. async (userId) => {
  53. const home = makeTempHome();
  54. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  55. const fetchMock = vi
  56. .fn<typeof fetch>()
  57. .mockResolvedValue(new Response(null, { status: 204 }));
  58. const dependencies = { homeDir: home, loadUserId: async () => userId, fetchImpl: fetchMock };
  59. const context = {
  60. clientTimezone: "Asia/Shanghai",
  61. clientLanguage: "zh-CN",
  62. screenResolution: "1280x800",
  63. };
  64. const detail = {
  65. work_direction: "software_data_ai",
  66. ui_mode: "code",
  67. workspace_memory_enabled: "false",
  68. proactive_task_recommendations_enabled: "null",
  69. claude_code_history_migration_selected: "false",
  70. exit_action: "close",
  71. exit_step: "3",
  72. };
  73. await createTelemetryCore(dependencies).reportEvent({
  74. context,
  75. elementName: "onboarding_expose",
  76. eventRegion: "app.onboarding",
  77. eventType: "expose",
  78. eventText: "",
  79. eventExtraDetail: {},
  80. });
  81. // 重建 Core 模拟进程重新加载,共用持久化设备标识,不由 UI 的 getDeviceId 代替。
  82. await createTelemetryCore(dependencies).reportEvent({
  83. context,
  84. elementName: "onboarding_end",
  85. eventRegion: "app.onboarding",
  86. eventType: "ck",
  87. eventText: "退出引导",
  88. eventExtraDetail: detail,
  89. });
  90. const bodies = fetchMock.mock.calls.map(([, init]) => JSON.parse(String(init?.body)));
  91. expect(bodies).toHaveLength(2);
  92. expect(bodies[0]).toMatchObject({
  93. user_id: userId,
  94. device_mid: expect.any(String),
  95. element_name: "onboarding_expose",
  96. });
  97. expect(bodies[0].device_mid).not.toBe("");
  98. expect(bodies[1]).toMatchObject({
  99. user_id: userId,
  100. device_mid: bodies[0].device_mid,
  101. element_name: "onboarding_end",
  102. event_text: "退出引导",
  103. event_extra_detail: detail,
  104. });
  105. expect(bodies[0].event_id).not.toBe(bodies[1].event_id);
  106. },
  107. );
  108. it("uses crypto.randomUUID with the correct receiver by default", async () => {
  109. const home = makeTempHome();
  110. process.env.HOME = home;
  111. const fakeCrypto = {
  112. randomUUID(this: unknown) {
  113. if (this !== fakeCrypto) {
  114. throw new TypeError('Value of "this" must be fakeCrypto');
  115. }
  116. return "default-random-id";
  117. },
  118. } as Crypto;
  119. Object.defineProperty(globalThis, "crypto", {
  120. value: fakeCrypto,
  121. configurable: true,
  122. });
  123. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  124. const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status: 204 }));
  125. const service = createTelemetryCore({
  126. fetchImpl: fetchMock,
  127. appVersion: "0.25.1",
  128. platform: "darwin",
  129. osVersion: "13.7.8",
  130. }) as {
  131. reportAppLaunch(context: {
  132. clientTimezone: string;
  133. clientLanguage: string;
  134. screenResolution: string;
  135. }): Promise<void>;
  136. };
  137. await service.reportAppLaunch({
  138. clientTimezone: "Asia/Shanghai",
  139. clientLanguage: "zh-CN",
  140. screenResolution: "3024x1964",
  141. });
  142. const [, requestInit] = fetchMock.mock.calls[0]!;
  143. expect(JSON.parse(String((requestInit as RequestInit).body))).toMatchObject({
  144. event_id: "default-random-id",
  145. });
  146. });
  147. it("reports app_launch with the expected request payload", async () => {
  148. const home = makeTempHome();
  149. process.env.HOME = home;
  150. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  151. const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status: 204 }));
  152. const service = createTelemetryCore({
  153. loadUserId: async () => "60171703486074334",
  154. fetchImpl: fetchMock,
  155. randomUUID: () => "452a978b-d926-4a65-9c07-b04344a307d0",
  156. appVersion: "0.25.1",
  157. platform: "darwin",
  158. osVersion: "13.7.8",
  159. }) as {
  160. reportAppLaunch(context: {
  161. clientTimezone: string;
  162. clientLanguage: string;
  163. screenResolution: string;
  164. }): Promise<void>;
  165. };
  166. await service.reportAppLaunch({
  167. clientTimezone: "Asia/Shanghai",
  168. clientLanguage: "zh-CN",
  169. screenResolution: "3024x1964",
  170. });
  171. expect(fetchMock).toHaveBeenCalledTimes(1);
  172. expect(fetchMock).toHaveBeenCalledWith(
  173. "https://zcode.z.ai/api/v1/event/report",
  174. expect.objectContaining({
  175. method: "POST",
  176. headers: expect.objectContaining({ "Content-Type": "application/json" }),
  177. }),
  178. );
  179. const [, requestInit] = fetchMock.mock.calls[0]!;
  180. expect(JSON.parse(String((requestInit as RequestInit).body))).toEqual({
  181. event_id: "452a978b-d926-4a65-9c07-b04344a307d0",
  182. client_timezone: "Asia/Shanghai",
  183. client_language: "zh-CN",
  184. element_name: "app_launch",
  185. event_region: "app",
  186. event_type: "view",
  187. event_text: "",
  188. event_extra_detail: {},
  189. user_id: "60171703486074334",
  190. screen_resolution: "3024x1964",
  191. app_version: "0.25.1",
  192. device_os_category: "macos",
  193. device_os_version: "13.7.8",
  194. // device_mid 现已独立于 event_id 生成(见 ensureDeviceMid);此处因注入的
  195. // randomUUID 为常量函数,两次调用同值,故与 event_id 恰好相等。
  196. device_mid: "452a978b-d926-4a65-9c07-b04344a307d0",
  197. mac_id: "",
  198. marketing_params: "{}",
  199. });
  200. });
  201. it("attaches marketing_params to every report payload", async () => {
  202. const home = makeTempHome();
  203. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  204. const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status: 204 }));
  205. const service = createTelemetryCore({
  206. homeDir: home,
  207. fetchImpl: fetchMock,
  208. loadMarketingParams: async () => ({
  209. channel_id: "douyin",
  210. utm_source: "wechat",
  211. utm_campaign: "summer_sale_2026",
  212. }),
  213. randomUUID: () => "marketing-event-id",
  214. });
  215. const context = {
  216. clientTimezone: "Asia/Shanghai",
  217. clientLanguage: "zh-CN",
  218. screenResolution: "3024x1964",
  219. };
  220. await service.reportAppLaunch(context);
  221. await service.reportEvent({
  222. context,
  223. elementName: "button_click",
  224. eventRegion: "app",
  225. eventType: "click",
  226. eventExtraDetail: {},
  227. });
  228. expect(fetchMock).toHaveBeenCalledTimes(2);
  229. for (const [, init] of fetchMock.mock.calls) {
  230. expect(JSON.parse(String((init as RequestInit).body))).toMatchObject({
  231. marketing_params:
  232. '{"channel_id":"douyin","utm_source":"wechat","utm_campaign":"summer_sale_2026"}',
  233. });
  234. }
  235. });
  236. it("continues reporting without attribution and warns once when attribution loading fails", async () => {
  237. const home = makeTempHome();
  238. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  239. const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status: 204 }));
  240. const warn = vi.fn();
  241. const service = createTelemetryCore({
  242. homeDir: home,
  243. fetchImpl: fetchMock,
  244. loadMarketingParams: async () => {
  245. throw new Error("credential unavailable");
  246. },
  247. warn,
  248. randomUUID: () => "marketing-load-failure-event-id",
  249. });
  250. const context = {
  251. clientTimezone: "Asia/Shanghai",
  252. clientLanguage: "zh-CN",
  253. screenResolution: "3024x1964",
  254. };
  255. await service.reportAppLaunch(context);
  256. await service.reportEvent({
  257. context,
  258. elementName: "button_click",
  259. eventRegion: "app",
  260. eventType: "click",
  261. eventExtraDetail: {},
  262. });
  263. expect(fetchMock).toHaveBeenCalledTimes(2);
  264. expect(warn).toHaveBeenCalledTimes(1);
  265. expect(warn).toHaveBeenCalledWith(
  266. "Telemetry marketing attribution load failed; continuing without attribution",
  267. );
  268. for (const [, init] of fetchMock.mock.calls) {
  269. expect(JSON.parse(String((init as RequestInit).body))).toMatchObject({
  270. marketing_params: "{}",
  271. });
  272. }
  273. });
  274. it("uses injected user id loader instead of credential storage details", async () => {
  275. const home = makeTempHome();
  276. process.env.HOME = home;
  277. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  278. const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status: 204 }));
  279. const loadUserId = vi.fn(async () => "60171703486074334");
  280. const service = createTelemetryCore({
  281. fetchImpl: fetchMock,
  282. loadUserId,
  283. randomUUID: () => "event-with-loader",
  284. appVersion: "0.25.1",
  285. platform: "darwin",
  286. osVersion: "13.7.8",
  287. }) as {
  288. reportAppLaunch(context: {
  289. clientTimezone: string;
  290. clientLanguage: string;
  291. screenResolution: string;
  292. }): Promise<void>;
  293. };
  294. await service.reportAppLaunch({
  295. clientTimezone: "Asia/Shanghai",
  296. clientLanguage: "zh-CN",
  297. screenResolution: "3024x1964",
  298. });
  299. expect(loadUserId).toHaveBeenCalledTimes(1);
  300. const [, requestInit] = fetchMock.mock.calls[0]!;
  301. expect(JSON.parse(String((requestInit as RequestInit).body))).toMatchObject({
  302. user_id: "60171703486074334",
  303. });
  304. });
  305. it("does not write local logs when sending telemetry reports", async () => {
  306. const home = makeTempHome();
  307. process.env.HOME = home;
  308. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  309. const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status: 204 }));
  310. const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  311. const service = createTelemetryCore({
  312. loadUserId: async () => "60171703486074334",
  313. fetchImpl: fetchMock,
  314. randomUUID: () => "telemetry-log-event-id",
  315. appVersion: "0.25.1",
  316. platform: "darwin",
  317. osVersion: "13.7.8",
  318. }) as {
  319. reportAppLaunch(context: {
  320. clientTimezone: string;
  321. clientLanguage: string;
  322. screenResolution: string;
  323. }): Promise<void>;
  324. };
  325. await service.reportAppLaunch({
  326. clientTimezone: "Asia/Shanghai",
  327. clientLanguage: "zh-CN",
  328. screenResolution: "3024x1964",
  329. });
  330. expect(fetchMock).toHaveBeenCalledTimes(1);
  331. expect(consoleSpy).not.toHaveBeenCalled();
  332. });
  333. it("reports custom telemetry events with optional talk and message ids", async () => {
  334. const home = makeTempHome();
  335. process.env.HOME = home;
  336. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  337. const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status: 204 }));
  338. const service = createTelemetryCore({
  339. loadUserId: async () => "loaded-user-id",
  340. fetchImpl: fetchMock,
  341. randomUUID: () => "custom-event-id",
  342. appVersion: "0.25.1",
  343. platform: "darwin",
  344. osVersion: "13.7.8",
  345. }) as {
  346. reportEvent(input: {
  347. context: {
  348. clientTimezone: string;
  349. clientLanguage: string;
  350. screenResolution: string;
  351. };
  352. elementName: string;
  353. eventRegion: string;
  354. eventType: string;
  355. eventExtraDetail: Record<string, string>;
  356. userId?: string;
  357. talkId?: string;
  358. messageId?: string;
  359. }): Promise<void>;
  360. };
  361. await service.reportEvent({
  362. context: {
  363. clientTimezone: "Asia/Shanghai",
  364. clientLanguage: "zh-CN",
  365. screenResolution: "3024x1964",
  366. },
  367. elementName: "send_btn",
  368. eventRegion: "app",
  369. eventType: "ck",
  370. eventExtraDetail: {
  371. input_start_time: "1710000000000",
  372. input_first_char_time: "1710000000100",
  373. input_send_time: "1710000000200",
  374. },
  375. userId: "override-user-id",
  376. talkId: "task-001",
  377. messageId: "message-001",
  378. });
  379. expect(fetchMock).toHaveBeenCalledTimes(1);
  380. const [, requestInit] = fetchMock.mock.calls[0]!;
  381. expect(JSON.parse(String((requestInit as RequestInit).body))).toEqual({
  382. event_id: "custom-event-id",
  383. client_timezone: "Asia/Shanghai",
  384. client_language: "zh-CN",
  385. element_name: "send_btn",
  386. event_region: "app",
  387. event_type: "ck",
  388. event_text: "",
  389. event_extra_detail: {
  390. input_start_time: "1710000000000",
  391. input_first_char_time: "1710000000100",
  392. input_send_time: "1710000000200",
  393. },
  394. user_id: "override-user-id",
  395. screen_resolution: "3024x1964",
  396. app_version: "0.25.1",
  397. device_os_category: "macos",
  398. device_os_version: "13.7.8",
  399. // device_mid 独立生成,此处因常量 mock 与 event_id 恰好相等(见上方说明)
  400. device_mid: "custom-event-id",
  401. mac_id: "",
  402. marketing_params: "{}",
  403. talk_id: "task-001",
  404. message_id: "message-001",
  405. });
  406. });
  407. it("reports app_daily_active at most once per local day", async () => {
  408. const home = makeTempHome();
  409. process.env.HOME = home;
  410. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  411. const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status: 204 }));
  412. const context = {
  413. clientTimezone: "Asia/Shanghai",
  414. clientLanguage: "zh-CN",
  415. screenResolution: "3024x1964",
  416. };
  417. const service = createTelemetryCore({
  418. fetchImpl: fetchMock,
  419. randomUUID: () => "event-dau-1",
  420. now: () => Date.UTC(2026, 3, 2, 10, 0, 0),
  421. }) as {
  422. reportAppDailyActive(input: typeof context): Promise<void>;
  423. };
  424. await service.reportAppDailyActive(context);
  425. await service.reportAppDailyActive(context);
  426. expect(fetchMock).toHaveBeenCalledTimes(1);
  427. const nextDayService = createTelemetryCore({
  428. fetchImpl: fetchMock,
  429. randomUUID: () => "event-dau-2",
  430. now: () => Date.UTC(2026, 3, 3, 10, 0, 0),
  431. }) as {
  432. reportAppDailyActive(input: typeof context): Promise<void>;
  433. };
  434. await nextDayService.reportAppDailyActive(context);
  435. expect(fetchMock).toHaveBeenCalledTimes(2);
  436. const [, requestInit] = fetchMock.mock.calls[1]!;
  437. expect(JSON.parse(String((requestInit as RequestInit).body))).toMatchObject({
  438. event_id: "event-dau-2",
  439. element_name: "app_daily_active",
  440. });
  441. });
  442. it("uses client timezone instead of UTC when deduplicating daily active events", async () => {
  443. const home = makeTempHome();
  444. process.env.HOME = home;
  445. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  446. const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status: 204 }));
  447. const context = {
  448. clientTimezone: "Asia/Shanghai",
  449. clientLanguage: "zh-CN",
  450. screenResolution: "3024x1964",
  451. };
  452. const lateNightService = createTelemetryCore({
  453. fetchImpl: fetchMock,
  454. randomUUID: () => "event-local-1",
  455. now: () => Date.UTC(2026, 3, 2, 15, 30, 0),
  456. }) as {
  457. reportAppDailyActive(input: typeof context): Promise<void>;
  458. };
  459. await lateNightService.reportAppDailyActive(context);
  460. const afterMidnightService = createTelemetryCore({
  461. fetchImpl: fetchMock,
  462. randomUUID: () => "event-local-2",
  463. now: () => Date.UTC(2026, 3, 2, 16, 30, 0),
  464. }) as {
  465. reportAppDailyActive(input: typeof context): Promise<void>;
  466. };
  467. await afterMidnightService.reportAppDailyActive(context);
  468. expect(fetchMock).toHaveBeenCalledTimes(2);
  469. const [, requestInit] = fetchMock.mock.calls[1]!;
  470. expect(JSON.parse(String((requestInit as RequestInit).body))).toMatchObject({
  471. event_id: "event-local-2",
  472. element_name: "app_daily_active",
  473. });
  474. });
  475. it("does not mark daily active as sent when the report endpoint returns non-2xx", async () => {
  476. const home = makeTempHome();
  477. process.env.HOME = home;
  478. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  479. const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  480. const fetchMock = vi
  481. .fn<typeof fetch>()
  482. .mockResolvedValueOnce(new Response("server error", { status: 500 }))
  483. .mockResolvedValueOnce(new Response("server error", { status: 500 }))
  484. .mockResolvedValueOnce(new Response(null, { status: 204 }));
  485. const context = {
  486. clientTimezone: "Asia/Shanghai",
  487. clientLanguage: "zh-CN",
  488. screenResolution: "3024x1964",
  489. };
  490. const service = createTelemetryCore({
  491. fetchImpl: fetchMock,
  492. randomUUID: () => "event-retry-1",
  493. now: () => Date.UTC(2026, 3, 2, 10, 0, 0),
  494. }) as {
  495. reportAppDailyActive(input: typeof context): Promise<void>;
  496. };
  497. await expect(service.reportAppDailyActive(context)).rejects.toThrow(/500/);
  498. expect(fetchMock).toHaveBeenCalledTimes(2);
  499. await service.reportAppDailyActive(context);
  500. expect(fetchMock).toHaveBeenCalledTimes(3);
  501. expect(consoleSpy).not.toHaveBeenCalled();
  502. await service.reportAppDailyActive(context);
  503. expect(fetchMock).toHaveBeenCalledTimes(3);
  504. });
  505. it("deduplicates concurrent daily active reports across service instances", async () => {
  506. const home = makeTempHome();
  507. process.env.HOME = home;
  508. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  509. let releaseFetch: (() => void) | null = null;
  510. const fetchStarted = new Promise<void>((resolve) => {
  511. releaseFetch = resolve;
  512. });
  513. const fetchMock = vi.fn<typeof fetch>().mockImplementation(async () => {
  514. await fetchStarted;
  515. return new Response(null, { status: 204 });
  516. });
  517. const context = {
  518. clientTimezone: "Asia/Shanghai",
  519. clientLanguage: "zh-CN",
  520. screenResolution: "3024x1964",
  521. };
  522. const firstService = createTelemetryCore({
  523. fetchImpl: fetchMock,
  524. randomUUID: () => "event-concurrent-1",
  525. now: () => Date.UTC(2026, 3, 2, 10, 0, 0),
  526. }) as {
  527. reportAppDailyActive(input: typeof context): Promise<void>;
  528. };
  529. const secondService = createTelemetryCore({
  530. fetchImpl: fetchMock,
  531. randomUUID: () => "event-concurrent-2",
  532. now: () => Date.UTC(2026, 3, 2, 10, 0, 0),
  533. }) as {
  534. reportAppDailyActive(input: typeof context): Promise<void>;
  535. };
  536. const firstPromise = firstService.reportAppDailyActive(context);
  537. await Promise.resolve();
  538. const secondPromise = secondService.reportAppDailyActive(context);
  539. await waitForCalls(fetchMock, 1);
  540. releaseFetch?.();
  541. await Promise.all([firstPromise, secondPromise]);
  542. expect(fetchMock).toHaveBeenCalledTimes(1);
  543. });
  544. it("does not block app_launch while daily active reporting is in flight", async () => {
  545. const home = makeTempHome();
  546. process.env.HOME = home;
  547. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  548. let releaseDailyActive: (() => void) | null = null;
  549. const dailyActiveGate = new Promise<void>((resolve) => {
  550. releaseDailyActive = resolve;
  551. });
  552. const fetchMock = vi
  553. .fn<typeof fetch>()
  554. .mockImplementationOnce(async () => {
  555. await dailyActiveGate;
  556. return new Response(null, { status: 204 });
  557. })
  558. .mockResolvedValueOnce(new Response(null, { status: 204 }));
  559. const context = {
  560. clientTimezone: "Asia/Shanghai",
  561. clientLanguage: "zh-CN",
  562. screenResolution: "3024x1964",
  563. };
  564. const dailyActiveService = createTelemetryCore({
  565. fetchImpl: fetchMock,
  566. randomUUID: () => "event-daily-active",
  567. now: () => Date.UTC(2026, 3, 2, 10, 0, 0),
  568. }) as {
  569. reportAppDailyActive(input: typeof context): Promise<void>;
  570. };
  571. const appLaunchService = createTelemetryCore({
  572. fetchImpl: fetchMock,
  573. randomUUID: () => "event-app-launch",
  574. now: () => Date.UTC(2026, 3, 2, 10, 0, 0),
  575. }) as {
  576. reportAppLaunch(input: typeof context): Promise<void>;
  577. };
  578. const dailyActivePromise = dailyActiveService.reportAppDailyActive(context);
  579. await waitForCalls(fetchMock, 1);
  580. const appLaunchPromise = appLaunchService.reportAppLaunch(context);
  581. await waitForCalls(fetchMock, 2);
  582. releaseDailyActive?.();
  583. await Promise.all([dailyActivePromise, appLaunchPromise]);
  584. const dailyActiveBody = JSON.parse(String(fetchMock.mock.calls[0]![1]!.body));
  585. const appLaunchBody = JSON.parse(String(fetchMock.mock.calls[1]![1]!.body));
  586. expect(fetchMock).toHaveBeenCalledTimes(2);
  587. expect(dailyActiveBody.element_name).toBe("app_daily_active");
  588. expect(appLaunchBody.element_name).toBe("app_launch");
  589. });
  590. it("recovers from a stale telemetry lock file", async () => {
  591. const home = makeTempHome();
  592. process.env.HOME = home;
  593. const lockFile = join(home, ".zcode", "v2", "telemetry-state.lock");
  594. mkdirSync(join(home, ".zcode", "v2"), { recursive: true });
  595. writeFileSync(lockFile, "", "utf-8");
  596. const staleAt = new Date(Date.UTC(2026, 3, 1, 0, 0, 0));
  597. utimesSync(lockFile, staleAt, staleAt);
  598. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  599. const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status: 204 }));
  600. const service = createTelemetryCore({
  601. fetchImpl: fetchMock,
  602. randomUUID: () => "launch-after-stale-lock",
  603. now: () => Date.UTC(2026, 3, 2, 10, 0, 0),
  604. }) as {
  605. reportAppLaunch(input: {
  606. clientTimezone: string;
  607. clientLanguage: string;
  608. screenResolution: string;
  609. }): Promise<void>;
  610. };
  611. await service.reportAppLaunch({
  612. clientTimezone: "Asia/Shanghai",
  613. clientLanguage: "zh-CN",
  614. screenResolution: "3024x1964",
  615. });
  616. expect(fetchMock).toHaveBeenCalledTimes(1);
  617. });
  618. it("recovers from a fresh telemetry lock owned by a dead process", async () => {
  619. const home = makeTempHome();
  620. process.env.HOME = home;
  621. const lockFile = join(home, ".zcode", "v2", "telemetry-state.lock");
  622. mkdirSync(join(home, ".zcode", "v2"), { recursive: true });
  623. writeFileSync(
  624. lockFile,
  625. JSON.stringify({
  626. pid: 99999999,
  627. createdAt: Date.UTC(2026, 3, 2, 10, 0, 0),
  628. }),
  629. "utf-8",
  630. );
  631. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  632. const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status: 204 }));
  633. const service = createTelemetryCore({
  634. fetchImpl: fetchMock,
  635. randomUUID: () => "launch-after-dead-owner-lock",
  636. now: () => Date.UTC(2026, 3, 2, 10, 0, 1),
  637. }) as {
  638. reportAppLaunch(input: {
  639. clientTimezone: string;
  640. clientLanguage: string;
  641. screenResolution: string;
  642. }): Promise<void>;
  643. };
  644. await service.reportAppLaunch({
  645. clientTimezone: "Asia/Shanghai",
  646. clientLanguage: "zh-CN",
  647. screenResolution: "3024x1964",
  648. });
  649. expect(fetchMock).toHaveBeenCalledTimes(1);
  650. });
  651. it("does not reacquire the state lock for every custom event after device_mid is cached", async () => {
  652. const home = makeTempHome();
  653. process.env.HOME = home;
  654. const stateDir = join(home, ".zcode", "v2");
  655. mkdirSync(stateDir, { recursive: true });
  656. writeFileSync(
  657. join(stateDir, "telemetry-state.json"),
  658. JSON.stringify({ deviceMid: "cached-device-mid" }),
  659. "utf-8",
  660. );
  661. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  662. const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  663. const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status: 204 }));
  664. const service = createTelemetryCore({
  665. fetchImpl: fetchMock,
  666. randomUUID: () => "cached-event-id",
  667. }) as {
  668. reportEvent(input: {
  669. context: {
  670. clientTimezone: string;
  671. clientLanguage: string;
  672. screenResolution: string;
  673. };
  674. elementName: string;
  675. eventRegion: string;
  676. eventType: string;
  677. eventExtraDetail: Record<string, string>;
  678. }): Promise<void>;
  679. };
  680. const context = {
  681. clientTimezone: "Asia/Shanghai",
  682. clientLanguage: "zh-CN",
  683. screenResolution: "3024x1964",
  684. };
  685. await Promise.all(
  686. Array.from({ length: 500 }, (_, index) =>
  687. service.reportEvent({
  688. context,
  689. elementName: "agent_step",
  690. eventRegion: "app",
  691. eventType: "agent_trace",
  692. eventExtraDetail: { index: String(index) },
  693. }),
  694. ),
  695. );
  696. expect(consoleSpy).not.toHaveBeenCalled();
  697. expect(fetchMock).toHaveBeenCalledTimes(500);
  698. });
  699. it("persists a stable device_mid across service restarts, decoupled from event_id", async () => {
  700. const home = makeTempHome();
  701. process.env.HOME = home;
  702. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  703. const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status: 204 }));
  704. const context = {
  705. clientTimezone: "Asia/Shanghai",
  706. clientLanguage: "zh-CN",
  707. screenResolution: "3024x1964",
  708. };
  709. // 每次实例用自增序列,使 event_id 与 device_mid 取到不同值:device_mid 已与首条
  710. // 事件的 eventId 解耦(独立 randomUUID),仅靠落盘复用保持跨重启稳定。
  711. function sequentialUuid(prefix: string): () => string {
  712. let counter = 0;
  713. return () => `${prefix}-${(counter += 1)}`;
  714. }
  715. const firstService = createTelemetryCore({
  716. fetchImpl: fetchMock,
  717. randomUUID: sequentialUuid("first"),
  718. }) as {
  719. reportAppLaunch(input: typeof context): Promise<void>;
  720. };
  721. await firstService.reportAppLaunch(context);
  722. const secondService = createTelemetryCore({
  723. fetchImpl: fetchMock,
  724. randomUUID: sequentialUuid("second"),
  725. }) as {
  726. reportAppLaunch(input: typeof context): Promise<void>;
  727. };
  728. await secondService.reportAppLaunch(context);
  729. const firstBody = JSON.parse(String(fetchMock.mock.calls[0]![1]!.body));
  730. const secondBody = JSON.parse(String(fetchMock.mock.calls[1]![1]!.body));
  731. // 首次:eventId=first-1,device_mid 是另一次独立调用 first-2(已解耦,不再相等)
  732. expect(firstBody.event_id).toBe("first-1");
  733. expect(firstBody.device_mid).toBe("first-2");
  734. // 重启:eventId 重新生成 second-1,device_mid 复用落盘值 first-2(跨重启稳定)
  735. expect(secondBody.event_id).toBe("second-1");
  736. expect(secondBody.device_mid).toBe("first-2");
  737. const telemetryStateFile = join(home, ".zcode", "v2", "telemetry-state.json");
  738. const telemetryState = JSON.parse(readFileSync(telemetryStateFile, "utf-8")) as {
  739. deviceMid: string;
  740. };
  741. expect(telemetryState.deviceMid).toBe("first-2");
  742. });
  743. it("keeps an existing persisted device_mid (back-compat with legacy event-id values)", async () => {
  744. const home = makeTempHome();
  745. process.env.HOME = home;
  746. // 老版本把首条事件的 eventId 当作 device_mid 落盘;新逻辑必须原样复用,不得突变
  747. const stateDir = join(home, ".zcode", "v2");
  748. mkdirSync(stateDir, { recursive: true });
  749. writeFileSync(
  750. join(stateDir, "telemetry-state.json"),
  751. JSON.stringify({ deviceMid: "legacy-event-id-from-old-version" }),
  752. "utf-8",
  753. );
  754. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  755. const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status: 204 }));
  756. const service = createTelemetryCore({
  757. fetchImpl: fetchMock,
  758. randomUUID: () => "fresh-event-id",
  759. }) as {
  760. reportAppLaunch(input: {
  761. clientTimezone: string;
  762. clientLanguage: string;
  763. screenResolution: string;
  764. }): Promise<void>;
  765. };
  766. await service.reportAppLaunch({
  767. clientTimezone: "Asia/Shanghai",
  768. clientLanguage: "zh-CN",
  769. screenResolution: "3024x1964",
  770. });
  771. const body = JSON.parse(String(fetchMock.mock.calls[0]![1]!.body));
  772. expect(body.device_mid).toBe("legacy-event-id-from-old-version");
  773. expect(body.event_id).toBe("fresh-event-id");
  774. });
  775. });