windowsInstallResourceLocks.test.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { describe, expect, it, vi } from "vitest";
  5. import {
  6. findWindowsProcessesReferencingResourceMarkers,
  7. isWindowsProcessReferencingResourceMarkers,
  8. probeWindowsPackagedResourceWritable,
  9. resolveWindowsPackagedResourceLockMarkers,
  10. runWindowsUpdateProcessCleanup,
  11. snapshotWindowsPackagedResources,
  12. } from "../src/main/windowsInstallResourceLocks.js";
  13. describe("windows install resource locks", () => {
  14. it.runIf(process.platform === "win32")(
  15. "does not report the PowerShell query process as a resource lock",
  16. async () => {
  17. // 修复原因:marker 会直接出现在 powershell.exe 的 -Command 参数里;如果脚本排除的是
  18. // Electron PID 而不是 PowerShell 自身 PID,扫描器必然把自己误报为资源占用进程。
  19. const uniqueMarker = `zcode-process-scan-self-${process.pid}-${Date.now()}`;
  20. await expect(
  21. // CI/开发机的 WMI 在高负载时可能超过生产 3 秒 fail-open 边界;测试只放宽
  22. // 查询等待,不改变产品更新路径的超时策略。
  23. findWindowsProcessesReferencingResourceMarkers([uniqueMarker], 10_000),
  24. ).resolves.toEqual([]);
  25. },
  26. );
  27. it("builds markers for packaged runtime resource directories", () => {
  28. const resourcesPath = join(
  29. "C:",
  30. "Users",
  31. "demo",
  32. "AppData",
  33. "Local",
  34. "Programs",
  35. "ZCode",
  36. "resources",
  37. );
  38. expect(resolveWindowsPackagedResourceLockMarkers(resourcesPath)).toEqual([
  39. join(resourcesPath, "glm"),
  40. join(resourcesPath, "tools"),
  41. ]);
  42. });
  43. it("matches resource paths regardless of slash direction or case", () => {
  44. const markers = ["C:\\Users\\demo\\AppData\\Local\\Programs\\ZCode\\resources\\glm"];
  45. expect(
  46. isWindowsProcessReferencingResourceMarkers(
  47. {
  48. pid: 42,
  49. commandLine:
  50. '"C:/Users/demo/AppData/Local/Programs/ZCode/ZCode.exe" "C:/Users/demo/AppData/Local/Programs/ZCode/resources/GLM/zcode-agent.exe"',
  51. },
  52. markers,
  53. ),
  54. ).toBe(true);
  55. });
  56. it("does not match unrelated processes", () => {
  57. const markers = ["C:\\Users\\demo\\AppData\\Local\\Programs\\ZCode\\resources\\glm"];
  58. expect(
  59. isWindowsProcessReferencingResourceMarkers(
  60. {
  61. pid: 108,
  62. commandLine: '"C:\\Windows\\System32\\notepad.exe"',
  63. executablePath: "C:\\Windows\\System32\\notepad.exe",
  64. },
  65. markers,
  66. ),
  67. ).toBe(false);
  68. });
  69. it("snapshots packaged resource dirs without throwing on missing dirs", () => {
  70. const root = mkdtempSync(join(tmpdir(), "zcode-resource-snapshot-"));
  71. try {
  72. const toolsDir = join(root, "tools");
  73. mkdirSync(toolsDir, { recursive: true });
  74. writeFileSync(join(toolsDir, "rg"), "binary", "utf8");
  75. const snapshot = snapshotWindowsPackagedResources(root);
  76. expect(snapshot.find((entry) => entry.dir === "tools")).toMatchObject({
  77. path: toolsDir,
  78. exists: true,
  79. entries: ["rg"],
  80. });
  81. expect(snapshot.find((entry) => entry.dir === "glm")).toMatchObject({
  82. exists: false,
  83. entries: [],
  84. });
  85. } finally {
  86. rmSync(root, { recursive: true, force: true });
  87. }
  88. });
  89. it("probes packaged resource dirs with writable and missing states", () => {
  90. const root = mkdtempSync(join(tmpdir(), "zcode-resource-probe-"));
  91. try {
  92. const glmDir = join(root, "glm");
  93. mkdirSync(glmDir, { recursive: true });
  94. const probes = probeWindowsPackagedResourceWritable(root);
  95. expect(probes.find((entry) => entry.dir === "glm")).toMatchObject({
  96. path: glmDir,
  97. exists: true,
  98. writable: true,
  99. });
  100. expect(probes.find((entry) => entry.dir === "tools")).toMatchObject({
  101. exists: false,
  102. writable: false,
  103. });
  104. } finally {
  105. rmSync(root, { recursive: true, force: true });
  106. }
  107. });
  108. it("terminates only processes still verified against packaged resources", async () => {
  109. const marker = "C:\\ZCode\\resources\\glm";
  110. const scan = vi
  111. .fn()
  112. .mockResolvedValueOnce([
  113. // 模拟退出屏障前的 Host PID=10 已退出,随后被无关记事本进程复用。
  114. {
  115. pid: 10,
  116. commandLine: '"C:\\Windows\\System32\\notepad.exe"',
  117. },
  118. {
  119. pid: 30,
  120. commandLine: `"${marker}\\zcode-agent.exe"`,
  121. },
  122. {
  123. pid: 30,
  124. executablePath: `${marker}\\zcode-agent.exe`,
  125. },
  126. ])
  127. .mockResolvedValueOnce([]);
  128. const terminate = vi.fn(async (pids: number[]) => pids.map((pid) => ({ pid })));
  129. const delay = vi.fn(async () => {});
  130. const result = await runWindowsUpdateProcessCleanup({
  131. resourceLockMarkers: [marker],
  132. lockReleaseGraceMs: 300,
  133. scan,
  134. terminate,
  135. delay,
  136. });
  137. expect(result.terminationPids).toEqual([30]);
  138. expect(terminate).toHaveBeenCalledWith([30]);
  139. expect(delay).toHaveBeenCalledWith(300);
  140. expect(scan).toHaveBeenCalledTimes(2);
  141. expect(result.errors).toEqual([]);
  142. });
  143. it("keeps update cleanup fail-open when scan or taskkill fails", async () => {
  144. const marker = "C:\\ZCode\\resources\\glm";
  145. const scan = vi
  146. .fn()
  147. .mockResolvedValueOnce([
  148. {
  149. pid: 10,
  150. executablePath: `${marker}\\zcode-agent.exe`,
  151. },
  152. ])
  153. .mockRejectedValueOnce(new Error("rescan timeout"));
  154. const terminate = vi.fn(async () => {
  155. throw new Error("taskkill failed");
  156. });
  157. const result = await runWindowsUpdateProcessCleanup({
  158. resourceLockMarkers: [marker],
  159. lockReleaseGraceMs: 300,
  160. scan,
  161. terminate,
  162. delay: async () => {},
  163. });
  164. expect(result.terminationPids).toEqual([10]);
  165. expect(result.remainingLockProcesses).toEqual([]);
  166. expect(result.errors).toEqual(["terminate: taskkill failed", "rescan: rescan timeout"]);
  167. });
  168. it("does not terminate historical pids when the live scan fails", async () => {
  169. const terminate = vi.fn(async () => []);
  170. const result = await runWindowsUpdateProcessCleanup({
  171. resourceLockMarkers: ["C:\\ZCode\\resources\\glm"],
  172. lockReleaseGraceMs: 300,
  173. scan: async () => {
  174. throw new Error("powershell timeout");
  175. },
  176. terminate,
  177. delay: async () => {},
  178. });
  179. expect(result.terminationPids).toEqual([]);
  180. expect(terminate).not.toHaveBeenCalled();
  181. expect(result.errors).toEqual(["initial-scan: powershell timeout"]);
  182. });
  183. });