conversation-session-remote-ui-walkthrough.test.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. import { startProjectPointerDrag } from "#e2e/helpers/project-sidebar";
  2. import { createStallableTcpProxy } from "#e2e/helpers/ssh-stallable-proxy";
  3. import { requestRemoteProjectConnection } from "#e2e/helpers/remote-project-actions";
  4. /* eslint-disable max-lines -- 走查 spec 按真实用户顺序串起向导、侧栏、设置的全部状态,拆散会丢失截图编号的连续性。 */
  5. import { execFile } from "node:child_process";
  6. import { mkdir, writeFile } from "node:fs/promises";
  7. import { createServer, connect, type Server, type Socket } from "node:net";
  8. import { resolve } from "node:path";
  9. import { promisify } from "node:util";
  10. import {
  11. TID_CONFIRM_DIALOG_CONFIRM,
  12. TID_VIRTUAL_PROJECT_ADD,
  13. TID_REMOTE_KIND_DOCKER,
  14. TID_REMOTE_KIND_SSH,
  15. TID_SETTINGS_BACK_BUTTON,
  16. TID_SETTINGS_SECTION_NAV,
  17. TID_SSH_AUTH_PASSWORD,
  18. TID_SSH_AUTH_PRIVATE_KEY,
  19. TID_SSH_DIALOG,
  20. TID_SSH_ERROR,
  21. TID_SSH_SUCCESS,
  22. TID_TASK_SETTINGS_BUTTON,
  23. testId,
  24. } from "@zcode/shared/test-ids";
  25. import {
  26. clearAppData,
  27. clickTestIdByDom,
  28. hoverTestIdByWebDriver,
  29. DEFAULT_WORKSPACE,
  30. waitForWorkspaceApp,
  31. } from "#e2e/helpers/desktop-app";
  32. import { startElectronWindowRecording } from "#e2e/helpers/electron-window-recorder";
  33. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  34. import {
  35. selectTaskOrganizeMode,
  36. openWorkspaceDraftFromSidebar,
  37. } from "#e2e/helpers/workspace-agent-warmup";
  38. import {
  39. clickLastEnabledSSHDialogButton,
  40. fillSSHPasswordSettings,
  41. prepareSSHConnectionPage,
  42. readSSHRuntimeConfig,
  43. openRemoteConnectionSelection,
  44. connectSSHWorkspace,
  45. waitForRemoteTab,
  46. waitForSSHDirectoryStep,
  47. waitForSSHError,
  48. } from "#e2e/helpers/ssh-remote-p0";
  49. /**
  50. * 远程连接 UI 走查:不是断言型用例,而是在真实 SSH 容器上按用户顺序走完向导、侧栏、
  51. * 设置页的全部可见状态,产出编号截图(浅/深色)、全程录屏和一份 index.json 目录。
  52. * 断言只保留“流程确实到达了该状态”,避免走查因为文案微调而中断。
  53. */
  54. const MARKER = "E2E_REMOTE_UI_WALKTHROUGH";
  55. const artifact = resolve(
  56. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/remote-ui-walkthrough",
  57. );
  58. const dialog = `[data-testid="${TID_SSH_DIALOG}"]`;
  59. const run = promisify(execFile);
  60. interface CaptureEntry {
  61. error?: string;
  62. files: string[];
  63. step: string;
  64. title: string;
  65. }
  66. const index: CaptureEntry[] = [];
  67. let sequence = 0;
  68. const nextStep = () => String(++sequence).padStart(2, "0");
  69. async function settle() {
  70. await browser.executeAsync((done) =>
  71. requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(done, 120))),
  72. );
  73. }
  74. async function setTheme(theme: "light" | "dark") {
  75. await browser.execute((value) => {
  76. const actions = (window as Window & { __testActions?: { setTheme(value: string): void } })
  77. .__testActions;
  78. if (!actions) throw new Error("Missing theme test actions");
  79. actions.setTheme(value);
  80. }, theme);
  81. }
  82. /** 同一状态各截一张浅色和深色;截完切回浅色,让录屏主线保持浅色。 */
  83. async function capture(name: string, title: string) {
  84. const step = nextStep();
  85. const files: string[] = [];
  86. for (const theme of ["light", "dark"] as const) {
  87. await setTheme(theme);
  88. await settle();
  89. const file = `${step}-${name}-${theme}.png`;
  90. await browser.saveScreenshot(resolve(artifact, file));
  91. files.push(file);
  92. }
  93. await setTheme("light");
  94. await settle();
  95. index.push({ step, title, files });
  96. }
  97. /** 连接进行中的实时帧:按固定间隔连拍直到条件满足,保留过程而不是只留结果。 */
  98. async function captureFrames(
  99. name: string,
  100. title: string,
  101. until: () => Promise<boolean>,
  102. options: { intervalMs?: number; timeoutMs: number },
  103. ) {
  104. const step = nextStep();
  105. const files: string[] = [];
  106. const started = Date.now();
  107. let satisfied = false;
  108. while (Date.now() - started < options.timeoutMs) {
  109. const file = `${step}-${name}-f${String(files.length + 1).padStart(3, "0")}.png`;
  110. await browser.saveScreenshot(resolve(artifact, file));
  111. files.push(file);
  112. if (await until()) {
  113. satisfied = true;
  114. break;
  115. }
  116. await browser.pause(options.intervalMs ?? 600);
  117. }
  118. index.push({ step, title: `${title}(${files.length} 帧)`, files });
  119. if (!satisfied) throw new Error(`${MARKER}: ${title} 未到达目标状态`);
  120. }
  121. async function openDeviceMenu() {
  122. await $('[data-source-server-card] button[aria-label="更多"]').click();
  123. await $('[role="menu"]').waitForDisplayed();
  124. }
  125. async function clickButton(label: string | RegExp, root = dialog) {
  126. const pattern = label instanceof RegExp ? label.source : null;
  127. await browser.waitUntil(
  128. () =>
  129. browser.execute(
  130. (scope, text, source) => {
  131. const matcher = source ? new RegExp(source, "u") : null;
  132. // 菜单项是 role=menuitem 的 div,不是 button;统一按可点击项匹配。
  133. const button = Array.from(
  134. document
  135. .querySelector(scope)
  136. ?.querySelectorAll<HTMLElement>('button, [role="menuitem"]') ?? [],
  137. ).find((item) => {
  138. const disabled =
  139. (item as HTMLButtonElement).disabled ||
  140. item.getAttribute("aria-disabled") === "true" ||
  141. item.hasAttribute("data-disabled");
  142. if (!item.getClientRects().length || disabled) return false;
  143. const content = item.textContent?.trim() ?? "";
  144. const aria = item.getAttribute("aria-label") ?? "";
  145. // 字符串只做精确匹配:「连接」不能误中「编辑连接」,「取消」不能误中「取消连接」。
  146. return matcher
  147. ? matcher.test(content) || matcher.test(aria)
  148. : content === text || aria === text;
  149. });
  150. if (!button) return false;
  151. button.click();
  152. return true;
  153. },
  154. root,
  155. typeof label === "string" ? label : null,
  156. pattern,
  157. ),
  158. { timeout: 30_000, timeoutMsg: `${MARKER}: 找不到按钮 ${String(label)}(${root})` },
  159. );
  160. }
  161. async function hasButton(label: string, root = dialog) {
  162. return browser.execute(
  163. (scope, text) =>
  164. Array.from(
  165. document.querySelector(scope)?.querySelectorAll<HTMLElement>('button, [role="menuitem"]') ??
  166. [],
  167. ).some(
  168. (item) =>
  169. item.getClientRects().length > 0 &&
  170. (item.textContent?.trim() === text || item.getAttribute("aria-label") === text),
  171. ),
  172. root,
  173. label,
  174. );
  175. }
  176. async function openProjectAddMenu() {
  177. await selectTaskOrganizeMode(["项目", "Project"]);
  178. await hoverTestIdByWebDriver("project-section");
  179. await clickTestIdByDom(TID_VIRTUAL_PROJECT_ADD);
  180. await $('[role="dialog"]').waitForDisplayed();
  181. }
  182. async function openSelection() {
  183. await openRemoteConnectionSelection();
  184. }
  185. async function closeDialog() {
  186. if (await $(dialog).isExisting()) {
  187. await clickButton("关闭");
  188. await $(dialog).waitForExist({ reverse: true, timeout: 10_000 });
  189. }
  190. }
  191. async function openSettingsRemoteDevices() {
  192. if (!(await $('[data-testid="settings-page"]').isDisplayed())) {
  193. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  194. }
  195. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "remoteDevices"));
  196. await $("[data-settings-content-frame]").waitForDisplayed();
  197. }
  198. async function backToWorkspace() {
  199. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  200. await $("[data-settings-content-frame]").waitForExist({ reverse: true, timeout: 10_000 });
  201. }
  202. async function rowState(identity: string) {
  203. return browser.execute(
  204. (key) =>
  205. document.querySelector<HTMLElement>(`[data-project-workspace-identity="${key}"]`)?.dataset
  206. .connectionState ?? null,
  207. identity,
  208. );
  209. }
  210. async function openProjectActions(identity: string) {
  211. const row = $(`[data-project-workspace-identity="${identity}"]`);
  212. await row.$('[data-testid="virtual-project-toggle"]').moveTo();
  213. await row.$('[data-testid="virtual-project-menu"]').click();
  214. await $('[role="menu"]').waitForDisplayed();
  215. }
  216. async function closePopover() {
  217. await browser.keys("Escape");
  218. await browser.pause(300);
  219. }
  220. /** 段落失败后把界面收回到工作区,让后续段落还能继续截图。 */
  221. async function recover() {
  222. await browser.keys("Escape");
  223. await browser.pause(300);
  224. if (await $(dialog).isExisting()) {
  225. if (await hasButton("稍后选择")) await clickButton("稍后选择").catch(() => undefined);
  226. await closeDialog().catch(() => undefined);
  227. }
  228. if (await $("[data-settings-content-frame]").isExisting()) {
  229. await backToWorkspace().catch(() => undefined);
  230. }
  231. }
  232. /** 走查段落彼此独立:一个段落失败只记一条失败条目并截图,不中断整条走查。 */
  233. async function segment(key: string, title: string, fn: () => Promise<void>) {
  234. try {
  235. await fn();
  236. } catch (error) {
  237. const detail = String(error instanceof Error ? error.message : error).slice(0, 300);
  238. const step = nextStep();
  239. const file = `${step}-FAILED-${key}.png`;
  240. await browser.saveScreenshot(resolve(artifact, file)).catch(() => undefined);
  241. index.push({
  242. step,
  243. title: `【段落失败】${title}:${detail}`,
  244. error: detail,
  245. files: [file],
  246. });
  247. await recover().catch(() => undefined);
  248. }
  249. }
  250. /** 找一个当前没有监听者的本地端口,用来制造“无法连接到主机”。 */
  251. async function closedPort() {
  252. const listener = createServer();
  253. await new Promise<void>((done) => listener.listen(0, "127.0.0.1", done));
  254. const address = listener.address();
  255. if (!address || typeof address === "string") throw new Error("Missing unused port");
  256. await new Promise<void>((done, reject) =>
  257. listener.close((error) => (error ? reject(error) : done())),
  258. );
  259. return address.port;
  260. }
  261. /** 只接受 TCP、不回 SSH banner 的桩,用来稳定停留在“连接中”。 */
  262. async function startStallServer() {
  263. const sockets = new Set<Socket>();
  264. const server: Server = createServer((socket) => {
  265. sockets.add(socket);
  266. socket.on("error", () => undefined);
  267. socket.on("close", () => sockets.delete(socket));
  268. });
  269. await new Promise<void>((yes, no) => {
  270. server.once("error", no);
  271. server.listen(0, "127.0.0.1", yes);
  272. });
  273. const address = server.address();
  274. if (!address || typeof address === "string") throw new Error("Missing stall port");
  275. return {
  276. port: address.port,
  277. sockets,
  278. async close() {
  279. for (const socket of sockets) socket.destroy();
  280. if (server.listening) await new Promise<void>((yes) => server.close(() => yes()));
  281. },
  282. };
  283. }
  284. /** 只允许操作本用例专属、带 r3-server 标签的目标容器,绝不碰共享的开发容器。 */
  285. async function ownedContainer(): Promise<string | null> {
  286. const name = process.env.ZCODE_E2E_SSH_CONTAINER?.trim();
  287. if (!name || !/^zcode-r3-server-[a-z0-9-]+$/u.test(name)) return null;
  288. try {
  289. const { stdout } = await run("docker", [
  290. "inspect",
  291. "--format",
  292. '{{index .Config.Labels "zcode.e2e.run"}}',
  293. name,
  294. ]);
  295. return stdout.trim() === "r3-server" ? name : null;
  296. } catch {
  297. return null;
  298. }
  299. }
  300. async function waitForTcpPort(host: string, port: number, timeoutMs: number) {
  301. const started = Date.now();
  302. while (Date.now() - started < timeoutMs) {
  303. const ok = await new Promise<boolean>((done) => {
  304. const socket = connect({ host, port });
  305. socket.setTimeout(1500);
  306. socket.once("connect", () => {
  307. socket.destroy();
  308. done(true);
  309. });
  310. socket.once("error", () => done(false));
  311. socket.once("timeout", () => {
  312. socket.destroy();
  313. done(false);
  314. });
  315. });
  316. if (ok) return;
  317. await new Promise((tick) => setTimeout(tick, 1000));
  318. }
  319. throw new Error(`${MARKER}: ${host}:${port} 在 ${timeoutMs}ms 内没有重新可达`);
  320. }
  321. describe(`${MARKER}: 远程连接 UI 走查`, () => {
  322. let transportProxy: Awaited<ReturnType<typeof createStallableTcpProxy>> | undefined;
  323. after(async () => {
  324. await transportProxy?.close();
  325. transportProxy = undefined;
  326. await browser.electron.restoreAllMocks();
  327. await clearAppData();
  328. });
  329. it("RDUX-WALKTHROUGH 按用户顺序截取向导、侧栏、设置的全部状态并录屏", async function () {
  330. this.timeout(30 * 60_000);
  331. await mkdir(artifact, { recursive: true });
  332. const direct = readSSHRuntimeConfig(MARKER);
  333. // Docker 动态发布端口在 stop/start 后会改变;稳定监听端口由代理独占,应用线路保持不变。
  334. const endpoint = { host: direct.host, port: direct.port };
  335. const backendPorts = [endpoint.port];
  336. transportProxy = await createStallableTcpProxy(endpoint);
  337. const config = { ...direct, host: "127.0.0.1", port: transportProxy.port };
  338. const workspacePath = config.workspacePaths[0]!;
  339. await prepareSSHConnectionPage(MARKER);
  340. await prepareV4ConversationE2E({ skipProvider: true });
  341. // 不做 refresh:刷新后 waitForWorkspaceApp 在本机曾停留 2 分钟未就绪,而走查不依赖侧栏宽度持久化。
  342. await browser.execute(() => {
  343. (
  344. window as Window & { __testActions?: { setLocale(value: "zh-CN"): void } }
  345. ).__testActions?.setLocale("zh-CN");
  346. });
  347. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  348. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60_000);
  349. await browser.electron.execute((electron) => {
  350. const window = electron.BrowserWindow.getAllWindows().find((item) => !item.isDestroyed());
  351. window?.setMinimumSize(360, 600);
  352. window?.setSize(1400, 1000);
  353. });
  354. await setTheme("light");
  355. await settle();
  356. // 指针停在角落,避免悬停入口影响截图。
  357. await browser.performActions([
  358. {
  359. type: "pointer",
  360. id: "park",
  361. parameters: { pointerType: "mouse" },
  362. actions: [{ type: "pointerMove", x: 2, y: 2, duration: 0 }],
  363. },
  364. ]);
  365. const recording = await startElectronWindowRecording({
  366. browser,
  367. frameIntervalMs: 500,
  368. outputPath: resolve(artifact, "remote-ui-walkthrough.webm"),
  369. encodeTimeoutMs: 5 * 60_000,
  370. stopTimeoutMs: 5 * 60_000,
  371. });
  372. const stall = await startStallServer();
  373. const container = await ownedContainer();
  374. let containerStopped = false;
  375. try {
  376. // ---------- 设置:按类型添加与连接反馈 ----------
  377. await openProjectAddMenu();
  378. await capture("project-add-menu", "侧栏「添加项目」:选择本机或远程设备");
  379. await browser.keys("Escape");
  380. await openSelection();
  381. await $(`${dialog} [data-testid="ssh-host-input"]`).waitForDisplayed();
  382. await capture("selection-empty", "设置新建:默认 SSH 分类表单");
  383. await clickTestIdByDom(TID_REMOTE_KIND_DOCKER);
  384. await $(`${dialog} [data-testid="docker-container-input"]`).waitForDisplayed();
  385. await capture("docker-manual-form", "手动输入 Docker 容器的表单");
  386. await clickTestIdByDom(TID_REMOTE_KIND_SSH);
  387. await $(`${dialog} [data-testid="ssh-host-input"]`).waitForDisplayed();
  388. await capture("ssh-form-empty", "新建 SSH 连接:空表单");
  389. await fillSSHPasswordSettings(config);
  390. await clickTestIdByDom(TID_SSH_AUTH_PRIVATE_KEY);
  391. await settle();
  392. await capture("ssh-form-private-key", "SSH 表单:切换到私钥认证");
  393. await clickTestIdByDom(TID_SSH_AUTH_PASSWORD);
  394. await fillSSHPasswordSettings(config);
  395. await clickButton("高级选项");
  396. await settle();
  397. await capture(
  398. "ssh-form-filled-advanced",
  399. "SSH 表单:已填写,展开高级选项(资源下载方式默认本地下载后上传)",
  400. );
  401. await clickLastEnabledSSHDialogButton(MARKER);
  402. const installVisible = () => hasButton("安装并继续");
  403. const boundary = $('[data-testid="source-server-boundary-dialog"]');
  404. await captureFrames(
  405. "connecting-first",
  406. "向导第 2 屏:首次连接,时间线逐步推进直到需要确认安装",
  407. async () =>
  408. (await installVisible()) ||
  409. (await boundary.isDisplayed()) ||
  410. !(await $(dialog).isExisting()),
  411. { timeoutMs: 120_000, intervalMs: 500 },
  412. );
  413. if (await installVisible()) {
  414. await capture("install-confirm", "首次连接:新设备需要安装 ZCode Server 的确认卡");
  415. await clickButton(/^连接日志/u);
  416. await settle();
  417. await capture("install-confirm-log-expanded", "安装确认 + 展开连接日志");
  418. await clickButton("安装并继续");
  419. await captureFrames(
  420. "installing",
  421. "安装并启动 ZCode Server 的实时进度",
  422. async () => (await boundary.isDisplayed()) || !(await $(dialog).isExisting()),
  423. { timeoutMs: 240_000, intervalMs: 700 },
  424. );
  425. }
  426. // 新版首次介绍必须真实确认;旧走查只等向导消失,会把已完成安装误报为超时。
  427. await boundary.waitForDisplayed();
  428. await capture("boundary-introduction", "首次远程连接:介绍页等待明确确认");
  429. await boundary.$(`[data-testid="${TID_CONFIRM_DIALOG_CONFIRM}"]`).click();
  430. await boundary.waitForDisplayed({ reverse: true });
  431. expect(await waitForSSHDirectoryStep(MARKER)).toBe("closed");
  432. await capture("device-first-added", "设置:添加完成并定位设备,不打开目录");
  433. await backToWorkspace();
  434. await connectSSHWorkspace({ config, workspacePath, caseMarker: MARKER });
  435. const tab = await waitForRemoteTab({ caseMarker: MARKER, expectedPath: workspacePath });
  436. const identity = tab.workspaceIdentity!;
  437. await browser.waitUntil(async () => (await rowState(identity)) === "online", {
  438. timeout: 30_000,
  439. });
  440. await settle();
  441. await capture("workspace-online", "远程项目已打开:侧栏项目行(已连接)+ 空会话");
  442. // ---------- 侧栏 ----------
  443. await openProjectActions(identity);
  444. await capture(
  445. "sidebar-details-online",
  446. "侧栏在线项目操作:追加项目 / 编辑 / 置顶 / 删除 / 移除入口",
  447. );
  448. await closePopover();
  449. const row = $(`[data-project-workspace-identity="${identity}"]`);
  450. await row.$('[data-testid="virtual-project-toggle"]').moveTo();
  451. await row.$('button[aria-label="更多"]').click();
  452. await $('[role="menu"]').waitForDisplayed();
  453. await capture("sidebar-more-menu", "侧栏项目行「更多」菜单");
  454. await closePopover();
  455. await openProjectAddMenu();
  456. await capture("project-add-menu-devices", "添加项目入口:选择所属设备");
  457. await browser.keys("Escape");
  458. await browser.keys("Escape");
  459. await openSettingsRemoteDevices();
  460. // RDUX-13:编辑与断开在设备行「更多」菜单里。
  461. await openDeviceMenu();
  462. await clickButton("编辑", '[role="menu"]');
  463. const editor = '[role="dialog"][data-slot="dialog-content"]';
  464. await $(editor).waitForDisplayed();
  465. await capture("edit-connection-dialog", "设置页编辑连接对话框");
  466. await clickButton("取消", editor);
  467. await $(editor).waitForExist({ reverse: true });
  468. // ---------- 设置:重复添加已在线目标复用设备 ----------
  469. await openSelection();
  470. await capture("add-with-saved-device", "已有设备时,新建仍直接进入默认 SSH 分类表单");
  471. expect(await $(`${dialog} input[type="search"]`).isExisting()).toBe(false);
  472. await fillSSHPasswordSettings(config);
  473. await clickLastEnabledSSHDialogButton(MARKER);
  474. expect(await waitForSSHDirectoryStep(MARKER)).toBe("closed");
  475. await settle();
  476. await capture("manual-reuse", "手动填写已在线目标:复用连接并留在设置");
  477. // ---------- 设置页 ----------
  478. await openSettingsRemoteDevices();
  479. await $("[data-source-server-card]").waitForDisplayed();
  480. await capture("settings-card-online", "设置 · 远程设备:设备行(已连接)与连接偏好");
  481. // 最近日志在设备行展开区。
  482. const toggle = $("[data-source-server-card] [data-source-server-toggle]");
  483. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  484. await $("[data-source-server-card] [data-source-server-log-toggle]").click();
  485. await $("[data-source-server-log-timestamp]").waitForDisplayed();
  486. await capture("settings-card-logs", "设备卡:展开最近日志");
  487. await $('[data-source-server-card] button[aria-label="更多"]').click();
  488. await $("[data-device-info]").waitForDisplayed();
  489. await capture(
  490. "settings-card-more-menu",
  491. "设备卡「更多」菜单:设备信息 / 在侧边栏中显示 / 复制设备 ID / 移除设备",
  492. );
  493. await clickButton("移除设备", '[role="menu"]');
  494. await $('[role="dialog"]').waitForDisplayed();
  495. await capture("settings-remove-confirm", "移除设备确认框(截图后按 Esc 取消)");
  496. // 确认框的取消按钮带 esc 快捷键后缀,直接按 Esc 关闭,绝不点确认。
  497. await browser.keys("Escape");
  498. await $('[role="dialog"]').waitForExist({ reverse: true });
  499. await openDeviceMenu();
  500. await clickButton("编辑", '[role="menu"]');
  501. await $(editor).waitForDisplayed();
  502. await capture("settings-edit-dialog", "设备卡「编辑」对话框");
  503. await clickButton("取消", editor);
  504. await $(editor).waitForExist({ reverse: true });
  505. await openDeviceMenu();
  506. // 断开菜单项内带任务继续提示,按前缀匹配。
  507. await clickButton(/^断开/u, '[role="menu"]');
  508. await $(
  509. '[data-source-server-card] [data-remote-connection-status="offline"]',
  510. ).waitForDisplayed({ timeout: 30_000 });
  511. await settle();
  512. await capture("settings-card-offline", "设备卡(未连接):最近在线与「连接」入口");
  513. // ---------- 断线后的会话与侧栏 ----------
  514. await backToWorkspace();
  515. await browser.waitUntil(async () => (await rowState(identity)) === "offline", {
  516. timeout: 30_000,
  517. });
  518. await settle();
  519. await capture("conversation-disconnected", "断开后:侧栏项目行(未连接)与会话区断线占位");
  520. await openProjectActions(identity);
  521. await capture("sidebar-details-offline", "侧栏离线项目操作:连接 / 移除入口");
  522. await clickButton("连接", '[role="menu"]');
  523. await captureFrames(
  524. "reconnecting",
  525. "从侧栏重连:连接中状态直到恢复在线",
  526. async () => (await rowState(identity)) === "online",
  527. { timeoutMs: 120_000, intervalMs: 600 },
  528. );
  529. if (await $(dialog).isExisting()) {
  530. if (await $(`${dialog} [data-testid="${TID_SSH_SUCCESS}"]`).isExisting()) {
  531. await clickButton("稍后选择");
  532. }
  533. await closeDialog();
  534. }
  535. await settle();
  536. await capture("workspace-reconnected", "重连完成:项目恢复在线");
  537. // ---------- 失败态:无法连接 / 认证失败 ----------
  538. await segment("unreachable", "主机不可达失败态", async () => {
  539. await openSelection();
  540. await clickTestIdByDom(TID_REMOTE_KIND_SSH);
  541. await fillSSHPasswordSettings({ ...config, host: "127.0.0.1", port: await closedPort() });
  542. await clickLastEnabledSSHDialogButton(MARKER);
  543. await waitForSSHError(MARKER, 90_000);
  544. await settle();
  545. await capture("failed-unreachable", "连接失败:主机不可达(错误卡 + 建议操作)");
  546. await closeDialog();
  547. });
  548. await segment("auth", "SSH 认证失败态", async () => {
  549. // 同一 user@host:port 在线时向导会直接复用连接,密码根本不会被校验;
  550. // 换一个不存在的用户名才能真正触发 SSH 认证失败。
  551. await openSelection();
  552. await clickTestIdByDom(TID_REMOTE_KIND_SSH);
  553. await fillSSHPasswordSettings({
  554. ...config,
  555. username: `${config.username}-nobody`,
  556. password: `${config.password}-wrong`,
  557. });
  558. await clickLastEnabledSSHDialogButton(MARKER);
  559. await waitForSSHError(MARKER, 120_000);
  560. await settle();
  561. await capture("failed-auth", "连接失败:SSH 认证失败(应提供「修改密码或私钥」)");
  562. if (await hasButton("修改密码或私钥")) {
  563. await clickButton("修改密码或私钥");
  564. await $(`${dialog} [data-testid="ssh-host-input"]`).waitForDisplayed();
  565. await settle();
  566. await capture("failed-auth-edit", "点击「修改密码或私钥」回到表单");
  567. }
  568. await closeDialog();
  569. });
  570. // ---------- 取消与后台继续 ----------
  571. await segment("cancel", "连接中取消", async () => {
  572. await openSelection();
  573. await clickTestIdByDom(TID_REMOTE_KIND_SSH);
  574. await fillSSHPasswordSettings({ ...config, host: "127.0.0.1", port: stall.port });
  575. await clickLastEnabledSSHDialogButton(MARKER);
  576. await browser.waitUntil(() => stall.sockets.size > 0, { timeout: 30_000 });
  577. await settle();
  578. await capture("connecting-pending", "连接中(对端不响应):可取消或在后台继续");
  579. await clickButton("取消连接");
  580. await browser
  581. .waitUntil(async () => (await $(dialog).getText()).includes("已取消"), {
  582. timeout: 30_000,
  583. })
  584. .catch(() => undefined);
  585. await settle();
  586. await capture("cancelled", "已取消:保留目标,可重试");
  587. await closeDialog();
  588. for (const socket of stall.sockets) socket.destroy();
  589. });
  590. await segment("minimized", "在后台继续与后台失败", async () => {
  591. await openSelection();
  592. await clickTestIdByDom(TID_REMOTE_KIND_SSH);
  593. await fillSSHPasswordSettings({ ...config, host: "127.0.0.1", port: stall.port });
  594. await clickLastEnabledSSHDialogButton(MARKER);
  595. await browser.waitUntil(() => stall.sockets.size > 0, { timeout: 30_000 });
  596. await clickButton(/在后台继续|收起/u);
  597. // 后台进度已由设置页承接;限定真实承接位置,避免全局同名卡片让旧侧栏覆盖说明误报通过。
  598. const background = $(
  599. '[data-settings-content-frame] [data-testid="remote-connection-minimized"]',
  600. );
  601. await background.waitForDisplayed();
  602. await settle();
  603. await capture("minimized-connecting", "在后台继续:设置页未完成连接显示进度");
  604. for (const socket of stall.sockets) socket.destroy();
  605. await browser.waitUntil(async () => /失败|failed/iu.test(await background.getText()), {
  606. timeout: 90_000,
  607. });
  608. await $(dialog).waitForDisplayed({ reverse: true, timeout: 5_000 });
  609. await settle();
  610. await capture("minimized-failed", "后台连接失败:设置进度项保留失败,不自动弹回");
  611. await background.click();
  612. await $(`${dialog} [data-testid="${TID_SSH_ERROR}"]`).waitForDisplayed();
  613. await settle();
  614. await capture("reopened-failed", "点击卡片恢复向导:失败详情");
  615. await closeDialog();
  616. });
  617. await segment("unfinished", "设置页未完成的连接", async () => {
  618. await openSettingsRemoteDevices();
  619. const unfinished = $("[data-unfinished-connections]");
  620. if (await unfinished.isExisting()) {
  621. await $("[data-unfinished-connections] summary").click();
  622. await settle();
  623. await capture("settings-unfinished", "设置 · 未完成的连接(失败的新目标不生成设备卡)");
  624. await clickButton("清理全部", "[data-unfinished-connections]");
  625. await $('[role="dialog"]').waitForDisplayed();
  626. await capture("settings-clear-all-confirm", "清理全部确认框(截图后按 Esc 取消)");
  627. await browser.keys("Escape");
  628. await $('[role="dialog"]').waitForExist({ reverse: true });
  629. }
  630. await backToWorkspace();
  631. });
  632. // ---------- 真实掉线:停止专属容器,观察自动恢复与失败 ----------
  633. if (container) {
  634. await segment("container", "停止远端容器后的掉线与恢复", async () => {
  635. transportProxy!.setRejectNewConnections(true);
  636. await run("docker", ["stop", container]);
  637. containerStopped = true;
  638. await captureFrames(
  639. "connection-lost",
  640. "远端被停止后:侧栏项目从已连接进入自动恢复 / 需要处理 / 连接失败",
  641. async () => ["failed", "pending", "offline"].includes((await rowState(identity)) ?? ""),
  642. { timeoutMs: 180_000, intervalMs: 1_000 },
  643. );
  644. await settle();
  645. await capture(
  646. "sidebar-after-loss",
  647. `掉线后的侧栏项目行(状态:${await rowState(identity)})`,
  648. );
  649. await openProjectActions(identity);
  650. await capture("sidebar-details-after-loss", "掉线后的项目操作菜单");
  651. await closePopover();
  652. await run("docker", ["start", container]);
  653. containerStopped = false;
  654. const published = await run("docker", ["port", container, "22/tcp"]);
  655. const port = Number(/^127\.0\.0\.1:(\d+)$/mu.exec(published.stdout)?.[1]);
  656. if (!Number.isInteger(port) || port < 1 || port > 65535)
  657. throw new Error("专属容器重启后缺少 loopback SSH 端口");
  658. endpoint.port = port;
  659. backendPorts.push(port);
  660. await waitForTcpPort(endpoint.host, endpoint.port, 60_000);
  661. transportProxy!.setRejectNewConnections(false);
  662. if ((await rowState(identity)) !== "online") {
  663. await requestRemoteProjectConnection(identity, MARKER);
  664. }
  665. // 如当前连接流程要求重试,继续走用户可见入口。
  666. if ((await $(dialog).isExisting()) && (await hasButton("重试"))) {
  667. await settle();
  668. await capture(
  669. "recovering-failed-detail",
  670. "远端恢复后点击失败项目:先看到上次失败详情与「重试」",
  671. );
  672. await clickButton("重试");
  673. }
  674. await captureFrames(
  675. "recovering",
  676. "远端恢复后点击项目:重新连接直到在线",
  677. async () => (await rowState(identity)) === "online",
  678. { timeoutMs: 180_000, intervalMs: 800 },
  679. );
  680. if (await $(dialog).isExisting()) {
  681. if (await $(`${dialog} [data-testid="${TID_SSH_SUCCESS}"]`).isExisting()) {
  682. await clickButton("稍后选择");
  683. }
  684. await closeDialog();
  685. }
  686. await settle();
  687. await capture("workspace-recovered", "远端恢复后项目重新在线");
  688. });
  689. }
  690. // ---------- 拖拽预览 ----------
  691. await segment("drag", "拖拽预览", async () => {
  692. const dragSelector = `[data-project-workspace-identity="${identity}"] [data-testid="virtual-project-toggle"]`;
  693. const position = await startProjectPointerDrag(dragSelector);
  694. await browser.waitUntil(
  695. () =>
  696. browser.execute(
  697. (selector, top) =>
  698. Math.abs(document.querySelector(selector)!.getBoundingClientRect().top - top) >= 6,
  699. dragSelector,
  700. position.top,
  701. ),
  702. { timeout: 5000, timeoutMsg: "项目拖拽没有产生可见位移" },
  703. );
  704. await $(
  705. `[data-project-workspace-identity="${identity}"] [data-testid="project-device"]`,
  706. ).waitForDisplayed();
  707. const step = nextStep();
  708. await browser.saveScreenshot(resolve(artifact, `${step}-drag-device-light.png`));
  709. index.push({
  710. step,
  711. title: "拖拽项目:移动的项目行保留设备标签",
  712. files: [`${step}-drag-device-light.png`],
  713. });
  714. await browser.keys("Escape");
  715. await browser.releaseActions();
  716. });
  717. } finally {
  718. if (container && containerStopped)
  719. await run("docker", ["start", container]).catch(() => undefined);
  720. await stall.close();
  721. const video = await recording.stop({ tailDurationMs: 1_000 }).catch((error: unknown) => ({
  722. videoPath: null,
  723. error: String(error),
  724. }));
  725. if (!video.videoPath)
  726. index.push({
  727. step: nextStep(),
  728. title: "全程录屏失败",
  729. files: [],
  730. error: "error" in video ? video.error : "未生成视频",
  731. });
  732. await writeFile(
  733. resolve(artifact, "index.json"),
  734. JSON.stringify(
  735. {
  736. marker: MARKER,
  737. capturedAt: new Date().toISOString(),
  738. target: `${config.username}@${config.host}:${config.port}`,
  739. backendPorts,
  740. video,
  741. captures: index,
  742. },
  743. null,
  744. 2,
  745. ),
  746. );
  747. }
  748. // 段落失败可以继续取证,但不能把未完成的交互汇总为 PASS。
  749. expect(index.filter((entry) => entry.error !== undefined).map((entry) => entry.title)).toEqual(
  750. [],
  751. );
  752. });
  753. });