webRemoteControlDialogLayout.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. // @vitest-environment jsdom
  2. import { readFileSync } from "node:fs";
  3. import { createElement, type ReactNode } from "react";
  4. import { renderToStaticMarkup } from "react-dom/server";
  5. import { cleanup, fireEvent, render, waitFor } from "@testing-library/react";
  6. import { afterEach, describe, expect, it, vi } from "vitest";
  7. import {
  8. WebRemoteControlDialog,
  9. isSameWebRemoteControlTarget,
  10. isReusableWebRemoteControlSession,
  11. getWebRemoteControlStatusTagLabel,
  12. } from "@/web-remote-control/index.js";
  13. vi.mock("@/components/ui/button.js", () => ({
  14. Button: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) =>
  15. createElement("button", props, children),
  16. }));
  17. vi.mock("@/components/ui/dialog.js", () => ({
  18. Dialog: ({ children }: { children?: ReactNode }) => createElement("div", null, children),
  19. DialogContent: ({
  20. children,
  21. className,
  22. showCloseButton: _showCloseButton,
  23. ...props
  24. }: {
  25. children?: ReactNode;
  26. className?: string;
  27. showCloseButton?: boolean;
  28. [key: string]: unknown;
  29. }) => createElement("section", { className, ...props }, children),
  30. DialogDescription: ({ children }: { children?: ReactNode }) => createElement("p", null, children),
  31. DialogHeader: ({ children, className }: { children?: ReactNode; className?: string }) =>
  32. createElement("header", { className }, children),
  33. DialogTitle: ({ children }: { children?: ReactNode }) => createElement("h2", null, children),
  34. }));
  35. const feedbackMocks = vi.hoisted(() => ({
  36. error: vi.fn(),
  37. info: vi.fn(),
  38. toast: vi.fn(),
  39. requestLoginEntry: vi.fn(),
  40. }));
  41. vi.mock("@/components/ui/toast.js", () => ({ toast: feedbackMocks.toast }));
  42. vi.mock("@/BotsDialog.js", () => ({
  43. BotsDialog: () => createElement("div", { "data-testid": "bots-dialog" }),
  44. }));
  45. const platformMock = vi.hoisted(() => ({
  46. getWebRemoteControlStatus: vi.fn(async () => ({ status: "idle" })),
  47. startWebRemoteControl: vi.fn(async () => ({ status: "running" })),
  48. stopWebRemoteControl: vi.fn(async () => {}),
  49. }));
  50. vi.mock("@/hooks/usePlatform.js", () => ({
  51. usePlatform: () => platformMock,
  52. }));
  53. vi.mock("@/hooks/useOAuth.js", () => ({
  54. useOAuth: () => ({ activeProvider: null, loadingProviders: false, refreshProviders: vi.fn() }),
  55. }));
  56. vi.mock("@/store/StoreProvider.js", () => ({
  57. useZCodeStore: (
  58. selector: (state: {
  59. theme: string;
  60. requestLoginEntry: typeof feedbackMocks.requestLoginEntry;
  61. }) => unknown,
  62. ) => selector({ theme: "zai-dark", requestLoginEntry: feedbackMocks.requestLoginEntry }),
  63. }));
  64. const intlMock = vi.hoisted(() => ({
  65. intl: {
  66. formatMessage: ({ id }: { id: string }) => id,
  67. },
  68. }));
  69. vi.mock("@/i18n/IntlProvider.js", () => ({
  70. useZCodeIntl: () => intlMock,
  71. }));
  72. vi.mock("@/logger.js", () => ({
  73. logger: {
  74. error: feedbackMocks.error,
  75. info: feedbackMocks.info,
  76. },
  77. }));
  78. function readWebRemoteControlDialogSource() {
  79. // Bugfix: WebRemoteControlDialog 经过 React.memo 包装后,组件 toString() 只会返回 [object Object]。
  80. // 源码结构守卫需要读取真实文件,才能继续校验复用顺序和确认弹窗保护没有被性能优化绕开。
  81. return readFileSync("packages/ui/src/web-remote-control/WebRemoteControlDialog.tsx", "utf8");
  82. }
  83. describe("WebRemoteControlDialog layout", () => {
  84. afterEach(() => {
  85. cleanup();
  86. platformMock.getWebRemoteControlStatus.mockClear();
  87. platformMock.startWebRemoteControl.mockClear();
  88. platformMock.stopWebRemoteControl.mockClear();
  89. feedbackMocks.error.mockClear();
  90. feedbackMocks.info.mockClear();
  91. feedbackMocks.toast.mockClear();
  92. });
  93. it("auth-required 显示登录入口,无二维码、生成中、复制链接或错误toast", async () => {
  94. platformMock.getWebRemoteControlStatus.mockResolvedValueOnce({ status: "auth-required" });
  95. const onOpenChange = vi.fn();
  96. const view = render(
  97. createElement(WebRemoteControlDialog, {
  98. open: true,
  99. onOpenChange,
  100. workspacePath: "/tmp/project",
  101. }),
  102. );
  103. const login = await view.findByRole("button", { name: "webRemoteControl.authRequired.login" });
  104. expect(view.container.textContent).toContain("webRemoteControl.authRequired.title");
  105. expect(view.container.textContent).toContain("webRemoteControl.authRequired.description");
  106. expect(view.container.textContent).not.toContain("webRemoteControl.generating");
  107. expect(view.queryByTestId("web-remote-control-copy-link-row")).toBeNull();
  108. expect(view.queryByRole("img")).toBeNull();
  109. expect(platformMock.startWebRemoteControl).not.toHaveBeenCalled();
  110. expect(feedbackMocks.toast).not.toHaveBeenCalled();
  111. fireEvent.click(login);
  112. expect(onOpenChange).toHaveBeenCalledWith(false);
  113. expect(feedbackMocks.requestLoginEntry).toHaveBeenCalledOnce();
  114. });
  115. it("启动因缺少JWT失败时读取main的auth-required状态,不展示失败toast", async () => {
  116. platformMock.getWebRemoteControlStatus
  117. .mockResolvedValueOnce({ status: "idle" })
  118. .mockResolvedValueOnce({ status: "auth-required" });
  119. platformMock.startWebRemoteControl.mockRejectedValueOnce(new Error("auth-required"));
  120. const view = render(
  121. createElement(WebRemoteControlDialog, {
  122. open: true,
  123. onOpenChange: vi.fn(),
  124. workspacePath: "/tmp/project",
  125. }),
  126. );
  127. await view.findByRole("button", { name: "webRemoteControl.authRequired.login" });
  128. expect(feedbackMocks.toast).not.toHaveBeenCalled();
  129. });
  130. it("treats native start cancellation as idle without failure UI", async () => {
  131. platformMock.startWebRemoteControl.mockResolvedValueOnce({ status: "cancelled" });
  132. const view = render(
  133. createElement(WebRemoteControlDialog, {
  134. open: true,
  135. onOpenChange: vi.fn(),
  136. workspacePath: "/tmp/project",
  137. }),
  138. );
  139. await waitFor(() => expect(platformMock.startWebRemoteControl).toHaveBeenCalledOnce());
  140. expect(view.container.textContent).toContain("webRemoteControl.statusDetail.idle");
  141. expect(feedbackMocks.toast).not.toHaveBeenCalled();
  142. expect(feedbackMocks.error).not.toHaveBeenCalled();
  143. });
  144. it("仅在 workspace 与 remoteSessionId 都匹配时复用远控状态", () => {
  145. expect(
  146. isSameWebRemoteControlTarget(
  147. {
  148. status: "running",
  149. sessionId: "sid-1",
  150. workspacePath: "/tmp/workspace-a",
  151. },
  152. "/tmp/workspace-b",
  153. ),
  154. ).toBe(false);
  155. expect(
  156. isSameWebRemoteControlTarget(
  157. {
  158. status: "running",
  159. sessionId: "sid-1",
  160. workspacePath: "/tmp/workspace-a",
  161. remoteSessionId: "remote-a",
  162. },
  163. "/tmp/workspace-a",
  164. undefined,
  165. "remote-b",
  166. ),
  167. ).toBe(false);
  168. expect(
  169. isSameWebRemoteControlTarget(
  170. {
  171. status: "running",
  172. sessionId: "sid-1",
  173. workspacePath: "/tmp/workspace-a",
  174. workspaceIdentity: "ssh://host/repo",
  175. remoteSessionId: "remote-a",
  176. },
  177. "/tmp/any-local-path",
  178. "ssh://host/repo",
  179. "remote-a",
  180. ),
  181. ).toBe(true);
  182. });
  183. it("复用已有 window 级远控会话时不要求 workspace 匹配", () => {
  184. expect(
  185. isReusableWebRemoteControlSession({
  186. status: "active",
  187. sessionId: "sid-1",
  188. mobileConnected: true,
  189. workspacePath: "/tmp/workspace-a",
  190. }),
  191. ).toBe(true);
  192. expect(
  193. isReusableWebRemoteControlSession({
  194. status: "idle",
  195. }),
  196. ).toBe(false);
  197. expect(
  198. isReusableWebRemoteControlSession({
  199. status: "error",
  200. sessionId: "sid-1",
  201. mobileConnected: true,
  202. workspacePath: "/tmp/workspace-a",
  203. }),
  204. ).toBe(false);
  205. expect(
  206. isReusableWebRemoteControlSession({
  207. status: "running",
  208. sessionId: "sid-1",
  209. mobileConnected: false,
  210. workspacePath: "/tmp/workspace-a",
  211. }),
  212. ).toBe(false);
  213. });
  214. it("打开弹层时先复用已连接手机的 window 会话再考虑重新 start", () => {
  215. const source = readWebRemoteControlDialogSource();
  216. const reuseIndex = source.indexOf("isReusableWebRemoteControlSession(currentStatus)");
  217. const startIndex = source.indexOf("platform.startWebRemoteControl");
  218. const pollReuseIndex = source.indexOf("isReusableWebRemoteControlSession(nextStatus)");
  219. expect(reuseIndex).toBeGreaterThan(-1);
  220. expect(startIndex).toBeGreaterThan(-1);
  221. expect(reuseIndex).toBeLessThan(startIndex);
  222. expect(pollReuseIndex).toBeGreaterThan(-1);
  223. });
  224. it("renders phone QR and bot channel entry cards in the remote control dialog", () => {
  225. const html = renderToStaticMarkup(
  226. createElement(WebRemoteControlDialog, {
  227. open: true,
  228. onOpenChange: vi.fn(),
  229. workspacePath: "/tmp/project",
  230. }),
  231. );
  232. expect(html).toContain('data-testid="web-remote-control-main-grid"');
  233. expect(html).toContain("webRemoteControl.mobileQr.title");
  234. expect(html).toContain("webRemoteControl.botChannel.title");
  235. expect(html).toContain("webRemoteControl.botChannel.weixin.title");
  236. expect(html).toContain("webRemoteControl.botChannel.feishu.title");
  237. expect(html).toContain("webRemoteControl.botChannel.lark.title");
  238. expect(html).toContain("webRemoteControl.botChannel.telegram.title");
  239. expect(html).toContain("login.oauth.regionTag.bigmodel");
  240. expect(html).toContain("login.oauth.regionTag.zai");
  241. expect(html).toContain('data-testid="web-remote-control-open-bots"');
  242. expect(html).toContain("webRemoteControl.botChannel.manageBots");
  243. const larkIndex = html.indexOf("webRemoteControl.botChannel.lark.title");
  244. const larkTagIndex = html.indexOf("login.oauth.regionTag.zai");
  245. const telegramIndex = html.indexOf("webRemoteControl.botChannel.telegram.title");
  246. const openBotsIndex = html.indexOf('data-testid="web-remote-control-open-bots"');
  247. expect(larkTagIndex).toBeGreaterThan(larkIndex);
  248. expect(larkTagIndex).toBeLessThan(telegramIndex);
  249. expect(telegramIndex).toBeGreaterThan(larkIndex);
  250. expect(openBotsIndex).toBeGreaterThan(telegramIndex);
  251. });
  252. it("merges status and copy link inside the Scan from phone card", () => {
  253. const html = renderToStaticMarkup(
  254. createElement(WebRemoteControlDialog, {
  255. open: true,
  256. onOpenChange: vi.fn(),
  257. workspacePath: "/tmp/project",
  258. }),
  259. );
  260. const scanCardIndex = html.indexOf('data-testid="web-remote-control-scan-card"');
  261. const connectionCardIndex = html.indexOf('data-testid="web-remote-control-connection-card"');
  262. const copyLinkIndex = html.indexOf('data-testid="web-remote-control-copy-link-row"');
  263. const botChannelIndex = html.indexOf("webRemoteControl.botChannel.title");
  264. expect(scanCardIndex).toBeGreaterThan(-1);
  265. expect(connectionCardIndex).toBeGreaterThan(scanCardIndex);
  266. expect(copyLinkIndex).toBeGreaterThan(connectionCardIndex);
  267. expect(copyLinkIndex).toBeLessThan(botChannelIndex);
  268. expect(html).toContain('data-testid="web-remote-control-connection-card"');
  269. expect(html).toContain('data-testid="web-remote-control-copy-link-row"');
  270. expect(html).toContain("webRemoteControl.statusDetail.idle");
  271. expect(html).toContain("webRemoteControl.copyLink.description");
  272. });
  273. it("V2弹窗只保留复制链接,移除刷新二维码入口", () => {
  274. const html = renderToStaticMarkup(
  275. createElement(WebRemoteControlDialog, {
  276. open: true,
  277. onOpenChange: vi.fn(),
  278. workspacePath: "/tmp/project",
  279. }),
  280. );
  281. expect(html).toContain("webRemoteControl.copyLink</button>");
  282. expect(html).not.toContain("webRemoteControl.refreshQr");
  283. });
  284. it("uses the paired mobile device name for the status tag instead of session id", () => {
  285. expect(
  286. getWebRemoteControlStatusTagLabel(
  287. {
  288. status: "active",
  289. sessionId: "sid-12345678",
  290. mobileConnected: true,
  291. mobileDeviceInfo: {
  292. platform: "web",
  293. version: "1.7.0",
  294. name: "mobile-browser",
  295. browserPlatform: "iPhone",
  296. updatedAt: 1,
  297. },
  298. },
  299. ({ id }: { id: string }) => id,
  300. ),
  301. ).toBe("iPhone");
  302. });
  303. });