desktopWindowLifecycle.test.ts 23 KB

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