useComposerAttachmentsAddToChatGate.test.ts 6.3 KB

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