conversation-session-remote-install-progress.test.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. import { parseRemoteWorkspaceIdentity } from "@zcode/shared";
  2. import { prepareSourceServerUpdateArchive } from "#e2e/helpers/source-server-update-fixture";
  3. import {
  4. connectRemoteSourceFromSettings,
  5. disconnectRemoteSource,
  6. } from "#e2e/helpers/remote-project-actions";
  7. import { mkdir, writeFile } from "node:fs/promises";
  8. import { resolve } from "node:path";
  9. import { clearAppData, switchToNewestWindow } from "#e2e/helpers/desktop-app";
  10. import {
  11. connectSSHWorkspace,
  12. runSSHCommand,
  13. readSingleSSHWorkspaceRuntimeConfig,
  14. waitForSSHDirectoryStep,
  15. } from "#e2e/helpers/ssh-remote-p0";
  16. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  17. const CASE_MARKER = "E2E_REMOTE_INSTALL_PROGRESS";
  18. const artifactDir = resolve(
  19. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/remote-install-progress",
  20. );
  21. interface Observation {
  22. phase: string;
  23. failedSubtitle: boolean;
  24. percentage: string | null;
  25. }
  26. type ObservedWindow = Window & {
  27. __installObservations?: Observation[];
  28. __duplicateUpdateToasts?: string[];
  29. __installObserver?: MutationObserver;
  30. };
  31. describe(`${CASE_MARKER}: 远端安装真实阶段`, () => {
  32. after(async () => {
  33. const observations = await browser.execute(() => {
  34. const state = window as ObservedWindow;
  35. state.__installObserver?.disconnect();
  36. return {
  37. phases: state.__installObservations ?? [],
  38. duplicateUpdateToasts: state.__duplicateUpdateToasts ?? [],
  39. };
  40. });
  41. await mkdir(artifactDir, { recursive: true });
  42. await writeFile(
  43. resolve(artifactDir, "install-progress.json"),
  44. JSON.stringify(observations, null, 2),
  45. );
  46. await browser.electron.restoreAllMocks();
  47. await clearAppData();
  48. });
  49. it("RDUX-16 自动更新时显示实时校验与重启,随后留在设备管理", async function () {
  50. this.timeout(10 * 60_000);
  51. // harness 的目标 suffix 支持命名批次,不限十六进制;仍只允许其独立容器命名空间。
  52. // 本机 Docker runner 每次新建 zcode-local-remote-* 容器,同样是独立命名空间;过去漏掉它,
  53. // 本机运行时第一行断言就失败。
  54. // 在本 case 内真实首装,再制造同版本新 SHA 验证更新。
  55. expect(process.env.ZCODE_E2E_SSH_CONTAINER).toMatch(
  56. /^zcode-(?:progress-e2e-|r3-server-|local-remote-)[a-z0-9-]+$/u,
  57. );
  58. const config = readSingleSSHWorkspaceRuntimeConfig(CASE_MARKER);
  59. // 隔离 HOME 首次进入职业引导;先退出引导,再使用已有 workspace 准备链。
  60. await browser.waitUntil(
  61. async () => {
  62. await switchToNewestWindow();
  63. return (
  64. (await $('[data-testid="onboarding-page"]').isDisplayed()) ||
  65. (await $('[data-testid^="v4-session-pane-"]').isDisplayed())
  66. );
  67. },
  68. { timeout: 30_000, timeoutMsg: `${CASE_MARKER}: 首次引导或工作区未出现` },
  69. );
  70. if (await $('[data-testid="onboarding-page"]').isDisplayed()) await browser.keys("Escape");
  71. await prepareV4ConversationE2E({ skipProvider: true });
  72. const initial = await connectSSHWorkspace({
  73. config,
  74. caseMarker: CASE_MARKER,
  75. workspacePath: config.workspacePath,
  76. });
  77. const sourceId = parseRemoteWorkspaceIdentity(initial.workspaceIdentity!)?.sourceServerId;
  78. if (!sourceId) throw new Error(`${CASE_MARKER}: 首装缺少 Source 身份`);
  79. const installed = await runSSHCommand(config, 'cat "$HOME/.zcode/server/current.json"');
  80. const oldSha = JSON.parse(installed.stdout).archiveSha256 as string;
  81. await disconnectRemoteSource(sourceId, CASE_MARKER);
  82. const update = await prepareSourceServerUpdateArchive(oldSha, CASE_MARKER);
  83. expect(update.newSha).not.toBe(update.oldSha);
  84. await browser.execute(() => {
  85. const state = window as ObservedWindow;
  86. state.__installObservations = [];
  87. state.__duplicateUpdateToasts = [];
  88. const capture = () => {
  89. // 从连接发起前持续观察,捕获 needs-upgrade 到 updating 之间短暂出现的重复按钮。
  90. const toastHost = document.querySelector<HTMLElement>("#zcode-toast-host");
  91. if (
  92. [...(toastHost?.querySelectorAll("button") ?? [])].some((button) =>
  93. /^(立即更新|Update now)$/iu.test(button.textContent?.trim() ?? ""),
  94. )
  95. ) {
  96. const text = toastHost?.innerText ?? "";
  97. if (!state.__duplicateUpdateToasts?.includes(text))
  98. state.__duplicateUpdateToasts?.push(text);
  99. }
  100. const dialog = document.querySelector<HTMLElement>('[data-testid="ssh-dialog"]');
  101. const active = dialog?.querySelector<HTMLElement>("ol > li.bg-surface");
  102. const phase = active?.querySelector("p")?.textContent?.trim() ?? "";
  103. if (!phase) return;
  104. const observation = {
  105. phase,
  106. failedSubtitle: /连接失败 ·|Connection failed ·/u.test(dialog?.innerText ?? ""),
  107. percentage:
  108. active?.querySelector('[role="progressbar"]')?.getAttribute("aria-valuenow") ?? null,
  109. };
  110. const previous = state.__installObservations?.at(-1);
  111. if (JSON.stringify(previous) !== JSON.stringify(observation))
  112. state.__installObservations?.push(observation);
  113. };
  114. state.__installObserver = new MutationObserver(capture);
  115. state.__installObserver.observe(document.body, {
  116. childList: true,
  117. subtree: true,
  118. characterData: true,
  119. attributes: true,
  120. });
  121. });
  122. await connectRemoteSourceFromSettings(sourceId, CASE_MARKER);
  123. await browser.waitUntil(
  124. () =>
  125. browser.execute(() =>
  126. Boolean(
  127. (window as ObservedWindow).__installObservations?.some(
  128. (item) => item.phase === "正在校验服务文件",
  129. ),
  130. ),
  131. ),
  132. { timeout: 300_000, interval: 200, timeoutMsg: `${CASE_MARKER}: 未实时显示整目录校验` },
  133. );
  134. await mkdir(artifactDir, { recursive: true });
  135. for (const theme of ["light", "dark"]) {
  136. await browser.execute((value) => {
  137. const actions = (window as Window & { __testActions?: { setTheme(value: string): void } })
  138. .__testActions;
  139. if (!actions) throw new Error("Missing theme test actions");
  140. actions.setTheme(value);
  141. }, theme);
  142. for (const width of [1400, 480]) {
  143. await browser.electron.execute((electron, nextWidth) => {
  144. const window = electron.BrowserWindow.getAllWindows().find(
  145. (candidate) => !candidate.isDestroyed(),
  146. );
  147. window?.setSize(nextWidth, 900);
  148. }, width);
  149. await browser.waitUntil(
  150. () =>
  151. browser.execute((expected) => {
  152. const rect = document
  153. .querySelector("[data-testid=ssh-dialog]")
  154. ?.getBoundingClientRect();
  155. return (
  156. Math.abs(window.innerWidth - expected) <= 1 &&
  157. Boolean(rect && rect.left >= 0 && rect.right <= window.innerWidth)
  158. );
  159. }, width),
  160. { timeout: 5000 },
  161. );
  162. await browser.executeAsync((done) =>
  163. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  164. );
  165. await browser.saveScreenshot(resolve(artifactDir, `verify-${theme}-${width}.png`));
  166. }
  167. }
  168. // 设置连接的完成态已与项目入口拆开;进度关闭后留在设备管理,不创建选目录步骤。
  169. await browser.waitUntil(
  170. () => browser.execute(() => !document.querySelector("[data-testid=ssh-error]")),
  171. { timeout: 180_000, interval: 500, timeoutMsg: `${CASE_MARKER}: 更新没有完成或显示错误` },
  172. );
  173. const flow = await waitForSSHDirectoryStep(CASE_MARKER);
  174. expect(flow).toBe("closed");
  175. await $(
  176. `[data-source-server-card="${sourceId}"] [data-remote-connection-status="online"]`,
  177. ).waitForDisplayed();
  178. expect(await $('[data-testid="settings-page"]').isDisplayed()).toBe(true);
  179. expect(await $('[data-testid="virtual-project-name"]').isExisting()).toBe(false);
  180. const observations = await browser.execute(
  181. () => (window as ObservedWindow).__installObservations ?? [],
  182. );
  183. expect(
  184. await browser.execute(() => (window as ObservedWindow).__duplicateUpdateToasts ?? []),
  185. ).toEqual([]);
  186. for (const phase of [
  187. "正在上传安装包",
  188. "正在解压服务文件",
  189. "正在校验安装包",
  190. "正在校验服务文件",
  191. "正在重启远端服务",
  192. ]) {
  193. expect(observations.some((item) => item.phase === phase)).toBe(true);
  194. }
  195. expect(observations.every((item) => !item.failedSubtitle)).toBe(true);
  196. expect(
  197. observations
  198. .filter((item) => item.phase !== "正在上传安装包")
  199. .every((item) => item.percentage === null),
  200. ).toBe(true);
  201. await browser.saveScreenshot(resolve(artifactDir, "device-ready.png"));
  202. });
  203. });