rendererMessageHandler.test.ts 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. import { readFileSync } from "node:fs";
  2. import { join } from "node:path";
  3. import { describe, expect, it, vi, beforeEach } from "vitest";
  4. /**
  5. * 验证 renderer/main.tsx 中 handleServicePortMessage 的防重复 createRoot 逻辑:
  6. * 多次收到 ServicePort message 时只应初始化一次 React root。
  7. *
  8. * 这里不真正渲染 React,而是验证 createRoot 只被调用一次。
  9. */
  10. const createRootMock = vi.fn(() => ({
  11. render: vi.fn(),
  12. }));
  13. vi.mock("react-dom/client", () => ({
  14. createRoot: createRootMock,
  15. }));
  16. vi.mock("@zcode/ui", () => ({
  17. AppErrorBoundary: ({ children }: { children: unknown }) => children,
  18. Root: () => null,
  19. ZCodeIntlProvider: ({ children }: { children: unknown }) => children,
  20. registerBaseWorkspaceServices: vi.fn(),
  21. registerRemoteWorkspaceSession: vi.fn(),
  22. playTaskNotificationSound: vi.fn(() => Promise.resolve()),
  23. }));
  24. vi.mock("@zcode/client", () => ({
  25. connectViaMessagePort: vi.fn(() => ({
  26. settingService: {},
  27. })),
  28. }));
  29. // 模拟 window.zcode
  30. vi.stubGlobal("window", {
  31. ...globalThis.window,
  32. location: { search: "" },
  33. matchMedia: () => ({ matches: true }),
  34. zcode: {
  35. selectDirectory: vi.fn(),
  36. activateOrSetWorkspace: vi.fn(),
  37. connectRemote: vi.fn(),
  38. disposeRemoteSession: vi.fn(async () => {}),
  39. isDockerAvailable: vi.fn(async () => false),
  40. listWSLDistros: vi.fn(async () => []),
  41. listDockerContainers: vi.fn(async () => []),
  42. listSSHConfigAliases: vi.fn(async () => []),
  43. openExternal: vi.fn(),
  44. registerOAuthState: vi.fn(),
  45. onOAuthCallback: vi.fn(() => () => {}),
  46. notifyRendererReady: vi.fn(),
  47. reportTelemetryEvent: vi.fn(async () => {}),
  48. showTaskNotification: vi.fn(),
  49. syncWindowTabs: vi.fn(),
  50. syncWindowUnreadCount: vi.fn(),
  51. onFocusTab: vi.fn(() => () => {}),
  52. onNewTab: vi.fn(() => () => {}),
  53. onNewTask: vi.fn(() => () => {}),
  54. onOpenWorkspace: vi.fn(() => () => {}),
  55. onWindowFullscreenChanged: vi.fn(() => () => {}),
  56. onTaskNotificationClick: vi.fn(() => () => {}),
  57. exportLogs: vi.fn(),
  58. onUpdateReady: vi.fn(() => () => {}),
  59. onUpdateCheckResult: vi.fn(() => () => {}),
  60. quitAndInstallUpdate: vi.fn(async () => {}),
  61. getInstalledEditors: vi.fn(),
  62. openInEditor: vi.fn(),
  63. executeDesktopCommand: vi.fn(),
  64. setApplicationLocale: vi.fn(),
  65. setTitleBarTheme: vi.fn(),
  66. },
  67. addEventListener: vi.fn(),
  68. });
  69. vi.stubGlobal("document", {
  70. documentElement: { classList: { add: vi.fn() } },
  71. getElementById: vi.fn(() => ({})),
  72. });
  73. vi.stubGlobal("navigator", { userAgent: "Mac" });
  74. vi.stubGlobal("localStorage", {
  75. getItem: () => "dark",
  76. setItem: vi.fn(),
  77. });
  78. describe("renderer main.tsx 防重复 createRoot", () => {
  79. beforeEach(() => {
  80. createRootMock.mockClear();
  81. vi.resetModules();
  82. });
  83. it("handleServicePortMessage 是命名函数而非匿名函数", () => {
  84. // Bugfix: 这个断言只关心入口文件里是否保留了可复用的命名 handler,
  85. // 没必要在全量测试时把整个 renderer 入口都 import 起来。直接读源码能避开
  86. // 大量模块初始化带来的偶发超时,同时仍然能防回归。
  87. const source = readFileSync(join(import.meta.dirname, "../src/renderer/src/main.tsx"), "utf-8");
  88. expect(source).toContain("function handleServicePortMessage(event: MessageEvent): void");
  89. expect(source).toContain('window.addEventListener("message", handleServicePortMessage);');
  90. });
  91. it("onOpenWorkspace bridge 缺失时有无操作 disposer 兜底", () => {
  92. const source = readFileSync(
  93. join(import.meta.dirname, "../src/renderer/src/desktopPlatform.ts"),
  94. "utf-8",
  95. );
  96. expect(source).toContain("window.zcode.onOpenWorkspace?.(handler) ?? (() => {})");
  97. });
  98. it("remote workspace service port 早于 base ServicePort 时会暂存并在 base ready 后 flush", () => {
  99. const source = readFileSync(join(import.meta.dirname, "../src/renderer/src/main.tsx"), "utf-8");
  100. expect(source).toContain("const pendingRemoteWorkspaceServicePorts");
  101. expect(source).toContain("pendingRemoteWorkspaceServicePorts.push(remoteWorkspacePort);");
  102. expect(source).toContain("notifyRemoteWorkspaceServicePortReady(params);");
  103. expect(source).toContain("function flushPendingRemoteWorkspaceServicePorts(): void");
  104. expect(source).toContain("flushPendingRemoteWorkspaceServicePorts();");
  105. });
  106. it("desktop Root 暂时显式开启 Assistant code-comment 卡片", () => {
  107. const source = readFileSync(join(import.meta.dirname, "../src/renderer/src/main.tsx"), "utf-8");
  108. expect(source).toContain("isDesktop");
  109. expect(source).toContain("assistantCodeCommentCardsEnabled");
  110. });
  111. });