desktopNotifications.test.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. import { beforeEach, describe, expect, it, vi } from "vitest";
  2. import { PlatformChannels } from "@zcode/shared";
  3. const electronMocks = vi.hoisted(() => {
  4. const notificationInstances: NotificationMock[] = [];
  5. class NotificationMock {
  6. static isSupported = vi.fn(() => true);
  7. handlers = new Map<string, Array<() => void>>();
  8. once = vi.fn((event: string, handler: () => void) => {
  9. const handlers = this.handlers.get(event) ?? [];
  10. handlers.push(handler);
  11. this.handlers.set(event, handlers);
  12. return this;
  13. });
  14. show = vi.fn();
  15. constructor(public options: unknown) {
  16. notificationInstances.push(this);
  17. }
  18. emit(event: string) {
  19. const handlers = this.handlers.get(event) ?? [];
  20. this.handlers.delete(event);
  21. for (const handler of handlers) {
  22. handler();
  23. }
  24. }
  25. }
  26. return {
  27. appDockShow: vi.fn(),
  28. appFocus: vi.fn(),
  29. appShow: vi.fn(),
  30. browserWindowFromWebContents: vi.fn(),
  31. browserWindowGetAllWindows: vi.fn(() => []),
  32. NotificationMock,
  33. notificationInstances,
  34. };
  35. });
  36. vi.mock("electron", () => ({
  37. app: {
  38. dock: {
  39. show: electronMocks.appDockShow,
  40. },
  41. focus: electronMocks.appFocus,
  42. show: electronMocks.appShow,
  43. },
  44. BrowserWindow: {
  45. fromWebContents: electronMocks.browserWindowFromWebContents,
  46. getAllWindows: electronMocks.browserWindowGetAllWindows,
  47. },
  48. Notification: electronMocks.NotificationMock,
  49. }));
  50. import {
  51. dispatchTaskNotification,
  52. getActiveTaskNotificationCountForTest,
  53. resetActiveTaskNotificationsForTest,
  54. } from "../src/main/desktopNotifications.js";
  55. function createTaskNotificationPayload(taskId = "task-1") {
  56. return {
  57. taskId,
  58. status: "completed" as const,
  59. title: "测试任务完成",
  60. body: "可以回来看结果了",
  61. };
  62. }
  63. describe("desktop task notifications", () => {
  64. beforeEach(() => {
  65. electronMocks.NotificationMock.isSupported.mockReturnValue(true);
  66. electronMocks.notificationInstances.length = 0;
  67. electronMocks.appDockShow.mockClear();
  68. electronMocks.appFocus.mockClear();
  69. electronMocks.appShow.mockClear();
  70. electronMocks.browserWindowFromWebContents.mockReset();
  71. electronMocks.browserWindowGetAllWindows.mockReset();
  72. electronMocks.browserWindowGetAllWindows.mockReturnValue([]);
  73. resetActiveTaskNotificationsForTest();
  74. });
  75. it("does not generate fallback copy in main process when localized notification copy is missing", () => {
  76. const eventSender = {
  77. send: vi.fn(),
  78. };
  79. const logger = {
  80. info: vi.fn(),
  81. warn: vi.fn(),
  82. };
  83. const shown = dispatchTaskNotification({
  84. event: { sender: eventSender } as never,
  85. payload: {
  86. ...createTaskNotificationPayload("task-missing-copy"),
  87. title: " ",
  88. body: "",
  89. },
  90. logger,
  91. });
  92. expect(shown).toBe(false);
  93. expect(electronMocks.notificationInstances).toHaveLength(0);
  94. expect(eventSender.send).not.toHaveBeenCalledWith(PlatformChannels.TaskNotificationSound);
  95. expect(logger.warn).toHaveBeenCalledWith(
  96. "[show-task-notification] missing localized notification copy",
  97. {
  98. taskId: "task-missing-copy",
  99. status: "completed",
  100. hasTitle: false,
  101. hasBody: false,
  102. },
  103. );
  104. });
  105. it("keeps native notifications alive until the click handler can focus the task window", () => {
  106. const eventSender = {
  107. send: vi.fn(),
  108. };
  109. const senderWindow = {
  110. id: 7,
  111. isDestroyed: vi.fn(() => false),
  112. isMinimized: vi.fn(() => true),
  113. restore: vi.fn(),
  114. isVisible: vi.fn(() => false),
  115. show: vi.fn(),
  116. focus: vi.fn(),
  117. webContents: {
  118. send: vi.fn(),
  119. },
  120. };
  121. const logger = {
  122. info: vi.fn(),
  123. warn: vi.fn(),
  124. };
  125. electronMocks.browserWindowFromWebContents.mockReturnValue(senderWindow);
  126. const shown = dispatchTaskNotification({
  127. event: { sender: eventSender } as never,
  128. payload: createTaskNotificationPayload(),
  129. logger,
  130. });
  131. expect(shown).toBe(true);
  132. expect(getActiveTaskNotificationCountForTest()).toBe(1);
  133. expect(eventSender.send).toHaveBeenCalledWith(PlatformChannels.TaskNotificationSound);
  134. electronMocks.notificationInstances[0]?.emit("click");
  135. expect(getActiveTaskNotificationCountForTest()).toBe(0);
  136. expect(senderWindow.restore).toHaveBeenCalledTimes(1);
  137. expect(senderWindow.show).toHaveBeenCalledTimes(1);
  138. expect(senderWindow.focus).toHaveBeenCalledTimes(1);
  139. expect(senderWindow.webContents.send).toHaveBeenCalledWith(
  140. PlatformChannels.TaskNotificationClick,
  141. "task-1",
  142. );
  143. expect(logger.info).toHaveBeenCalledWith(
  144. "[show-task-notification] notification click handled",
  145. { taskId: "task-1", windowId: 7 },
  146. );
  147. expect(senderWindow.restore.mock.invocationCallOrder[0]).toBeLessThan(
  148. senderWindow.focus.mock.invocationCallOrder[0] ?? Number.MAX_SAFE_INTEGER,
  149. );
  150. if (process.platform === "darwin") {
  151. expect(electronMocks.appDockShow).toHaveBeenCalledTimes(1);
  152. expect(electronMocks.appShow).toHaveBeenCalledTimes(1);
  153. expect(electronMocks.appFocus).toHaveBeenCalledWith({ steal: true });
  154. expect(senderWindow.show.mock.invocationCallOrder[0]).toBeLessThan(
  155. electronMocks.appFocus.mock.invocationCallOrder[0] ?? Number.MAX_SAFE_INTEGER,
  156. );
  157. }
  158. });
  159. it("releases retained notifications when the OS closes them", () => {
  160. const eventSender = {
  161. send: vi.fn(),
  162. };
  163. electronMocks.browserWindowFromWebContents.mockReturnValue({
  164. webContents: {
  165. send: vi.fn(),
  166. },
  167. });
  168. dispatchTaskNotification({
  169. event: { sender: eventSender } as never,
  170. payload: createTaskNotificationPayload("task-closed-by-os"),
  171. logger: { info: vi.fn(), warn: vi.fn() },
  172. });
  173. expect(getActiveTaskNotificationCountForTest()).toBe(1);
  174. electronMocks.notificationInstances[0]?.emit("close");
  175. expect(getActiveTaskNotificationCountForTest()).toBe(0);
  176. });
  177. it("deduplicates elicitation notifications by request id instead of task id", () => {
  178. const eventSender = {
  179. send: vi.fn(),
  180. };
  181. const logger = {
  182. info: vi.fn(),
  183. warn: vi.fn(),
  184. };
  185. const firstShown = dispatchTaskNotification({
  186. event: { sender: eventSender } as never,
  187. payload: {
  188. taskId: "task-awaiting-user",
  189. status: "elicitation_request",
  190. requestId: "question-1",
  191. title: "需要你确认",
  192. body: "请回答当前问题",
  193. },
  194. logger,
  195. });
  196. const duplicateShown = dispatchTaskNotification({
  197. event: { sender: eventSender } as never,
  198. payload: {
  199. taskId: "task-awaiting-user",
  200. status: "elicitation_request",
  201. requestId: "question-1",
  202. title: "需要你确认",
  203. body: "请回答当前问题",
  204. },
  205. logger,
  206. });
  207. const nextRequestShown = dispatchTaskNotification({
  208. event: { sender: eventSender } as never,
  209. payload: {
  210. taskId: "task-awaiting-user",
  211. status: "elicitation_request",
  212. requestId: "question-2",
  213. title: "需要你确认",
  214. body: "请回答下一个问题",
  215. },
  216. logger,
  217. });
  218. expect(firstShown).toBe(true);
  219. expect(duplicateShown).toBe(false);
  220. expect(nextRequestShown).toBe(true);
  221. expect(electronMocks.notificationInstances).toHaveLength(2);
  222. expect(eventSender.send).toHaveBeenCalledTimes(2);
  223. expect(eventSender.send).toHaveBeenCalledWith(PlatformChannels.TaskNotificationSound);
  224. });
  225. });