windowsInstallResourceLocks.test.ts 6.8 KB

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