remoteNewConnectionForm.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. // @vitest-environment jsdom
  2. import { createElement, type ComponentProps } from "react";
  3. import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
  4. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  5. import type {
  6. DockerContainerInfo,
  7. SourceServerManagementSnapshot,
  8. SSHConfigAliasOption,
  9. WSLDistro,
  10. } from "@zcode/shared";
  11. import zhCN from "@/i18n/locales/zh-CN.js";
  12. /**
  13. * RDUX-27:新建连接表单的头部、类型切换、SSH config 导入、粘贴拆分、内联校验与两种入口页脚。
  14. * 挂载真实向导(useRemoteConnectionFlow + SSHDialog),只替换服务端口。
  15. */
  16. const ports = vi.hoisted(() => ({
  17. snapshot: {} as SourceServerManagementSnapshot,
  18. credentialService: { load: vi.fn(async () => null), save: vi.fn() },
  19. settingService: {
  20. get: vi.fn(async () => ({ remoteBoundaryIntroAcknowledgedVersion: 1 })),
  21. update: vi.fn(async () => undefined),
  22. },
  23. management: {
  24. getSnapshot: vi.fn(),
  25. onDidChangeState: () => ({ dispose() {} }),
  26. onDidChangeDirectory: () => ({ dispose() {} }),
  27. updateSource: vi.fn(),
  28. confirmIdentityChange: vi.fn(),
  29. },
  30. platform: {
  31. isLocalDevelopmentRuntime: false,
  32. isDockerAvailable: vi.fn(async () => true),
  33. listSSHConfigAliases: vi.fn(async (): Promise<SSHConfigAliasOption[]> => []),
  34. listWSLDistros: vi.fn(async (): Promise<WSLDistro[]> => []),
  35. listDockerContainers: vi.fn(async (): Promise<DockerContainerInfo[]> => []),
  36. onRemoteConnectionLog: vi.fn(() => () => undefined),
  37. cancelPendingRemoteConnection: vi.fn(async () => undefined),
  38. selectFile: vi.fn(async () => null),
  39. },
  40. confirm: vi.fn(async () => true),
  41. }));
  42. vi.mock("@/i18n/IntlProvider.js", () => ({
  43. useZCodeIntl: () => ({
  44. locale: "zh-CN",
  45. intl: {
  46. formatMessage: ({ id }: { id: string }, values: Record<string, string> = {}) =>
  47. ((zhCN as Record<string, string>)[id] ?? id).replace(
  48. /\{(\w+)\}/gu,
  49. (_, key) => values[key] ?? `{${key}}`,
  50. ),
  51. },
  52. }),
  53. }));
  54. vi.mock("@/hooks/useWorkspaceServices.js", () => ({
  55. useBaseWorkspaceServices: () => ({ ...ports, sourceServerManagementService: ports.management }),
  56. useOptionalBaseWorkspaceServices: () => ({
  57. ...ports,
  58. sourceServerManagementService: ports.management,
  59. }),
  60. }));
  61. vi.mock("@/hooks/usePlatform.js", () => ({
  62. usePlatform: () => ports.platform,
  63. useOptionalPlatform: () => ports.platform,
  64. }));
  65. vi.mock("@/hooks/useConfirmDialog.js", () => ({ useConfirmDialog: () => ports.confirm }));
  66. import { RemoteConnectionDialog } from "@/SSHDialog.js";
  67. import { useRemoteWorkspaceSessionStore } from "@/store/remoteWorkspaceSessionStore.js";
  68. type DialogProps = ComponentProps<typeof RemoteConnectionDialog>;
  69. function mountDialog(overrides: Partial<DialogProps> = {}) {
  70. const props: DialogProps = {
  71. open: true,
  72. onConnect: vi.fn(async () => "session-a"),
  73. onSelectProject: vi.fn(async () => undefined),
  74. onCancelSession: vi.fn(async () => undefined),
  75. ...overrides,
  76. };
  77. return { ...render(createElement(RemoteConnectionDialog, props)), props };
  78. }
  79. const mountSettingsEntry = (overrides: Partial<DialogProps> = {}) =>
  80. mountDialog({ completion: "device-management", ...overrides });
  81. const aliases: SSHConfigAliasOption[] = [
  82. {
  83. alias: "gpu",
  84. host: "gpu.example.com",
  85. username: "ubuntu",
  86. port: 2222,
  87. privateKeyPath: "~/.ssh/gpu.pem",
  88. },
  89. { alias: "staging", host: "staging.example.com", username: "deploy" },
  90. ];
  91. function pasteInto(element: HTMLElement, text: string) {
  92. const event = new Event("paste", { bubbles: true, cancelable: true });
  93. Object.assign(event, { clipboardData: { getData: () => text } });
  94. fireEvent(element, event);
  95. return event;
  96. }
  97. beforeEach(() => {
  98. vi.clearAllMocks();
  99. vi.stubGlobal(
  100. "ResizeObserver",
  101. class {
  102. observe() {}
  103. unobserve() {}
  104. disconnect() {}
  105. },
  106. );
  107. HTMLElement.prototype.scrollIntoView = vi.fn();
  108. ports.platform.isDockerAvailable.mockResolvedValue(true);
  109. ports.platform.listSSHConfigAliases.mockResolvedValue([]);
  110. ports.platform.listDockerContainers.mockResolvedValue([]);
  111. ports.snapshot = {
  112. generation: 1,
  113. servers: [],
  114. profiles: [],
  115. states: [],
  116. workspaceHistory: [],
  117. failedPathCount: 0,
  118. abandonedPathCount: 0,
  119. migrationCounts: [],
  120. };
  121. ports.management.getSnapshot.mockImplementation(async () => ports.snapshot);
  122. useRemoteWorkspaceSessionStore.setState({ sessionsById: {} });
  123. });
  124. afterEach(cleanup);
  125. describe("设置入口的新建连接表单", () => {
  126. it("没有步骤条和说明句,标题下实时预览目标,焦点在主机", async () => {
  127. mountSettingsEntry();
  128. const host = await screen.findByTestId("ssh-host-input");
  129. expect(screen.getByRole("heading", { name: "新建连接" })).toBeTruthy();
  130. expect(screen.queryByRole("navigation", { name: zhCN["remote.wizard"] })).toBeNull();
  131. expect(screen.queryByText(/填写建立/)).toBeNull();
  132. const preview = screen.getByTestId("remote-new-connection-preview");
  133. expect(preview.textContent).toBe("user@host:22");
  134. await waitFor(() => expect(document.activeElement).toBe(host));
  135. fireEvent.change(host, { target: { value: "10.0.0.5" } });
  136. fireEvent.change(screen.getByTestId("ssh-username-input"), { target: { value: "root" } });
  137. expect(preview.textContent).toBe("root@10.0.0.5:22");
  138. });
  139. it("类型切换带类型色并标记选中项,认证方式保持中性", async () => {
  140. mountSettingsEntry();
  141. const kinds = await screen.findByRole("group", { name: zhCN["remote.connectionType"] });
  142. const ssh = within(kinds).getByTestId("remote-kind-ssh");
  143. expect(ssh.getAttribute("aria-pressed")).toBe("true");
  144. expect(ssh.className).toContain("bg-remote-ssh-surface");
  145. fireEvent.click(within(kinds).getByTestId("remote-kind-docker"));
  146. const docker = within(kinds).getByTestId("remote-kind-docker");
  147. expect(docker.getAttribute("aria-pressed")).toBe("true");
  148. expect(docker.className).toContain("bg-remote-docker-surface");
  149. expect(ssh.className).not.toContain("bg-remote-ssh-surface");
  150. fireEvent.click(ssh);
  151. const auth = screen.getByRole("group", { name: zhCN["ssh.authMethod"] });
  152. expect(within(auth).getByRole("button", { pressed: true }).className).not.toMatch(
  153. /bg-remote-/u,
  154. );
  155. });
  156. it("从 SSH config 导入后显示关联标签,焦点到第一个空必填项,× 只解除关联", async () => {
  157. ports.platform.listSSHConfigAliases.mockResolvedValue(aliases);
  158. mountSettingsEntry();
  159. const importButton = await screen.findByTestId("remote-ssh-config-import");
  160. await waitFor(() => expect((importButton as HTMLButtonElement).disabled).toBe(false));
  161. fireEvent.click(importButton);
  162. fireEvent.click(await screen.findByText("staging"));
  163. const chip = await screen.findByTestId("remote-ssh-config-alias-chip");
  164. expect(chip.textContent).toContain("已关联 Host staging");
  165. expect(chip.className).toContain("bg-remote-ssh-surface");
  166. expect((screen.getByTestId("ssh-host-input") as HTMLInputElement).value).toBe(
  167. "staging.example.com",
  168. );
  169. await waitFor(() =>
  170. expect(document.activeElement).toBe(screen.getByTestId("ssh-password-input")),
  171. );
  172. fireEvent.click(within(chip).getByRole("button", { name: zhCN["ssh.configAliasUnlink"] }));
  173. expect(screen.queryByTestId("remote-ssh-config-alias-chip")).toBeNull();
  174. expect((screen.getByTestId("ssh-host-input") as HTMLInputElement).value).toBe(
  175. "staging.example.com",
  176. );
  177. });
  178. it("导入的 Host 已有私钥时焦点移到主操作", async () => {
  179. ports.platform.listSSHConfigAliases.mockResolvedValue(aliases);
  180. mountSettingsEntry();
  181. const importButton = await screen.findByTestId("remote-ssh-config-import");
  182. await waitFor(() => expect((importButton as HTMLButtonElement).disabled).toBe(false));
  183. fireEvent.click(importButton);
  184. fireEvent.click(await screen.findByText("gpu"));
  185. await waitFor(() =>
  186. expect(document.activeElement).toBe(screen.getByRole("button", { name: "添加并连接" })),
  187. );
  188. });
  189. it("没有 config Host 时导入按钮禁用并说明原因", async () => {
  190. mountSettingsEntry();
  191. const importButton = await screen.findByTestId("remote-ssh-config-import");
  192. await waitFor(() => expect(importButton.textContent).toContain(zhCN["ssh.importEmpty"]));
  193. expect((importButton as HTMLButtonElement).disabled).toBe(true);
  194. });
  195. it("粘贴 ssh 命令拆分主机、用户名和端口,并解除别名关联", async () => {
  196. ports.platform.listSSHConfigAliases.mockResolvedValue(aliases);
  197. mountSettingsEntry();
  198. const importButton = await screen.findByTestId("remote-ssh-config-import");
  199. await waitFor(() => expect((importButton as HTMLButtonElement).disabled).toBe(false));
  200. fireEvent.click(importButton);
  201. fireEvent.click(await screen.findByText("staging"));
  202. await screen.findByTestId("remote-ssh-config-alias-chip");
  203. const host = screen.getByTestId("ssh-host-input");
  204. const event = pasteInto(host, "ssh root@10.0.0.5 -p 2222");
  205. expect(event.defaultPrevented).toBe(true);
  206. expect((host as HTMLInputElement).value).toBe("10.0.0.5");
  207. expect((screen.getByTestId("ssh-username-input") as HTMLInputElement).value).toBe("root");
  208. expect((screen.getByTestId("ssh-port-input") as HTMLInputElement).value).toBe("2222");
  209. expect(screen.getByText("已识别 root@10.0.0.5:2222")).toBeTruthy();
  210. expect(screen.queryByTestId("remote-ssh-config-alias-chip")).toBeNull();
  211. await waitFor(() =>
  212. expect(document.activeElement).toBe(screen.getByTestId("ssh-password-input")),
  213. );
  214. // 手动修改主机后识别提示消失;不匹配的文本交给浏览器默认粘贴。
  215. fireEvent.change(host, { target: { value: "10.0.0.6" } });
  216. expect(screen.queryByText(/已识别/)).toBeNull();
  217. expect(pasteInto(host, "plain-host").defaultPrevented).toBe(false);
  218. });
  219. it("提交时在字段下方显示错误,焦点到第一个出错字段,修正后错误消失", async () => {
  220. const { props } = mountSettingsEntry();
  221. const host = await screen.findByTestId("ssh-host-input");
  222. fireEvent.click(screen.getByRole("button", { name: "添加并连接" }));
  223. const hostError = (await screen.findByText(zhCN["ssh.validation.hostRequired"])).closest("p")!;
  224. expect(host.getAttribute("aria-invalid")).toBe("true");
  225. expect(host.getAttribute("aria-describedby")).toBe(hostError.id);
  226. expect(screen.getByText(zhCN["ssh.validation.usernameRequired"])).toBeTruthy();
  227. expect(screen.getByText(zhCN["ssh.validation.passwordRequired"])).toBeTruthy();
  228. expect(document.activeElement).toBe(host);
  229. expect(props.onConnect).not.toHaveBeenCalled();
  230. fireEvent.change(host, { target: { value: "10.0.0.5" } });
  231. expect(screen.queryByText(zhCN["ssh.validation.hostRequired"])).toBeNull();
  232. expect(host.getAttribute("aria-invalid")).toBeNull();
  233. expect(screen.getByText(zhCN["ssh.validation.usernameRequired"])).toBeTruthy();
  234. });
  235. it("设置入口页脚提供取消与添加并连接", async () => {
  236. mountSettingsEntry();
  237. const submit = await screen.findByRole("button", { name: "添加并连接" });
  238. const footer = submit.parentElement!;
  239. expect(within(footer).getByRole("button", { name: zhCN["common.cancel"] })).toBeTruthy();
  240. });
  241. it("Docker 没有说明段,不可用时在选择器下方警告", async () => {
  242. ports.platform.isDockerAvailable.mockResolvedValue(false);
  243. mountSettingsEntry();
  244. fireEvent.click(await screen.findByTestId("remote-kind-docker"));
  245. fireEvent.click(screen.getByRole("button", { name: zhCN["docker.inputMode.select"] }));
  246. const warning = await screen.findByText(zhCN["docker.unavailable"]);
  247. expect(warning.closest("[data-remote-field-hint=warning]")).toBeTruthy();
  248. expect(screen.queryByText("连接本机 Docker 容器。")).toBeNull();
  249. expect(screen.getByTestId("remote-new-connection-preview").textContent).toBe(
  250. zhCN["docker.selectContainer"],
  251. );
  252. });
  253. it.each([
  254. ["Docker 不可用", false, "docker.unavailable"],
  255. ["没有运行中的容器", true, "docker.noContainers"],
  256. ] as const)("%s时,打开容器下拉的空列表说明原因", async (_, available, messageId) => {
  257. ports.platform.isDockerAvailable.mockResolvedValue(available);
  258. mountSettingsEntry();
  259. fireEvent.click(await screen.findByTestId("remote-kind-docker"));
  260. fireEvent.click(screen.getByRole("button", { name: zhCN["docker.inputMode.select"] }));
  261. await screen.findByText(zhCN[messageId]);
  262. fireEvent.click(screen.getByTestId("docker-container-select"));
  263. const list = await screen.findByRole("listbox");
  264. expect(within(list).getByText(zhCN[messageId])).toBeTruthy();
  265. expect(within(list).queryByText(zhCN["docker.selectContainer"])).toBeNull();
  266. });
  267. });
  268. describe("项目/聊天入口的新建 SSH 连接表单", () => {
  269. it("保留三步步骤条、类型标签与返回连接入口,隐藏别名入口", async () => {
  270. ports.platform.listSSHConfigAliases.mockResolvedValue(aliases);
  271. mountDialog();
  272. fireEvent.click(await screen.findByRole("button", { name: zhCN["remote.selection.new.ssh"] }));
  273. await screen.findByTestId("ssh-host-input");
  274. const steps = screen.getByRole("navigation", { name: zhCN["remote.wizard"] });
  275. expect(within(steps).getAllByRole("listitem")).toHaveLength(3);
  276. expect(screen.getByRole("heading", { name: "新建连接" })).toBeTruthy();
  277. expect(document.querySelector("[data-remote-connection-kind=ssh]")).toBeTruthy();
  278. expect(screen.queryByTestId("remote-ssh-config-import")).toBeNull();
  279. fireEvent.click(screen.getByRole("button", { name: /高级/ }));
  280. expect(screen.queryByTestId("ssh-config-alias-select")).toBeNull();
  281. const back = screen.getByRole("button", { name: zhCN["remote.selection.back"] });
  282. const footer = back.parentElement!;
  283. expect(footer.lastElementChild!.textContent).toBe(zhCN["remote.startConnection"]);
  284. });
  285. });