webRemoteControlDialogLayout.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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 "@/WebRemoteControlDialog.js";
  13. vi.mock("@/components/ui/button.js", () => ({
  14. Button: ({
  15. children,
  16. ...props
  17. }: {
  18. children?: ReactNode;
  19. [key: string]: unknown;
  20. }) => createElement("button", props, children),
  21. }));
  22. vi.mock("@/components/ui/dialog.js", () => ({
  23. Dialog: ({ children }: { children?: ReactNode }) =>
  24. createElement("div", null, children),
  25. DialogContent: ({
  26. children,
  27. className,
  28. showCloseButton: _showCloseButton,
  29. ...props
  30. }: {
  31. children?: ReactNode;
  32. className?: string;
  33. showCloseButton?: boolean;
  34. [key: string]: unknown;
  35. }) => createElement("section", { className, ...props }, children),
  36. DialogDescription: ({ children }: { children?: ReactNode }) =>
  37. createElement("p", null, children),
  38. DialogHeader: ({
  39. children,
  40. className,
  41. }: {
  42. children?: ReactNode;
  43. className?: string;
  44. }) => createElement("header", { className }, children),
  45. DialogTitle: ({ children }: { children?: ReactNode }) =>
  46. createElement("h2", null, children),
  47. }));
  48. const feedbackMocks = vi.hoisted(() => ({
  49. error: vi.fn(),
  50. info: vi.fn(),
  51. toast: vi.fn(),
  52. }));
  53. vi.mock("@/components/ui/toast.js", () => ({ toast: feedbackMocks.toast }));
  54. vi.mock("@/BotsDialog.js", () => ({
  55. BotsDialog: () => createElement("div", { "data-testid": "bots-dialog" }),
  56. }));
  57. const platformMock = vi.hoisted(() => ({
  58. getWebRemoteControlStatus: vi.fn(async () => ({ status: "idle" })),
  59. startWebRemoteControl: vi.fn(async () => ({ status: "running" })),
  60. refreshWebRemoteControlPairing: vi.fn(async () => ({ status: "running" })),
  61. stopWebRemoteControl: vi.fn(async () => {}),
  62. }));
  63. vi.mock("@/hooks/usePlatform.js", () => ({
  64. usePlatform: () => platformMock,
  65. }));
  66. const confirmDialogMock = vi.hoisted(() => vi.fn(async () => true));
  67. vi.mock("@/hooks/useConfirmDialog.js", () => ({
  68. useConfirmDialog: () => confirmDialogMock,
  69. }));
  70. vi.mock("@/store/StoreProvider.js", () => ({
  71. useZCodeStore: (selector: (state: { theme: string }) => unknown) =>
  72. selector({ theme: "zai-dark" }),
  73. }));
  74. const intlMock = vi.hoisted(() => ({
  75. intl: {
  76. formatMessage: ({ id }: { id: string }) => id,
  77. },
  78. }));
  79. vi.mock("@/i18n/IntlProvider.js", () => ({
  80. useZCodeIntl: () => intlMock,
  81. }));
  82. vi.mock("@/logger.js", () => ({
  83. logger: {
  84. error: feedbackMocks.error,
  85. info: feedbackMocks.info,
  86. },
  87. }));
  88. function readWebRemoteControlDialogSource() {
  89. // Bugfix: WebRemoteControlDialog 经过 React.memo 包装后,组件 toString() 只会返回 [object Object]。
  90. // 源码结构守卫需要读取真实文件,才能继续校验复用顺序和确认弹窗保护没有被性能优化绕开。
  91. return readFileSync("packages/ui/src/WebRemoteControlDialog.tsx", "utf8");
  92. }
  93. describe("WebRemoteControlDialog layout", () => {
  94. afterEach(() => {
  95. cleanup();
  96. platformMock.getWebRemoteControlStatus.mockClear();
  97. platformMock.startWebRemoteControl.mockClear();
  98. platformMock.refreshWebRemoteControlPairing.mockClear();
  99. platformMock.stopWebRemoteControl.mockClear();
  100. feedbackMocks.error.mockClear();
  101. feedbackMocks.info.mockClear();
  102. feedbackMocks.toast.mockClear();
  103. confirmDialogMock.mockClear();
  104. });
  105. it("treats native start cancellation as idle without failure UI", async () => {
  106. platformMock.startWebRemoteControl.mockResolvedValueOnce({ status: "cancelled" });
  107. const view = render(
  108. createElement(WebRemoteControlDialog, {
  109. open: true,
  110. onOpenChange: vi.fn(),
  111. workspacePath: "/tmp/project",
  112. }),
  113. );
  114. await waitFor(() => expect(platformMock.startWebRemoteControl).toHaveBeenCalledOnce());
  115. expect(view.container.textContent).toContain("webRemoteControl.statusDetail.idle");
  116. expect(feedbackMocks.toast).not.toHaveBeenCalled();
  117. expect(feedbackMocks.error).not.toHaveBeenCalled();
  118. });
  119. it("keeps the running status and shows no feedback when native refresh is cancelled", async () => {
  120. platformMock.getWebRemoteControlStatus.mockResolvedValueOnce({
  121. status: "running",
  122. sessionId: "sid-1",
  123. mobileConnected: true,
  124. workspacePath: "/tmp/project",
  125. });
  126. platformMock.refreshWebRemoteControlPairing.mockResolvedValueOnce({ status: "cancelled" });
  127. const view = render(
  128. createElement(WebRemoteControlDialog, {
  129. open: true,
  130. onOpenChange: vi.fn(),
  131. workspacePath: "/tmp/project",
  132. }),
  133. );
  134. const refreshButton = await view.findByRole("button", {
  135. name: "webRemoteControl.refreshQr",
  136. });
  137. fireEvent.click(refreshButton);
  138. await waitFor(() => expect(platformMock.refreshWebRemoteControlPairing).toHaveBeenCalledOnce());
  139. expect(view.container.textContent).toContain("webRemoteControl.statusDetail.running");
  140. expect(feedbackMocks.toast).not.toHaveBeenCalled();
  141. expect(feedbackMocks.error).not.toHaveBeenCalled();
  142. });
  143. it("仅在 workspace 与 remoteSessionId 都匹配时复用远控状态", () => {
  144. expect(
  145. isSameWebRemoteControlTarget(
  146. {
  147. status: "running",
  148. sessionId: "sid-1",
  149. workspacePath: "/tmp/workspace-a",
  150. },
  151. "/tmp/workspace-b",
  152. ),
  153. ).toBe(false);
  154. expect(
  155. isSameWebRemoteControlTarget(
  156. {
  157. status: "running",
  158. sessionId: "sid-1",
  159. workspacePath: "/tmp/workspace-a",
  160. remoteSessionId: "remote-a",
  161. },
  162. "/tmp/workspace-a",
  163. undefined,
  164. "remote-b",
  165. ),
  166. ).toBe(false);
  167. expect(
  168. isSameWebRemoteControlTarget(
  169. {
  170. status: "running",
  171. sessionId: "sid-1",
  172. workspacePath: "/tmp/workspace-a",
  173. workspaceIdentity: "ssh://host/repo",
  174. remoteSessionId: "remote-a",
  175. },
  176. "/tmp/any-local-path",
  177. "ssh://host/repo",
  178. "remote-a",
  179. ),
  180. ).toBe(true);
  181. });
  182. it("复用已有 window 级远控会话时不要求 workspace 匹配", () => {
  183. expect(
  184. isReusableWebRemoteControlSession({
  185. status: "active",
  186. sessionId: "sid-1",
  187. mobileConnected: true,
  188. workspacePath: "/tmp/workspace-a",
  189. }),
  190. ).toBe(true);
  191. expect(
  192. isReusableWebRemoteControlSession({
  193. status: "idle",
  194. }),
  195. ).toBe(false);
  196. expect(
  197. isReusableWebRemoteControlSession({
  198. status: "error",
  199. sessionId: "sid-1",
  200. mobileConnected: true,
  201. workspacePath: "/tmp/workspace-a",
  202. }),
  203. ).toBe(false);
  204. expect(
  205. isReusableWebRemoteControlSession({
  206. status: "running",
  207. sessionId: "sid-1",
  208. mobileConnected: false,
  209. workspacePath: "/tmp/workspace-a",
  210. }),
  211. ).toBe(false);
  212. });
  213. it("打开弹层时先复用已连接手机的 window 会话再考虑重新 start", () => {
  214. const source = readWebRemoteControlDialogSource();
  215. const reuseIndex = source.indexOf(
  216. "isReusableWebRemoteControlSession(currentStatus)",
  217. );
  218. const startIndex = source.indexOf("platform.startWebRemoteControl");
  219. const pollReuseIndex = source.indexOf(
  220. "isReusableWebRemoteControlSession(nextStatus)",
  221. );
  222. expect(reuseIndex).toBeGreaterThan(-1);
  223. expect(startIndex).toBeGreaterThan(-1);
  224. expect(reuseIndex).toBeLessThan(startIndex);
  225. expect(pollReuseIndex).toBeGreaterThan(-1);
  226. });
  227. it("uses Remote Connect width without forcing the lighter dialog to full height", () => {
  228. const html = renderToStaticMarkup(
  229. createElement(WebRemoteControlDialog, {
  230. open: true,
  231. onOpenChange: vi.fn(),
  232. workspacePath: "/tmp/project",
  233. }),
  234. );
  235. expect(html).toContain("max-h-[calc(100vh-6rem)]");
  236. expect(html).toContain("max-w-4xl");
  237. expect(html).toContain("overflow-hidden");
  238. expect(html).toContain('data-testid="web-remote-control-dialog-scroll"');
  239. expect(html).not.toContain('class="h-[calc(100vh-6rem)]');
  240. expect(html).toContain("overflow-y-auto");
  241. });
  242. it("renders phone QR and bot channel entry cards in the remote control dialog", () => {
  243. const html = renderToStaticMarkup(
  244. createElement(WebRemoteControlDialog, {
  245. open: true,
  246. onOpenChange: vi.fn(),
  247. workspacePath: "/tmp/project",
  248. }),
  249. );
  250. expect(html).toContain('data-testid="web-remote-control-main-grid"');
  251. expect(html).toContain("webRemoteControl.mobileQr.title");
  252. expect(html).toContain("webRemoteControl.botChannel.title");
  253. expect(html).toContain("webRemoteControl.botChannel.weixin.title");
  254. expect(html).toContain("webRemoteControl.botChannel.feishu.title");
  255. expect(html).toContain("webRemoteControl.botChannel.lark.title");
  256. expect(html).toContain("webRemoteControl.botChannel.telegram.title");
  257. expect(html).toContain("login.oauth.regionTag.bigmodel");
  258. expect(html).toContain("login.oauth.regionTag.zai");
  259. expect(html).not.toContain("web-remote-control-bot-channel-logo-");
  260. expect(html).toContain("size-12");
  261. expect(html).toContain("border-transparent");
  262. expect(html).toContain('data-testid="web-remote-control-open-bots"');
  263. expect(html).toContain("webRemoteControl.botChannel.manageBots");
  264. const larkIndex = html.indexOf("webRemoteControl.botChannel.lark.title");
  265. const larkTagIndex = html.indexOf("login.oauth.regionTag.zai");
  266. const telegramIndex = html.indexOf("webRemoteControl.botChannel.telegram.title");
  267. const openBotsIndex = html.indexOf('data-testid="web-remote-control-open-bots"');
  268. expect(larkTagIndex).toBeGreaterThan(larkIndex);
  269. expect(larkTagIndex).toBeLessThan(telegramIndex);
  270. expect(telegramIndex).toBeGreaterThan(larkIndex);
  271. expect(openBotsIndex).toBeGreaterThan(telegramIndex);
  272. });
  273. it("merges status and copy link inside the Scan from phone card", () => {
  274. const html = renderToStaticMarkup(
  275. createElement(WebRemoteControlDialog, {
  276. open: true,
  277. onOpenChange: vi.fn(),
  278. workspacePath: "/tmp/project",
  279. }),
  280. );
  281. const scanCardIndex = html.indexOf('data-testid="web-remote-control-scan-card"');
  282. const connectionCardIndex = html.indexOf(
  283. 'data-testid="web-remote-control-connection-card"',
  284. );
  285. const copyLinkIndex = html.indexOf('data-testid="web-remote-control-copy-link-row"');
  286. const botChannelIndex = html.indexOf("webRemoteControl.botChannel.title");
  287. expect(scanCardIndex).toBeGreaterThan(-1);
  288. expect(connectionCardIndex).toBeGreaterThan(scanCardIndex);
  289. expect(copyLinkIndex).toBeGreaterThan(connectionCardIndex);
  290. expect(copyLinkIndex).toBeLessThan(botChannelIndex);
  291. expect(html).toContain('data-testid="web-remote-control-connection-card"');
  292. expect(html).toContain('data-testid="web-remote-control-copy-link-row"');
  293. expect(html).toContain("items-center");
  294. expect(html).toContain("webRemoteControl.statusDetail.idle");
  295. expect(html).toContain("webRemoteControl.copyLink.description");
  296. expect(html).not.toContain('data-testid="web-remote-control-copy-link-card"');
  297. expect(html).not.toContain("mt-5 flex min-h-11");
  298. });
  299. it("renders a refresh QR action near the copied mobile link", () => {
  300. const html = renderToStaticMarkup(
  301. createElement(WebRemoteControlDialog, {
  302. open: true,
  303. onOpenChange: vi.fn(),
  304. workspacePath: "/tmp/project",
  305. }),
  306. );
  307. const refreshIndex = html.indexOf("webRemoteControl.refreshQr");
  308. const copyIndex = html.indexOf("webRemoteControl.copyLink</button>");
  309. expect(refreshIndex).toBeGreaterThan(-1);
  310. expect(copyIndex).toBeGreaterThan(-1);
  311. expect(refreshIndex).toBeLessThan(copyIndex);
  312. });
  313. it("asks for confirmation before refreshing pairing material", () => {
  314. const source = readWebRemoteControlDialogSource();
  315. const confirmIndex = source.indexOf("confirmDialog({");
  316. const refreshIndex = source.indexOf("platform.refreshWebRemoteControlPairing");
  317. expect(source).toContain("webRemoteControl.refreshQr.confirmTitle");
  318. expect(source).toContain("webRemoteControl.refreshQr.confirmDescription");
  319. expect(confirmIndex).toBeGreaterThan(-1);
  320. expect(refreshIndex).toBeGreaterThan(-1);
  321. expect(confirmIndex).toBeLessThan(refreshIndex);
  322. });
  323. it("uses the paired mobile device name for the status tag instead of session id", () => {
  324. expect(
  325. getWebRemoteControlStatusTagLabel(
  326. {
  327. status: "active",
  328. sessionId: "sid-12345678",
  329. mobileConnected: true,
  330. mobileDeviceInfo: {
  331. platform: "web",
  332. version: "1.7.0",
  333. name: "mobile-browser",
  334. browserPlatform: "iPhone",
  335. updatedAt: 1,
  336. },
  337. },
  338. ({ id }: { id: string }) => id,
  339. ),
  340. ).toBe("iPhone");
  341. });
  342. it("does not let dialog-local state decide the global remote-control session state", () => {
  343. const source = readWebRemoteControlDialogSource();
  344. expect(source).not.toContain("setWebRemoteControlSessionActive");
  345. expect(source).not.toContain("useWebRemoteControlRuntimeStore");
  346. });
  347. it("does not pass theme into start payload when syncing Web remote control status", () => {
  348. const source = readWebRemoteControlDialogSource();
  349. // Bugfix: 手机远控已改为默认 dark + 本地偏好,桌面端不应再把 theme 注入 start 参数,
  350. // 否则会重新把两端主题耦合到同一链路,和当前设计目标冲突。
  351. expect(source).not.toContain("theme,");
  352. });
  353. });