desktopWindowLifecycle.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. vi.mock("../src/main/databaseStartupRelay.js", () => ({
  3. getDatabaseStartupPortPayload: () => ({ databaseStartupId: "window-host-test" }),
  4. }));
  5. vi.mock("electron", () => ({
  6. app: {
  7. setBadgeCount: vi.fn(),
  8. dock: undefined,
  9. },
  10. BrowserWindow: {
  11. fromId: vi.fn(),
  12. },
  13. Menu: {
  14. buildFromTemplate: vi.fn(() => ({ setMenu: vi.fn() })),
  15. },
  16. MessageChannelMain: class MessageChannelMain {
  17. readonly port1 = { id: "port-1" };
  18. readonly port2 = { id: "port-2" };
  19. },
  20. }));
  21. vi.mock("../src/main/desktopWindowChrome.js", () => ({
  22. createBrowserWindow: vi.fn(),
  23. }));
  24. vi.mock("../src/main/armsBrowserPerfLoadNudge.js", () => ({
  25. scheduleArmsBrowserPerfLoadNudge: vi.fn(),
  26. }));
  27. import { handleDarwinWindowCloseRequest } from "../src/main/desktopDarwinCloseBehavior.js";
  28. import { createBrowserWindow } from "../src/main/desktopWindowChrome.js";
  29. import {
  30. createWindow,
  31. handleDesktopWindowCloseRequest,
  32. } from "../src/main/desktopWindowLifecycle.js";
  33. describe("desktopWindowLifecycle createWindow", () => {
  34. afterEach(() => {
  35. vi.useRealTimers();
  36. });
  37. it("local Host 始终携带 conversation backing cwd 供历史 workspace spawn 兜底", () => {
  38. let handleDomReady: (() => void) | undefined;
  39. const webContents = {
  40. id: 42,
  41. on: vi.fn((event: string, listener: () => void) => {
  42. if (event === "dom-ready") handleDomReady = listener;
  43. }),
  44. };
  45. const win = {
  46. id: 7,
  47. webContents,
  48. on: vi.fn(),
  49. isDestroyed: vi.fn(() => false),
  50. show: vi.fn(),
  51. focus: vi.fn(),
  52. };
  53. vi.mocked(createBrowserWindow).mockReturnValue(win as never);
  54. const child = { pid: 1234 };
  55. const spawnHostProcess = vi.fn(() => child as never);
  56. const fallbackCwd = "/Users/demo/.zcode/workspace/default";
  57. createWindow({
  58. iconPath: "/tmp/icon.png",
  59. preloadPath: "/tmp/preload.js",
  60. logger: { info: vi.fn(), warn: vi.fn() },
  61. forceQuitRef: { current: false },
  62. windowHostProcessMap: new Map(),
  63. spawnHostProcess,
  64. disposeHostProcess: vi.fn(),
  65. syncAutoUpdaterStateToWindow: vi.fn(),
  66. syncReadyUpdateToWindow: vi.fn(),
  67. syncPostUpdateReleaseNotesToWindow: vi.fn(),
  68. webRemoteControlManager: { disposeWindow: vi.fn(async () => undefined) },
  69. disposeRemoteWorkspaceSessionsForWindow: vi.fn(),
  70. reattachRemoteWorkspaceSessionsForWindow: vi.fn(),
  71. agentWarmupTargets: [
  72. { workspacePath: "/Users/demo/active-project" },
  73. { workspacePath: "/Users/demo/recent-a" },
  74. { workspacePath: "/Users/demo/recent-b" },
  75. ],
  76. agentSpawnFallbackCwd: fallbackCwd,
  77. deviceMid: "device-mid",
  78. runtimeProcessEnvFallbackPatch: {},
  79. });
  80. expect(handleDomReady).toBeTypeOf("function");
  81. handleDomReady?.();
  82. expect(spawnHostProcess).toHaveBeenCalledWith(
  83. win,
  84. "local-42",
  85. expect.objectContaining({
  86. type: "init-local",
  87. workspacePath: "/Users/demo/active-project",
  88. agentWarmupTargets: [
  89. { workspacePath: "/Users/demo/active-project" },
  90. { workspacePath: "/Users/demo/recent-a" },
  91. { workspacePath: "/Users/demo/recent-b" },
  92. ],
  93. agentSpawnFallbackCwd: fallbackCwd,
  94. runtimeProcessEnvPatch: {},
  95. }),
  96. );
  97. });
  98. it("InitLocal 携带 spawn 时刻 Main 的实时界面语言", () => {
  99. let handleDomReady: (() => void) | undefined;
  100. const webContents = {
  101. id: 43,
  102. on: vi.fn((event: string, listener: () => void) => {
  103. if (event === "dom-ready") handleDomReady = listener;
  104. }),
  105. };
  106. const win = {
  107. id: 8,
  108. webContents,
  109. on: vi.fn(),
  110. isDestroyed: vi.fn(() => false),
  111. show: vi.fn(),
  112. focus: vi.fn(),
  113. };
  114. vi.mocked(createBrowserWindow).mockReturnValue(win as never);
  115. const spawnHostProcess = vi.fn(() => ({ pid: 1238 }) as never);
  116. let locale: "zh-CN" | "en-US" = "en-US";
  117. createWindow({
  118. iconPath: "/tmp/icon.png",
  119. preloadPath: "/tmp/preload.js",
  120. logger: { info: vi.fn(), warn: vi.fn() },
  121. forceQuitRef: { current: false },
  122. windowHostProcessMap: new Map(),
  123. spawnHostProcess,
  124. disposeHostProcess: vi.fn(),
  125. syncAutoUpdaterStateToWindow: vi.fn(),
  126. syncReadyUpdateToWindow: vi.fn(),
  127. syncPostUpdateReleaseNotesToWindow: vi.fn(),
  128. webRemoteControlManager: { disposeWindow: vi.fn(async () => undefined) },
  129. disposeRemoteWorkspaceSessionsForWindow: vi.fn(),
  130. reattachRemoteWorkspaceSessionsForWindow: vi.fn(),
  131. agentSpawnFallbackCwd: "/Users/dev/.zcode/workspace/default",
  132. deviceMid: "device-mid",
  133. runtimeProcessEnvFallbackPatch: {},
  134. currentApplicationLocale: () => locale,
  135. });
  136. // 窗口创建后、Host spawn 前切换语言,InitLocal 必须读到切换后的值。
  137. locale = "zh-CN";
  138. handleDomReady?.();
  139. expect(spawnHostProcess).toHaveBeenCalledWith(
  140. win,
  141. "local-43",
  142. expect.objectContaining({ type: "init-local", locale: "zh-CN" }),
  143. );
  144. });
  145. it("等待提前采集的 runtime env 完成后再创建 Local Host", async () => {
  146. let handleDomReady: (() => void) | undefined;
  147. let resolveRuntimeEnv: ((patch: Record<string, string>) => void) | undefined;
  148. const runtimeProcessEnvPatchPromise = new Promise<Record<string, string>>((resolve) => {
  149. resolveRuntimeEnv = resolve;
  150. });
  151. const webContents = {
  152. id: 43,
  153. on: vi.fn((event: string, listener: () => void) => {
  154. if (event === "dom-ready") handleDomReady = listener;
  155. }),
  156. };
  157. const win = {
  158. id: 8,
  159. webContents,
  160. on: vi.fn(),
  161. isDestroyed: vi.fn(() => false),
  162. show: vi.fn(),
  163. focus: vi.fn(),
  164. };
  165. vi.mocked(createBrowserWindow).mockReturnValue(win as never);
  166. const spawnHostProcess = vi.fn(() => ({ pid: 1235 }) as never);
  167. createWindow({
  168. iconPath: "/tmp/icon.png",
  169. preloadPath: "/tmp/preload.js",
  170. logger: { info: vi.fn(), warn: vi.fn() },
  171. forceQuitRef: { current: false },
  172. windowHostProcessMap: new Map(),
  173. spawnHostProcess,
  174. disposeHostProcess: vi.fn(),
  175. syncAutoUpdaterStateToWindow: vi.fn(),
  176. syncReadyUpdateToWindow: vi.fn(),
  177. syncPostUpdateReleaseNotesToWindow: vi.fn(),
  178. webRemoteControlManager: { disposeWindow: vi.fn(async () => undefined) },
  179. disposeRemoteWorkspaceSessionsForWindow: vi.fn(),
  180. reattachRemoteWorkspaceSessionsForWindow: vi.fn(),
  181. agentSpawnFallbackCwd: "/Users/demo/.zcode/workspace/default",
  182. deviceMid: "device-mid",
  183. runtimeProcessEnvPatchPromise,
  184. runtimeProcessEnvFallbackPatch: {},
  185. });
  186. handleDomReady?.();
  187. expect(spawnHostProcess).not.toHaveBeenCalled();
  188. resolveRuntimeEnv?.({ PATH: "/Users/demo/.local/bin:/usr/bin:/bin" });
  189. await runtimeProcessEnvPatchPromise;
  190. await Promise.resolve();
  191. expect(spawnHostProcess).toHaveBeenCalledWith(
  192. win,
  193. "local-43",
  194. expect.objectContaining({
  195. type: "init-local",
  196. runtimeProcessEnvPatch: {
  197. PATH: "/Users/demo/.local/bin:/usr/bin:/bin",
  198. },
  199. }),
  200. );
  201. });
  202. it("renderer reload 复用已有 Host 时不等待 runtime env prewarm", () => {
  203. let handleDomReady: (() => void) | undefined;
  204. const webContents = {
  205. id: 44,
  206. on: vi.fn((event: string, listener: () => void) => {
  207. if (event === "dom-ready") handleDomReady = listener;
  208. }),
  209. postMessage: vi.fn(),
  210. };
  211. const win = {
  212. id: 9,
  213. webContents,
  214. on: vi.fn(),
  215. isDestroyed: vi.fn(() => false),
  216. show: vi.fn(),
  217. focus: vi.fn(),
  218. };
  219. vi.mocked(createBrowserWindow).mockReturnValue(win as never);
  220. const existingChild = { pid: 1236, postMessage: vi.fn() };
  221. const spawnHostProcess = vi.fn();
  222. const syncAutoUpdaterStateToWindow = vi.fn();
  223. const reattachRemoteWorkspaceSessionsForWindow = vi.fn();
  224. createWindow({
  225. iconPath: "/tmp/icon.png",
  226. preloadPath: "/tmp/preload.js",
  227. logger: { info: vi.fn(), warn: vi.fn() },
  228. forceQuitRef: { current: false },
  229. windowHostProcessMap: new Map([[44, existingChild as never]]),
  230. spawnHostProcess,
  231. disposeHostProcess: vi.fn(),
  232. syncAutoUpdaterStateToWindow,
  233. syncReadyUpdateToWindow: vi.fn(),
  234. syncPostUpdateReleaseNotesToWindow: vi.fn(),
  235. webRemoteControlManager: { disposeWindow: vi.fn(async () => undefined) },
  236. disposeRemoteWorkspaceSessionsForWindow: vi.fn(),
  237. reattachRemoteWorkspaceSessionsForWindow,
  238. agentSpawnFallbackCwd: "/Users/demo/.zcode/workspace/default",
  239. deviceMid: "device-mid",
  240. runtimeProcessEnvPatchPromise: new Promise(() => {}),
  241. runtimeProcessEnvFallbackPatch: {},
  242. });
  243. handleDomReady?.();
  244. expect(existingChild.postMessage).toHaveBeenCalledWith(
  245. expect.objectContaining({ type: "attach-service-port" }),
  246. [expect.objectContaining({ id: "port-2" })],
  247. );
  248. expect(webContents.postMessage).toHaveBeenCalledWith(
  249. "zcode:service-port",
  250. { databaseStartupId: "window-host-test" },
  251. [expect.objectContaining({ id: "port-1" })],
  252. );
  253. expect(spawnHostProcess).not.toHaveBeenCalled();
  254. expect(syncAutoUpdaterStateToWindow).toHaveBeenCalledWith(win);
  255. expect(reattachRemoteWorkspaceSessionsForWindow).toHaveBeenCalledWith(
  256. win,
  257. "local-44:renderer-reload",
  258. );
  259. });
  260. it("runtime env 永不完成时按 deadline 使用 fallback,迟到结果不重复创建 Host", async () => {
  261. vi.useFakeTimers();
  262. let handleDomReady: (() => void) | undefined;
  263. let resolveRuntimeEnv: ((patch: Record<string, string>) => void) | undefined;
  264. const runtimeProcessEnvPatchPromise = new Promise<Record<string, string>>((resolve) => {
  265. resolveRuntimeEnv = resolve;
  266. });
  267. const webContents = {
  268. id: 45,
  269. on: vi.fn((event: string, listener: () => void) => {
  270. if (event === "dom-ready") handleDomReady = listener;
  271. }),
  272. };
  273. const win = {
  274. id: 10,
  275. webContents,
  276. on: vi.fn(),
  277. isDestroyed: vi.fn(() => false),
  278. show: vi.fn(),
  279. focus: vi.fn(),
  280. };
  281. vi.mocked(createBrowserWindow).mockReturnValue(win as never);
  282. const spawnHostProcess = vi.fn(() => ({ pid: 1237 }) as never);
  283. const fallbackPatch = { PATH: "/usr/local/bin:/usr/bin:/bin" };
  284. createWindow({
  285. iconPath: "/tmp/icon.png",
  286. preloadPath: "/tmp/preload.js",
  287. logger: { info: vi.fn(), warn: vi.fn() },
  288. forceQuitRef: { current: false },
  289. windowHostProcessMap: new Map(),
  290. spawnHostProcess,
  291. disposeHostProcess: vi.fn(),
  292. syncAutoUpdaterStateToWindow: vi.fn(),
  293. syncReadyUpdateToWindow: vi.fn(),
  294. syncPostUpdateReleaseNotesToWindow: vi.fn(),
  295. webRemoteControlManager: { disposeWindow: vi.fn(async () => undefined) },
  296. disposeRemoteWorkspaceSessionsForWindow: vi.fn(),
  297. reattachRemoteWorkspaceSessionsForWindow: vi.fn(),
  298. agentSpawnFallbackCwd: "/Users/demo/.zcode/workspace/default",
  299. deviceMid: "device-mid",
  300. runtimeProcessEnvPatchPromise,
  301. runtimeProcessEnvFallbackPatch: fallbackPatch,
  302. runtimeProcessEnvWaitTimeoutMs: 50,
  303. });
  304. handleDomReady?.();
  305. await vi.advanceTimersByTimeAsync(49);
  306. expect(spawnHostProcess).not.toHaveBeenCalled();
  307. await vi.advanceTimersByTimeAsync(1);
  308. expect(spawnHostProcess).toHaveBeenCalledTimes(1);
  309. expect(spawnHostProcess).toHaveBeenCalledWith(
  310. win,
  311. "local-45",
  312. expect.objectContaining({ runtimeProcessEnvPatch: fallbackPatch }),
  313. );
  314. resolveRuntimeEnv?.({ PATH: "/Users/demo/.local/bin:/usr/bin:/bin" });
  315. await Promise.resolve();
  316. expect(spawnHostProcess).toHaveBeenCalledTimes(1);
  317. });
  318. it("runtime env prewarm reject 时仍传完整 fallback,不触发 Host 同步采集", async () => {
  319. let handleDomReady: (() => void) | undefined;
  320. const webContents = {
  321. id: 46,
  322. on: vi.fn((event: string, listener: () => void) => {
  323. if (event === "dom-ready") handleDomReady = listener;
  324. }),
  325. };
  326. const win = {
  327. id: 11,
  328. webContents,
  329. on: vi.fn(),
  330. isDestroyed: vi.fn(() => false),
  331. show: vi.fn(),
  332. focus: vi.fn(),
  333. };
  334. vi.mocked(createBrowserWindow).mockReturnValue(win as never);
  335. const spawnHostProcess = vi.fn(() => ({ pid: 1238 }) as never);
  336. const fallbackPatch = { PATH: "/usr/local/bin:/usr/bin:/bin" };
  337. createWindow({
  338. iconPath: "/tmp/icon.png",
  339. preloadPath: "/tmp/preload.js",
  340. logger: { info: vi.fn(), warn: vi.fn() },
  341. forceQuitRef: { current: false },
  342. windowHostProcessMap: new Map(),
  343. spawnHostProcess,
  344. disposeHostProcess: vi.fn(),
  345. syncAutoUpdaterStateToWindow: vi.fn(),
  346. syncReadyUpdateToWindow: vi.fn(),
  347. syncPostUpdateReleaseNotesToWindow: vi.fn(),
  348. webRemoteControlManager: { disposeWindow: vi.fn(async () => undefined) },
  349. disposeRemoteWorkspaceSessionsForWindow: vi.fn(),
  350. reattachRemoteWorkspaceSessionsForWindow: vi.fn(),
  351. agentSpawnFallbackCwd: "/Users/demo/.zcode/workspace/default",
  352. deviceMid: "device-mid",
  353. runtimeProcessEnvPatchPromise: Promise.reject(new Error("profile failed")),
  354. runtimeProcessEnvFallbackPatch: fallbackPatch,
  355. runtimeProcessEnvWaitTimeoutMs: 50,
  356. });
  357. handleDomReady?.();
  358. await Promise.resolve();
  359. await Promise.resolve();
  360. expect(spawnHostProcess).toHaveBeenCalledWith(
  361. win,
  362. "local-46",
  363. expect.objectContaining({ runtimeProcessEnvPatch: fallbackPatch }),
  364. );
  365. });
  366. it("首个 Local Host 创建前等待灰度裁决门,resolve 后才 spawn", async () => {
  367. // CR-01 Local 路径回归:dom-ready 触发后,spawnHostProcess 必须等到
  368. // awaitFirstHostSpawnDecision resolve 之后才被调用,确保首个 Host env 写入的是
  369. // 服务端裁决真值而非冷启动默认 false。
  370. let handleDomReady: (() => void) | undefined;
  371. let resolveGate!: () => void;
  372. const gatePromise = new Promise<void>((resolve) => {
  373. resolveGate = resolve;
  374. });
  375. const awaitFirstHostSpawnDecision = vi.fn(() => gatePromise);
  376. const webContents = {
  377. id: 47,
  378. on: vi.fn((event: string, listener: () => void) => {
  379. if (event === "dom-ready") handleDomReady = listener;
  380. }),
  381. };
  382. const win = {
  383. id: 12,
  384. webContents,
  385. on: vi.fn(),
  386. isDestroyed: vi.fn(() => false),
  387. show: vi.fn(),
  388. focus: vi.fn(),
  389. };
  390. vi.mocked(createBrowserWindow).mockReturnValue(win as never);
  391. const spawnHostProcess = vi.fn(() => ({ pid: 1239 }) as never);
  392. createWindow({
  393. iconPath: "/tmp/icon.png",
  394. preloadPath: "/tmp/preload.js",
  395. logger: { info: vi.fn(), warn: vi.fn() },
  396. forceQuitRef: { current: false },
  397. windowHostProcessMap: new Map(),
  398. spawnHostProcess,
  399. disposeHostProcess: vi.fn(),
  400. syncAutoUpdaterStateToWindow: vi.fn(),
  401. syncReadyUpdateToWindow: vi.fn(),
  402. syncPostUpdateReleaseNotesToWindow: vi.fn(),
  403. webRemoteControlManager: { disposeWindow: vi.fn(async () => undefined) },
  404. disposeRemoteWorkspaceSessionsForWindow: vi.fn(),
  405. reattachRemoteWorkspaceSessionsForWindow: vi.fn(),
  406. agentSpawnFallbackCwd: "/Users/demo/.zcode/workspace/default",
  407. deviceMid: "device-mid",
  408. runtimeProcessEnvFallbackPatch: {},
  409. awaitFirstHostSpawnDecision,
  410. });
  411. handleDomReady?.();
  412. // 裁决门未 resolve 前,dom-ready handler 在 await 处挂起,绝不创建 Host。
  413. expect(awaitFirstHostSpawnDecision).toHaveBeenCalledOnce();
  414. expect(spawnHostProcess).not.toHaveBeenCalled();
  415. resolveGate();
  416. // flush microtasks:handler 越过 await,走 sync fallback 路径 spawn。
  417. await new Promise((resolve) => {
  418. setTimeout(resolve, 0);
  419. });
  420. expect(spawnHostProcess).toHaveBeenCalledWith(
  421. win,
  422. "local-47",
  423. expect.objectContaining({ type: "init-local" }),
  424. );
  425. });
  426. });
  427. describe("desktopWindowLifecycle handleDarwinWindowCloseRequest", () => {
  428. it("全屏时点击关闭应只退出全屏", () => {
  429. const logger = {
  430. info: vi.fn(),
  431. };
  432. const win = {
  433. isFullScreen: vi.fn(() => true),
  434. setFullScreen: vi.fn(),
  435. hide: vi.fn(),
  436. };
  437. const prevented = handleDarwinWindowCloseRequest({
  438. win,
  439. forceQuit: false,
  440. label: "local-1",
  441. logger,
  442. });
  443. expect(prevented).toBe(true);
  444. expect(win.setFullScreen).toHaveBeenCalledTimes(1);
  445. expect(win.setFullScreen).toHaveBeenCalledWith(false);
  446. expect(win.hide).not.toHaveBeenCalled();
  447. expect(logger.info).toHaveBeenCalledWith(
  448. "[createWindow] fullscreen close converted to leave-full-screen (local-1)",
  449. );
  450. });
  451. it("非全屏时点击关闭仍然隐藏窗口", () => {
  452. const logger = {
  453. info: vi.fn(),
  454. };
  455. const win = {
  456. isFullScreen: vi.fn(() => false),
  457. setFullScreen: vi.fn(),
  458. hide: vi.fn(),
  459. };
  460. const prevented = handleDarwinWindowCloseRequest({
  461. win,
  462. forceQuit: false,
  463. label: "local-2",
  464. logger,
  465. });
  466. expect(prevented).toBe(true);
  467. expect(win.hide).toHaveBeenCalledTimes(1);
  468. expect(win.setFullScreen).not.toHaveBeenCalled();
  469. expect(logger.info).toHaveBeenCalledWith(
  470. "[createWindow] window hidden instead of closed (local-2)",
  471. );
  472. });
  473. it("应用主动退出时不拦截关闭", () => {
  474. const logger = {
  475. info: vi.fn(),
  476. };
  477. const win = {
  478. isFullScreen: vi.fn(() => true),
  479. setFullScreen: vi.fn(),
  480. hide: vi.fn(),
  481. };
  482. const prevented = handleDarwinWindowCloseRequest({
  483. win,
  484. forceQuit: true,
  485. label: "local-3",
  486. logger,
  487. });
  488. expect(prevented).toBe(false);
  489. expect(win.hide).not.toHaveBeenCalled();
  490. expect(win.setFullScreen).not.toHaveBeenCalled();
  491. expect(logger.info).not.toHaveBeenCalled();
  492. });
  493. });
  494. describe("desktopWindowLifecycle handleDesktopWindowCloseRequest", () => {
  495. it("prevents closing when the last Windows window cancel is chosen", () => {
  496. const logger = {
  497. info: vi.fn(),
  498. };
  499. const confirmQuit = vi.fn(() => false);
  500. const requestQuit = vi.fn();
  501. const prevented = handleDesktopWindowCloseRequest({
  502. platform: "win32",
  503. forceQuit: false,
  504. closeToTraySupported: true,
  505. isLastWindow: true,
  506. label: "local-4",
  507. logger,
  508. confirmQuit,
  509. requestQuit,
  510. });
  511. expect(prevented).toBe(true);
  512. expect(confirmQuit).toHaveBeenCalledTimes(1);
  513. expect(requestQuit).not.toHaveBeenCalled();
  514. expect(logger.info).toHaveBeenCalledWith(
  515. "[createWindow] last window close canceled by user (local-4)",
  516. );
  517. });
  518. it("requests app quit when the last Windows window close is confirmed", () => {
  519. const logger = {
  520. info: vi.fn(),
  521. };
  522. const confirmQuit = vi.fn(() => true);
  523. const requestQuit = vi.fn();
  524. const prevented = handleDesktopWindowCloseRequest({
  525. platform: "win32",
  526. forceQuit: false,
  527. closeToTraySupported: true,
  528. isLastWindow: true,
  529. label: "local-5",
  530. logger,
  531. confirmQuit,
  532. requestQuit,
  533. });
  534. expect(prevented).toBe(true);
  535. expect(confirmQuit).toHaveBeenCalledTimes(1);
  536. expect(requestQuit).toHaveBeenCalledTimes(1);
  537. expect(logger.info).toHaveBeenCalledWith(
  538. "[createWindow] last window close confirmed, quitting app (local-5)",
  539. );
  540. });
  541. it("skips quit confirmation when confirmation is disabled", () => {
  542. const logger = {
  543. info: vi.fn(),
  544. };
  545. const confirmQuit = vi.fn(() => false);
  546. const requestQuit = vi.fn();
  547. const prevented = handleDesktopWindowCloseRequest({
  548. platform: "win32",
  549. forceQuit: false,
  550. closeToTraySupported: true,
  551. isLastWindow: true,
  552. label: "local-7",
  553. logger,
  554. shouldConfirmQuit: false,
  555. confirmQuit,
  556. requestQuit,
  557. });
  558. expect(prevented).toBe(true);
  559. expect(confirmQuit).not.toHaveBeenCalled();
  560. expect(requestQuit).toHaveBeenCalledTimes(1);
  561. expect(logger.info).toHaveBeenCalledWith(
  562. "[createWindow] last window close skipped confirmation, quitting app (local-7)",
  563. );
  564. });
  565. it("does not confirm quit when another window remains open", () => {
  566. const logger = {
  567. info: vi.fn(),
  568. };
  569. const confirmQuit = vi.fn(() => true);
  570. const requestQuit = vi.fn();
  571. const prevented = handleDesktopWindowCloseRequest({
  572. platform: "win32",
  573. forceQuit: false,
  574. closeToTraySupported: true,
  575. isLastWindow: false,
  576. label: "local-6",
  577. logger,
  578. confirmQuit,
  579. requestQuit,
  580. });
  581. expect(prevented).toBe(false);
  582. expect(confirmQuit).not.toHaveBeenCalled();
  583. expect(requestQuit).not.toHaveBeenCalled();
  584. });
  585. it("hides linux window to tray when tray is supported and close-to-tray enabled", () => {
  586. const logger = { info: vi.fn() };
  587. const hideWindow = vi.fn();
  588. const confirmQuit = vi.fn(() => true);
  589. const requestQuit = vi.fn();
  590. const prevented = handleDesktopWindowCloseRequest({
  591. platform: "linux",
  592. forceQuit: false,
  593. closeToTray: true,
  594. closeToTraySupported: true,
  595. isLastWindow: true,
  596. label: "local-linux-tray",
  597. logger,
  598. confirmQuit,
  599. requestQuit,
  600. hideWindow,
  601. });
  602. expect(prevented).toBe(true);
  603. expect(hideWindow).toHaveBeenCalledTimes(1);
  604. expect(confirmQuit).not.toHaveBeenCalled();
  605. expect(requestQuit).not.toHaveBeenCalled();
  606. });
  607. it("treats missing linux tray capability as unsupported and falls back to quit confirmation", () => {
  608. const logger = { info: vi.fn() };
  609. const hideWindow = vi.fn();
  610. const confirmQuit = vi.fn(() => true);
  611. const requestQuit = vi.fn();
  612. // 能力未探测完成(缓存为空)与探测失败都必须走安全默认,绝不能隐藏窗口导致失联。
  613. for (const closeToTraySupported of [undefined, false] as const) {
  614. hideWindow.mockClear();
  615. confirmQuit.mockClear();
  616. requestQuit.mockClear();
  617. const prevented = handleDesktopWindowCloseRequest({
  618. platform: "linux",
  619. forceQuit: false,
  620. closeToTray: true,
  621. closeToTraySupported,
  622. isLastWindow: true,
  623. label: "local-linux-no-tray",
  624. logger,
  625. confirmQuit,
  626. requestQuit,
  627. hideWindow,
  628. });
  629. expect(prevented).toBe(true);
  630. expect(hideWindow).not.toHaveBeenCalled();
  631. expect(confirmQuit).toHaveBeenCalledTimes(1);
  632. expect(requestQuit).toHaveBeenCalledTimes(1);
  633. }
  634. });
  635. it("hides windows window to tray on the happy path when tray instance is ready", () => {
  636. const logger = { info: vi.fn() };
  637. const hideWindow = vi.fn();
  638. const confirmQuit = vi.fn(() => true);
  639. const requestQuit = vi.fn();
  640. const prevented = handleDesktopWindowCloseRequest({
  641. platform: "win32",
  642. forceQuit: false,
  643. closeToTray: true,
  644. closeToTraySupported: true,
  645. isLastWindow: true,
  646. label: "local-win32-tray",
  647. logger,
  648. confirmQuit,
  649. requestQuit,
  650. hideWindow,
  651. });
  652. expect(prevented).toBe(true);
  653. expect(hideWindow).toHaveBeenCalledTimes(1);
  654. expect(confirmQuit).not.toHaveBeenCalled();
  655. expect(requestQuit).not.toHaveBeenCalled();
  656. });
  657. it("does not hide windows window when tray instance failed to create", () => {
  658. const logger = { info: vi.fn() };
  659. const hideWindow = vi.fn();
  660. const confirmQuit = vi.fn(() => true);
  661. const requestQuit = vi.fn();
  662. // CR:win32 托盘创建失败(trayReady=false)时隐藏即失联,必须走确认退出。
  663. const prevented = handleDesktopWindowCloseRequest({
  664. platform: "win32",
  665. forceQuit: false,
  666. closeToTray: true,
  667. closeToTraySupported: false,
  668. isLastWindow: true,
  669. label: "local-win32-no-tray",
  670. logger,
  671. confirmQuit,
  672. requestQuit,
  673. hideWindow,
  674. });
  675. expect(prevented).toBe(true);
  676. expect(hideWindow).not.toHaveBeenCalled();
  677. expect(confirmQuit).toHaveBeenCalledTimes(1);
  678. expect(requestQuit).toHaveBeenCalledTimes(1);
  679. });
  680. it("falls back to quit confirmation on linux when close-to-tray setting is off", () => {
  681. const logger = { info: vi.fn() };
  682. const hideWindow = vi.fn();
  683. const confirmQuit = vi.fn(() => false);
  684. const requestQuit = vi.fn();
  685. const prevented = handleDesktopWindowCloseRequest({
  686. platform: "linux",
  687. forceQuit: false,
  688. closeToTray: false,
  689. closeToTraySupported: true,
  690. isLastWindow: true,
  691. label: "local-linux-off",
  692. logger,
  693. confirmQuit,
  694. requestQuit,
  695. hideWindow,
  696. });
  697. expect(prevented).toBe(true);
  698. expect(hideWindow).not.toHaveBeenCalled();
  699. expect(confirmQuit).toHaveBeenCalledTimes(1);
  700. });
  701. });