useComposerAttachmentsAddToChatGate.test.ts 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import { act, createElement } from "react";
  2. import { createRoot } from "react-dom/client";
  3. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  4. import type { IPromptAttachmentTransferService } from "@zcode/services";
  5. import { useComposerAttachmentUploadStore } from "@/store/composerAttachmentUploadStore.js";
  6. import {
  7. useComposerAttachments,
  8. type ComposerAttachmentsApi,
  9. } from "@/v4/composer/useComposerAttachments.js";
  10. import {
  11. dispatchWhiteboardAddToChat,
  12. WHITEBOARD_ADD_TO_CHAT_EVENT,
  13. } from "@/lib/whiteboard.js";
  14. const mocks = vi.hoisted(() => ({
  15. platform: {
  16. canSelectFilePath: true,
  17. createTempTextAttachment: vi.fn(),
  18. getPathForFile: vi.fn(),
  19. selectFiles: vi.fn(async () => [] as string[]),
  20. },
  21. service: null as IPromptAttachmentTransferService | null,
  22. }));
  23. vi.mock("@/hooks/usePlatform.js", () => ({
  24. usePlatform: () => mocks.platform,
  25. }));
  26. vi.mock("@/hooks/useServices.js", () => ({
  27. useServices: () => ({ promptAttachmentTransferService: mocks.service }),
  28. }));
  29. vi.mock("@/i18n/IntlProvider.js", () => ({
  30. useZCodeIntl: () => ({
  31. intl: {
  32. formatMessage: ({ id }: { id: string }) => id,
  33. },
  34. }),
  35. }));
  36. // 复刻 useComposerAttachmentsUpload.test.ts 的 DOM shim:window/document 都是 EventTarget,
  37. // 保证 window.dispatchEvent(CustomEvent) 能驱动 hook 内的 add-to-chat 监听。
  38. function createMinimalElement(ownerDocument: Document) {
  39. const element = {
  40. addEventListener: () => {},
  41. appendChild: (child: Node) => {
  42. Object.assign(child, { parentNode: element });
  43. element.childNodes.push(child);
  44. return child;
  45. },
  46. attributes: new Map<string, string>(),
  47. childNodes: [] as Node[],
  48. getAttribute: (name: string) => element.attributes.get(name) ?? null,
  49. insertBefore: (child: Node) => element.appendChild(child),
  50. nodeName: "DIV",
  51. nodeType: 1,
  52. ownerDocument,
  53. parentNode: null,
  54. removeAttribute: (name: string) => element.attributes.delete(name),
  55. removeChild: (child: Node) => {
  56. element.childNodes = element.childNodes.filter((item) => item !== child);
  57. return child;
  58. },
  59. removeEventListener: () => {},
  60. setAttribute: (name: string, value: string) => element.attributes.set(name, value),
  61. style: {},
  62. tagName: "DIV",
  63. };
  64. return element as unknown as Element;
  65. }
  66. function installMinimalDom() {
  67. const windowTarget = new EventTarget();
  68. const documentTarget = new EventTarget();
  69. const documentMock = {
  70. addEventListener: documentTarget.addEventListener.bind(documentTarget),
  71. createComment: () => ({ nodeType: 8, parentNode: null }),
  72. createElement: () => createMinimalElement(documentMock as unknown as Document),
  73. createTextNode: (nodeValue: string) => ({ nodeType: 3, nodeValue, parentNode: null }),
  74. defaultView: null as unknown,
  75. nodeType: 9,
  76. removeEventListener: documentTarget.removeEventListener.bind(documentTarget),
  77. };
  78. const windowMock = {
  79. addEventListener: windowTarget.addEventListener.bind(windowTarget),
  80. clearTimeout,
  81. dispatchEvent: windowTarget.dispatchEvent.bind(windowTarget),
  82. document: documentMock,
  83. HTMLIFrameElement: function HTMLIFrameElement() {},
  84. HTMLElement: function HTMLElement() {},
  85. Node: function Node() {},
  86. removeEventListener: windowTarget.removeEventListener.bind(windowTarget),
  87. setTimeout,
  88. };
  89. documentMock.defaultView = windowMock;
  90. Object.defineProperty(globalThis, "document", { configurable: true, value: documentMock });
  91. Object.defineProperty(globalThis, "window", { configurable: true, value: windowMock });
  92. Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
  93. configurable: true,
  94. value: true,
  95. });
  96. return createMinimalElement(documentMock as unknown as Document);
  97. }
  98. let latestApi: ComposerAttachmentsApi | null = null;
  99. function Probe({ listenAddToChatEvents }: { listenAddToChatEvents?: boolean }) {
  100. latestApi = useComposerAttachments({
  101. attachmentPut: vi.fn(),
  102. attachmentSessionId: null,
  103. // 模拟 SessionPane 的分屏/侧聊语义:只有聚焦 composer 传 listenAddToChatEvents=true。
  104. listenAddToChatEvents,
  105. scopeId: "add-to-chat-gate",
  106. workspacePath: "/workspace",
  107. });
  108. return null;
  109. }
  110. function renderProbe(options: { listenAddToChatEvents?: boolean }) {
  111. const root = createRoot(installMinimalDom());
  112. act(() => root.render(createElement(Probe, options)));
  113. return root;
  114. }
  115. function dispatchWhiteboardEvent() {
  116. return dispatchWhiteboardAddToChat({
  117. workspacePath: "/workspace",
  118. boardId: "board-missing",
  119. });
  120. }
  121. beforeEach(() => {
  122. latestApi = null;
  123. mocks.platform.createTempTextAttachment.mockReset();
  124. mocks.platform.getPathForFile.mockReset();
  125. mocks.platform.selectFiles.mockReset();
  126. useComposerAttachmentUploadStore.setState({ scopes: {} });
  127. });
  128. afterEach(async () => {
  129. vi.useRealTimers();
  130. useComposerAttachmentUploadStore.setState({ scopes: {} });
  131. // React 19 scheduler 会在 root.unmount() 后留一个 setImmediate 回调,先排空再删 DOM shim。
  132. await new Promise<void>((resolve) => setImmediate(resolve));
  133. delete (globalThis as { document?: unknown }).document;
  134. delete (globalThis as { window?: unknown }).window;
  135. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown }).IS_REACT_ACT_ENVIRONMENT;
  136. });
  137. describe("useComposerAttachments add-to-chat 门控", () => {
  138. it("listenAddToChatEvents=false 同样不消费 whiteboard 引用事件(pre-existing 同款收口)", () => {
  139. const root = renderProbe({ listenAddToChatEvents: false });
  140. let cancelled = false;
  141. act(() => {
  142. cancelled = dispatchWhiteboardEvent();
  143. });
  144. expect(cancelled).toBe(false);
  145. // boardId 不存在时接收方会设置 exportMissing 错误;未接收则保持 null。
  146. expect(latestApi?.attachmentError).toBeNull();
  147. act(() => root.unmount());
  148. });
  149. it("listenAddToChatEvents=true 时 whiteboard 引用事件仍被接收", () => {
  150. const root = renderProbe({ listenAddToChatEvents: true });
  151. let cancelled = false;
  152. act(() => {
  153. cancelled = dispatchWhiteboardEvent();
  154. });
  155. expect(cancelled).toBe(true);
  156. expect(latestApi?.attachmentError).toBe("whiteboard.exportMissing");
  157. act(() => root.unmount());
  158. });
  159. it("事件常量与监听名保持稳定", () => {
  160. expect(WHITEBOARD_ADD_TO_CHAT_EVENT).toBe("zcode:add-whiteboard-to-chat");
  161. });
  162. });