mobileLogPullExport.test.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import { mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  5. import {
  6. MOBILE_LOG_PULL_DEFAULT_WINDOW_MS,
  7. pullAndExportMobileLogs,
  8. MobileLogPullError,
  9. type MobileLogPullExportDependencies,
  10. } from "#src/main/web-remote-relay/index.js";
  11. const NOW = new Date(2026, 9, 23, 10, 0, 0);
  12. describe("pullAndExportMobileLogs", () => {
  13. let exportDir: string;
  14. beforeEach(async () => {
  15. exportDir = await mkdtemp(join(tmpdir(), "zcode-mobile-log-export-"));
  16. });
  17. afterEach(async () => {
  18. await rm(exportDir, { recursive: true, force: true });
  19. });
  20. function deps(
  21. overrides: Partial<MobileLogPullExportDependencies>,
  22. ): MobileLogPullExportDependencies {
  23. return {
  24. findTarget: () => ({ windowId: 7, deviceLabel: "Pixel 8-android" }),
  25. pull: async () => {
  26. throw new Error("not stubbed");
  27. },
  28. exportDir,
  29. realtimeLogDir: "/tmp/realtime",
  30. locale: "zh-CN",
  31. now: () => NOW,
  32. showMessage: vi.fn(async () => 1),
  33. showItemInFolder: vi.fn(),
  34. logger: { info: vi.fn(), warn: vi.fn() },
  35. ...overrides,
  36. };
  37. }
  38. it("逐片写入 JSONL(header + 条目 + summary),点「打开所在文件夹」定位文件", async () => {
  39. const showMessage = vi.fn(async () => 0);
  40. const showItemInFolder = vi.fn();
  41. const pull = vi.fn<MobileLogPullExportDependencies["pull"]>(
  42. async (_windowId, _query, onShard) => {
  43. await onShard({
  44. entries: [{ ts: 1, level: "info", message: "a" }],
  45. sources: [],
  46. compressed: false,
  47. });
  48. await onShard({
  49. entries: [{ ts: 2, level: "warn", message: "b" }],
  50. sources: [],
  51. compressed: true,
  52. });
  53. return {
  54. requestId: "r",
  55. entryCount: 2,
  56. totalMatched: 2,
  57. shardCount: 2,
  58. compressedShardCount: 1,
  59. truncated: false,
  60. sources: [],
  61. };
  62. },
  63. );
  64. const result = await pullAndExportMobileLogs(
  65. undefined,
  66. deps({ pull, showMessage, showItemInFolder }),
  67. );
  68. expect(result.status).toBe("exported");
  69. if (result.status !== "exported") return;
  70. expect(result.path).toBe(join(exportDir, "mobile-logs-Pixel_8-android-20261023-100000.jsonl"));
  71. expect(pull.mock.calls[0]?.[0]).toBe(7);
  72. expect(pull.mock.calls[0]?.[1]).toMatchObject({
  73. sinceTs: NOW.getTime() - MOBILE_LOG_PULL_DEFAULT_WINDOW_MS,
  74. });
  75. const lines = (await readFile(result.path, "utf8"))
  76. .trim()
  77. .split("\n")
  78. .map((line) => JSON.parse(line));
  79. expect(lines.map((line) => line.kind ?? line.message)).toEqual([
  80. "mobile-log-pull",
  81. "a",
  82. "b",
  83. "mobile-log-pull-summary",
  84. ]);
  85. expect(showMessage).toHaveBeenCalledWith(
  86. expect.objectContaining({ type: "info", message: "已导出 2 条手机日志。" }),
  87. );
  88. expect(showItemInFolder).toHaveBeenCalledWith(result.path);
  89. });
  90. it("拉取日志统一 [web-remote-control] zcode_rc_log_pull_*,result 带 outcome/耗时/字节数/错误码", async () => {
  91. const info = vi.fn();
  92. const warn = vi.fn();
  93. await pullAndExportMobileLogs(
  94. 1,
  95. deps({
  96. logger: { info, warn },
  97. pull: async (_windowId, _query, onShard) => {
  98. await onShard({ entries: [{ ts: 1, level: "info" }], sources: [], compressed: false });
  99. throw new MobileLogPullError("timeout", "slow", 1);
  100. },
  101. }),
  102. );
  103. expect(info).toHaveBeenCalledWith(
  104. "[web-remote-control] zcode_rc_log_pull_start",
  105. expect.objectContaining({ window: 7 }),
  106. );
  107. const [message, fields] = warn.mock.calls.at(-1) ?? [];
  108. expect(message).toBe("[web-remote-control] zcode_rc_log_pull_result");
  109. expect(fields).toMatchObject({
  110. outcome: "error",
  111. error_code: "timeout",
  112. entries: 1,
  113. file: "mobile-logs-Pixel_8-android-20261023-100000.jsonl",
  114. });
  115. expect(fields.bytes).toBeGreaterThan(0);
  116. expect(fields.duration_ms).toBeGreaterThanOrEqual(0);
  117. });
  118. it("同名文件已存在时独占创建失败,不截断也不删除已有文件", async () => {
  119. const existing = join(exportDir, "mobile-logs-Pixel_8-android-20261023-100000.jsonl");
  120. await writeFile(existing, "other export\n");
  121. const result = await pullAndExportMobileLogs(
  122. 1,
  123. deps({
  124. pull: async (_windowId, _query, onShard) => {
  125. await onShard({ entries: [{ ts: 1, level: "info" }], sources: [], compressed: false });
  126. throw new Error("unreachable");
  127. },
  128. }),
  129. );
  130. expect(result).toMatchObject({ status: "failed", code: "invalid-shard" });
  131. expect(await readFile(existing, "utf8")).toBe("other export\n");
  132. });
  133. it("未配对时只弹提示,不创建文件", async () => {
  134. const showMessage = vi.fn(async () => 0);
  135. const result = await pullAndExportMobileLogs(
  136. 1,
  137. deps({ findTarget: () => undefined, showMessage, locale: "en-US" }),
  138. );
  139. expect(result).toMatchObject({ status: "failed", code: "not-paired" });
  140. expect(await readdir(exportDir)).toEqual([]);
  141. expect(showMessage).toHaveBeenCalledWith(
  142. expect.objectContaining({ type: "warning", buttons: ["OK"] }),
  143. );
  144. });
  145. it("手机不支持时删除空文件并提示升级", async () => {
  146. const showMessage = vi.fn(async () => 0);
  147. const result = await pullAndExportMobileLogs(
  148. 1,
  149. deps({
  150. pull: async () => {
  151. throw new MobileLogPullError("unsupported", "unknown zcode_type");
  152. },
  153. showMessage,
  154. }),
  155. );
  156. expect(result).toMatchObject({ status: "failed", code: "unsupported" });
  157. expect(result).not.toHaveProperty("path");
  158. expect(await readdir(exportDir)).toEqual([]);
  159. expect(showMessage).toHaveBeenCalledWith(
  160. expect.objectContaining({ message: expect.stringContaining("不支持日志拉取") }),
  161. );
  162. });
  163. it("中途失败但已写入条目时保留部分文件", async () => {
  164. const result = await pullAndExportMobileLogs(
  165. 1,
  166. deps({
  167. pull: async (_windowId, _query, onShard) => {
  168. await onShard({ entries: [{ ts: 1, level: "info" }], sources: [], compressed: false });
  169. throw new MobileLogPullError("timeout", "slow", 1);
  170. },
  171. }),
  172. );
  173. expect(result).toMatchObject({ status: "failed", code: "timeout" });
  174. if (result.status !== "failed" || !result.path) throw new Error("expected partial path");
  175. const content = await readFile(result.path, "utf8");
  176. expect(content.trim().split("\n")).toHaveLength(2);
  177. });
  178. });