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

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