conversation-session-r3-update-cancel.test.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
  2. import { join, resolve } from "node:path";
  3. import {
  4. parseRemoteWorkspaceIdentity,
  5. type SourceServerManagementSnapshot,
  6. type SourceServerOperationLog,
  7. } from "@zcode/shared";
  8. import {
  9. TID_CONFIRM_DIALOG_CONFIRM,
  10. TID_SETTINGS_SECTION_NAV,
  11. TID_TASK_SETTINGS_BUTTON,
  12. testId,
  13. } from "@zcode/shared/test-ids";
  14. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  15. import {
  16. clearAppData,
  17. clickTestIdByDom,
  18. readSettings,
  19. seedSettings,
  20. } from "#e2e/helpers/desktop-app";
  21. import { resolveE2ERuntimePath } from "#e2e/helpers/e2e-runtime-paths";
  22. import {
  23. startRemoteAssetHttpProxy,
  24. type RemoteAssetHttpProxy,
  25. } from "#e2e/helpers/remote-asset-http-proxy";
  26. import {
  27. disconnectRemoteSource,
  28. requestRemoteProjectConnection,
  29. } from "#e2e/helpers/remote-project-actions";
  30. import {
  31. callSourceManagement,
  32. installSourceManagementRpc,
  33. readSourceManagementCall,
  34. restoreSourceManagementRpc,
  35. startSourceManagementCall,
  36. waitForSourceManagementRpcReady,
  37. } from "#e2e/helpers/source-server-update-inflight";
  38. import {
  39. clickLastEnabledSSHDialogButton,
  40. fillSSHPasswordSettings,
  41. openSSHRemoteDialog,
  42. readSSHRuntimeConfig,
  43. runSSHCommand,
  44. selectSSHRemoteDirectory,
  45. waitForRemoteTab,
  46. waitForSSHDirectoryStep,
  47. type SSHConnectionConfig,
  48. } from "#e2e/helpers/ssh-remote-p0";
  49. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  50. // 与 harness/remote/remote-wdio-env.mjs 的 TEST_CDN_SPEC_MARKERS 一致:本机缓存目录按该标记隔离。
  51. const CASE_MARKER = "E2E_R3_UPDATE_CANCEL";
  52. const FAKE_CDN_HOST = "remote-assets.e2e.invalid";
  53. // 从 remote/installation 场景目录回到 packages/desktop。
  54. const DESKTOP_ROOT = resolve(import.meta.dirname, "../../../../..");
  55. const MOCK_CDN_ROOT = join(DESKTOP_ROOT, "mock-cdn");
  56. const PROXY_NO_PROXY = [
  57. "localhost",
  58. "127.0.0.1",
  59. "::1",
  60. ".aminer.cn",
  61. ".bigmodel.cn",
  62. ".z.ai",
  63. ".codegeex.cn",
  64. ".z.ai",
  65. ".zcode-ai.com",
  66. "js.stripe.com",
  67. ].join(",");
  68. // 约 90MB 的 archive 按 1 MiB/s 需要一分多钟,足够观察本机阶段并点击取消。
  69. const SLOW_ARCHIVE_BYTES_PER_SECOND = 1024 * 1024;
  70. // 03/04 还要等远端断线被检测、再发第二次更新;按 256 KiB/s 约六分钟,确保这些步骤都落在本机阶段内。
  71. const HELD_ARCHIVE_BYTES_PER_SECOND = 256 * 1024;
  72. // RDUX-13-LOG-01:远端每秒输出一条文本进度。约 90MB 按 640 KiB/s 约 140 秒,
  73. // 在下载结束前就能积累超过 Host 100 行窗口的样本数。
  74. const REMOTE_ARCHIVE_BYTES_PER_SECOND = 640 * 1024;
  75. const REMOTE_PROGRESS_OVER_WINDOW_MS = 115_000;
  76. const REMOTE_STAGE_PHASES = new Set([
  77. "preflight",
  78. "upload",
  79. "extract",
  80. "verify-archive",
  81. "verify",
  82. "restart",
  83. "install",
  84. ]);
  85. const artifactDir = resolve(
  86. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/r3-update-cancel",
  87. );
  88. /** 当前 release 的 runtime/package.json 字节数与 sha256;损坏后字节数为 0。 */
  89. async function readRemotePackageJson(config: SSHConnectionConfig): Promise<string> {
  90. const result = await runSSHCommand(
  91. config,
  92. [
  93. 'R="$HOME/.zcode/server"',
  94. 'id=$(sed -n \'s/^[[:space:]]*"releaseId"[[:space:]]*:[[:space:]]*"\\([^"]*\\)".*/\\1/p\' "$R/current.json" | head -n 1)',
  95. 'echo "$(wc -c < "$R/releases/$id/runtime/package.json" | tr -d " ") $(sha256sum "$R/releases/$id/runtime/package.json" | cut -d " " -f 1)"',
  96. ].join("; "),
  97. );
  98. return result.stdout.trim();
  99. }
  100. /** 与 R3A-BLD-12 相同:停服后把当前 release 的 package.json 截为空,`serve --daemon` 必然失败。 */
  101. async function damageCurrentRelease(config: SSHConnectionConfig): Promise<void> {
  102. await runSSHCommand(
  103. config,
  104. [
  105. 'R="$HOME/.zcode/server"',
  106. '"$R/bin/zcode" stop --wait --server-root "$R" --json >/dev/null 2>&1 || true',
  107. 'id=$(sed -n \'s/^[[:space:]]*"releaseId"[[:space:]]*:[[:space:]]*"\\([^"]*\\)".*/\\1/p\' "$R/current.json" | head -n 1)',
  108. ': > "$R/releases/$id/runtime/package.json"',
  109. ].join("; "),
  110. { timeoutMs: 60_000 },
  111. );
  112. }
  113. /** 只停远端服务、不改 release:在线连接随之关闭,下一次连接由 `serve --daemon` 重新拉起。 */
  114. async function stopRemoteService(config: SSHConnectionConfig): Promise<void> {
  115. await runSSHCommand(
  116. config,
  117. [
  118. 'R="$HOME/.zcode/server"',
  119. '"$R/bin/zcode" stop --wait --server-root "$R" --json >/dev/null 2>&1 || true',
  120. ].join("; "),
  121. { timeoutMs: 60_000 },
  122. );
  123. }
  124. /** 轮询到 done 成立或超时,返回最后一次读到的值;不抛错,便于先把修复前的现象写进工件再断言。 */
  125. async function pollFor<T>(
  126. read: () => T | Promise<T>,
  127. done: (value: T) => boolean,
  128. timeoutMs: number,
  129. ): Promise<T> {
  130. const deadline = Date.now() + timeoutMs;
  131. for (;;) {
  132. const value = await read();
  133. if (done(value) || Date.now() > deadline) return value;
  134. await browser.pause(200);
  135. }
  136. }
  137. async function clickFailedBannerReconnect(): Promise<void> {
  138. const banner = $('[data-testid="remote-conversation-banner"][data-connection-state="failed"]');
  139. await banner.waitForDisplayed({
  140. timeout: 120_000,
  141. timeoutMsg: `${CASE_MARKER}: 会话横幅未进入连接失败`,
  142. });
  143. await browser.waitUntil(
  144. () =>
  145. browser.execute(() => {
  146. const button = Array.from(
  147. document.querySelectorAll<HTMLButtonElement>(
  148. '[data-testid="remote-conversation-banner"] button',
  149. ),
  150. ).find(
  151. (item) => ["重新连接", "Reconnect"].includes(item.innerText.trim()) && !item.disabled,
  152. );
  153. button?.click();
  154. return Boolean(button);
  155. }),
  156. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 横幅没有可用的重新连接` },
  157. );
  158. }
  159. async function startWizardReinstall(): Promise<void> {
  160. const reinstall = $('[data-testid="ssh-dialog"] [data-source-server-reinstall]');
  161. await reinstall.waitForDisplayed({
  162. timeout: 120_000,
  163. timeoutMsg: `${CASE_MARKER}: 向导失败页缺少重新安装`,
  164. });
  165. await reinstall.click();
  166. await $('[role="dialog"][data-confirm-intent="source-server-reinstall"]').waitForDisplayed({
  167. timeout: 15_000,
  168. timeoutMsg: `${CASE_MARKER}: 没有重新安装确认`,
  169. });
  170. await clickTestIdByDom(TID_CONFIRM_DIALOG_CONFIRM, { timeout: 15_000 });
  171. }
  172. async function readWizardButtons() {
  173. return browser.execute(() =>
  174. Array.from(
  175. document.querySelectorAll<HTMLButtonElement>('[data-testid="ssh-dialog"] button'),
  176. ).map((button) => ({ text: button.innerText.trim(), disabled: button.disabled })),
  177. );
  178. }
  179. /**
  180. * 读连接日志里最新的本机下载百分比;日志列表收起时先展开。重新安装场景的上次失败在启动阶段,阶段轨
  181. * 停在该失败上,下载进度只出现在日志里(阶段轨投影是既有行为,不在本用例范围)。
  182. */
  183. async function readDownloadProgress(): Promise<number | null> {
  184. return browser.execute(() => {
  185. const dialog = document.querySelector('[data-testid="ssh-dialog"]');
  186. if (!dialog) return null;
  187. const container = dialog.querySelector('[data-testid="remote-connection-log"]');
  188. if (!container) {
  189. Array.from(dialog.querySelectorAll<HTMLButtonElement>("button"))
  190. .find((button) => /^(连接日志|Connection log)/u.test(button.innerText.trim()))
  191. ?.click();
  192. return null;
  193. }
  194. const matches = Array.from(
  195. (container.textContent ?? "").matchAll(
  196. /\[source-server:download\] download progress: (\d+(?:\.\d+)?)%/gu,
  197. ),
  198. );
  199. const last = matches.at(-1);
  200. if (matches.length > 1) throw new Error("同一次下载在向导日志中占用了多行");
  201. return last ? Number(last[1]) : null;
  202. });
  203. }
  204. async function readProfileState(profileId: string) {
  205. const snapshot = await callSourceManagement<SourceServerManagementSnapshot>("getSnapshot");
  206. return snapshot.states.find((state) => state.profileId === profileId);
  207. }
  208. async function readOperationLogs(profileId: string): Promise<SourceServerOperationLog[]> {
  209. return callSourceManagement<SourceServerOperationLog[]>("getRecentOperationLogs", [profileId]);
  210. }
  211. async function setTheme(theme: "light" | "dark"): Promise<void> {
  212. await browser.execute((color) => {
  213. (
  214. window as Window & { __testActions?: { setTheme(theme: string): void } }
  215. ).__testActions?.setTheme(color);
  216. }, theme);
  217. await browser.executeAsync((done) =>
  218. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  219. );
  220. }
  221. /** 深浅主题截图,供人工复核本机下载进度与可用的「取消连接」;结束后恢复浅色。 */
  222. async function captureThemeScreenshots(name: string): Promise<void> {
  223. await mkdir(artifactDir, { recursive: true });
  224. for (const theme of ["light", "dark"] as const) {
  225. await setTheme(theme);
  226. await browser.saveScreenshot(resolve(artifactDir, `${name}-${theme}.png`));
  227. }
  228. await setTheme("light");
  229. }
  230. const isCancelButton = (text: string) => /^(取消连接|Cancel connection)$/u.test(text);
  231. /** 打开设置页的远程设备,展开第一台设备,等更新日志出现。 */
  232. async function openDeviceUpdateLog(): Promise<void> {
  233. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  234. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "remoteDevices"));
  235. const toggle = $("[data-source-server-card] [data-source-server-toggle]");
  236. await toggle.waitForDisplayed();
  237. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  238. await $("[data-source-server-card] [data-source-server-log]").waitForDisplayed();
  239. }
  240. /** 设备更新日志中含下载进度的行。 */
  241. async function readDeviceDownloadRows(): Promise<string[]> {
  242. return browser.execute(() =>
  243. Array.from(
  244. document.querySelectorAll("[data-source-server-card] [data-source-server-log] > div"),
  245. )
  246. .map((row) => row.textContent ?? "")
  247. .filter((text) => text.includes("download progress:")),
  248. );
  249. }
  250. /** 远端下载脚本输出的纯文本进度:带资源标识,不带结构化 progress。 */
  251. const isRemoteTextProgress = (entry: SourceServerOperationLog) =>
  252. entry.phase === "download" &&
  253. entry.progress === undefined &&
  254. entry.message.startsWith("download progress: [");
  255. describe(`${CASE_MARKER}: 更新的本机阶段显示下载进度并可取消`, () => {
  256. let proxy: RemoteAssetHttpProxy | null = null;
  257. const cacheDir = resolveE2ERuntimePath(CASE_MARKER, "cache");
  258. const facts: Record<string, unknown> = { timeline: [] as string[] };
  259. const mark = async (label: string) => {
  260. (facts.timeline as string[]).push(`${new Date().toISOString()} ${label}`);
  261. await mkdir(artifactDir, { recursive: true });
  262. await writeFile(resolve(artifactDir, "update-cancel.json"), JSON.stringify(facts, null, 2));
  263. };
  264. // 01/02 重装完成后的在线设备,供 03/04 复用(同一 Electron 会话与 Host RPC 端口)。
  265. let context:
  266. | {
  267. config: SSHConnectionConfig;
  268. profileId: string;
  269. identity: string;
  270. workspacePath: string;
  271. versionCacheDir: string;
  272. }
  273. | undefined;
  274. const requireContext = () => {
  275. if (!context) throw new Error(`${CASE_MARKER}: 01/02 未完成,缺少已重装的在线设备`);
  276. return context;
  277. };
  278. /** 等更新进入本机下载:快照为 updating + updateCancelable,且测试 CDN 上有一条进行中的 archive 传输。 */
  279. const waitForLocalDownload = async (profileId: string, transfersBefore: number) => {
  280. let state: Awaited<ReturnType<typeof readProfileState>>;
  281. await browser.waitUntil(
  282. async () => {
  283. state = await readProfileState(profileId);
  284. const transfer = proxy!.transfers.at(-1);
  285. return (
  286. state?.state === "updating" &&
  287. state.updateCancelable === true &&
  288. proxy!.transfers.length > transfersBefore &&
  289. transfer !== undefined &&
  290. transfer.sentBytes > 0 &&
  291. !transfer.completed &&
  292. !transfer.aborted
  293. );
  294. },
  295. { timeout: 120_000, interval: 500, timeoutMsg: `${CASE_MARKER}: 更新没有进入本机下载` },
  296. );
  297. return state!;
  298. };
  299. after(async () => {
  300. try {
  301. facts.transfers = proxy?.transfers ?? [];
  302. await mkdir(artifactDir, { recursive: true });
  303. await browser.saveScreenshot(resolve(artifactDir, "update-cancel-final.png")).catch(() => {});
  304. await writeFile(resolve(artifactDir, "update-cancel.json"), JSON.stringify(facts, null, 2));
  305. await restoreSourceManagementRpc().catch(() => undefined);
  306. await clearAppData();
  307. } finally {
  308. await proxy?.close();
  309. await rm(cacheDir, { recursive: true, force: true });
  310. }
  311. });
  312. it("R3-UPDATE-CANCEL-01/02 本机下载显示进度、可取消且不写远端;远端阶段不可取消,重试后重装完成", async function () {
  313. this.timeout(25 * 60_000);
  314. // worker 修改 process.env 无法影响已创建的 Electron;三项必须由 runner 在 WDIO 启动前注入。
  315. expect(process.env.ZCODE_DEV_REMOTE_ASSET_USE_CDN).toBe("1");
  316. expect(process.env.ZCODE_REMOTE_ASSET_CDN_BASE_URL).toBe(`http://${FAKE_CDN_HOST}`);
  317. expect(process.env.ZCODE_REMOTE_ASSET_CACHE_DIR).toBe(cacheDir);
  318. const config = readSSHRuntimeConfig(CASE_MARKER);
  319. const [workspacePath] = config.workspacePaths;
  320. const { version } = JSON.parse(
  321. await readFile(resolve(DESKTOP_ROOT, "../../package.json"), "utf8"),
  322. ) as { version: string };
  323. const versionCacheDir = join(cacheDir, "source-server", version);
  324. proxy = await startRemoteAssetHttpProxy({
  325. expectedHost: FAKE_CDN_HOST,
  326. mockCdnRoot: MOCK_CDN_ROOT,
  327. });
  328. await rm(cacheDir, { recursive: true, force: true });
  329. // Bug 原因:旧 App 仍在启动时,Host 会把内存里的设置写回文件;在它存活时种代理会被覆盖,
  330. // 重载后代理为 direct,首装连不到测试 CDN(本机 4 次运行中 2 次)。种子在旧进程退出后写入。
  331. const { proxyUrl } = proxy;
  332. await reloadElectronSessionPreservingBrowserProfile(browser, {
  333. afterElectronProcessExit: async () => {
  334. await seedSettings({ httpProxy: proxyUrl, httpProxyNoProxy: PROXY_NO_PROXY });
  335. },
  336. });
  337. await prepareV4ConversationE2E({ skipProvider: true });
  338. await installSourceManagementRpc();
  339. // 首连:干净目标经测试 CDN 安装(不限速)。
  340. await openSSHRemoteDialog(CASE_MARKER);
  341. await fillSSHPasswordSettings(config);
  342. await clickLastEnabledSSHDialogButton(CASE_MARKER);
  343. expect(await waitForSSHDirectoryStep(CASE_MARKER)).toBe("directory");
  344. const profileId = (await readSettings()).connectionProfiles?.find(
  345. (profile) =>
  346. profile.target.kind === "ssh" &&
  347. profile.target.host === config.host &&
  348. profile.target.port === config.port,
  349. )?.profileId;
  350. if (!profileId) throw new Error(`${CASE_MARKER}: 首连后缺少线路`);
  351. await waitForSourceManagementRpcReady(CASE_MARKER);
  352. // 首次安装复用同一 resolver:此时设备日志是安装那次连接,应有本机下载进度。
  353. // 必须在打开项目之前读取:打开项目会再连接一次(复用在线连接),并替换设备日志。
  354. const installLogs = await readOperationLogs(profileId);
  355. facts.installDownloadLogs = installLogs.filter((entry) => entry.phase === "download");
  356. expect(
  357. installLogs.some(
  358. (entry) => entry.phase === "download" && entry.message.startsWith("download progress:"),
  359. ),
  360. ).toBe(true);
  361. await selectSSHRemoteDirectory(workspacePath, CASE_MARKER);
  362. const tab = await waitForRemoteTab({ caseMarker: CASE_MARKER, expectedPath: workspacePath });
  363. const identity = tab.workspaceIdentity!;
  364. const sourceServerId = parseRemoteWorkspaceIdentity(identity)?.sourceServerId;
  365. if (!sourceServerId) throw new Error(`${CASE_MARKER}: 首连后缺少设备身份`);
  366. const installedPackage = await readRemotePackageJson(config);
  367. expect(installedPackage).not.toMatch(/^0 /u);
  368. facts.installed = { tab, profileId, installedPackage };
  369. await mark("installed");
  370. // R3-UPDATE-CANCEL-01:损坏 release → 清空本机缓存并限速 → 向导失败页重新安装。
  371. await disconnectRemoteSource(sourceServerId, CASE_MARKER, { workspaceIdentities: [identity] });
  372. await damageCurrentRelease(config);
  373. expect(await readRemotePackageJson(config)).toMatch(/^0 /u);
  374. await rm(cacheDir, { recursive: true, force: true });
  375. proxy.setArchiveBytesPerSecond(SLOW_ARCHIVE_BYTES_PER_SECOND);
  376. await requestRemoteProjectConnection(identity, CASE_MARKER);
  377. await clickFailedBannerReconnect();
  378. await startWizardReinstall();
  379. await mark("reinstall-started");
  380. await browser.waitUntil(async () => ((await readDownloadProgress()) ?? 0) > 0, {
  381. timeout: 120_000,
  382. interval: 500,
  383. timeoutMsg: `${CASE_MARKER}: 本机下载期间向导日志没有下载进度`,
  384. });
  385. const initialProgress = (await readDownloadProgress())!;
  386. await browser.waitUntil(async () => ((await readDownloadProgress()) ?? 0) > initialProgress, {
  387. timeout: 15_000,
  388. timeoutMsg: `${CASE_MARKER}: 下载进度没有在原有一行中更新`,
  389. });
  390. const localState = await readProfileState(profileId);
  391. const localButtons = await readWizardButtons();
  392. const localLogs = await readOperationLogs(profileId);
  393. facts.localStage = { state: localState, buttons: localButtons, logs: localLogs };
  394. await captureThemeScreenshots("local-download");
  395. expect(localState).toMatchObject({ state: "updating", updateCancelable: true });
  396. expect(
  397. localLogs.some(
  398. (entry) => entry.phase === "download" && entry.message.startsWith("download progress:"),
  399. ),
  400. ).toBe(true);
  401. const cancelButtons = localButtons.filter((button) => isCancelButton(button.text));
  402. expect(cancelButtons.length).toBeGreaterThan(0);
  403. expect(cancelButtons.every((button) => !button.disabled)).toBe(true);
  404. expect(
  405. localButtons.find((button) => /^(返回配置|Back to configuration)$/u.test(button.text))
  406. ?.disabled,
  407. ).toBe(true);
  408. await mark("local-stage-observed");
  409. const canceledAt = Date.now();
  410. const clicked = await browser.execute(() => {
  411. const button = Array.from(
  412. document.querySelectorAll<HTMLButtonElement>('[data-testid="ssh-dialog"] button'),
  413. )
  414. .reverse()
  415. .find((item) => /^(取消连接|Cancel connection)$/u.test(item.innerText.trim()));
  416. if (!button || button.disabled) return false;
  417. button.click();
  418. return true;
  419. });
  420. expect(clicked).toBe(true);
  421. // 取消必须立即中止本机请求,而不是等下载结束或网络超时。
  422. await browser.waitUntil(() => Promise.resolve(proxy!.transfers.at(-1)?.aborted === true), {
  423. timeout: 15_000,
  424. interval: 200,
  425. timeoutMsg: `${CASE_MARKER}: 取消后测试 CDN 的 archive 请求没有被中止`,
  426. });
  427. await browser.waitUntil(async () => (await readProfileState(profileId))?.state !== "updating", {
  428. timeout: 15_000,
  429. interval: 500,
  430. timeoutMsg: `${CASE_MARKER}: 取消后设备仍在更新中`,
  431. });
  432. facts.cancelLatencyMs = Date.now() - canceledAt;
  433. const canceledState = await readProfileState(profileId);
  434. const canceledLogs = await readOperationLogs(profileId);
  435. const transfer = proxy.transfers.at(-1)!;
  436. facts.canceled = { state: canceledState, logs: canceledLogs, transfer };
  437. expect(transfer.sentBytes).toBeLessThan(transfer.totalBytes);
  438. expect(canceledState?.updateCancelable).toBeUndefined();
  439. expect(canceledState?.errorCode).toBeUndefined();
  440. expect(canceledLogs.at(-1)).toMatchObject({ operation: "update", level: "info" });
  441. expect(canceledLogs.at(-1)?.message).toMatch(/cancel/iu);
  442. const leftovers = await readdir(versionCacheDir).catch(() => [] as string[]);
  443. facts.cacheAfterCancel = leftovers;
  444. expect(leftovers.filter((name) => name.endsWith(".tmp"))).toEqual([]);
  445. // 本机阶段没有写入远端:release 仍是损坏状态。
  446. expect(await readRemotePackageJson(config)).toMatch(/^0 /u);
  447. await browser.waitUntil(
  448. async () =>
  449. (await readWizardButtons()).some(
  450. (button) => /^(重试|Retry)$/u.test(button.text) && !button.disabled,
  451. ),
  452. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 取消后向导没有进入可重试的已取消状态` },
  453. );
  454. await mark("canceled");
  455. // R3-UPDATE-CANCEL-02:解除限速后重试,再次重新安装;远端阶段不可取消。
  456. proxy.setArchiveBytesPerSecond(null);
  457. await browser.execute(() => {
  458. Array.from(document.querySelectorAll<HTMLButtonElement>('[data-testid="ssh-dialog"] button'))
  459. .find((item) => /^(重试|Retry)$/u.test(item.innerText.trim()) && !item.disabled)
  460. ?.click();
  461. });
  462. await startWizardReinstall();
  463. let remoteStage: Record<string, unknown> | undefined;
  464. await browser.waitUntil(
  465. async () => {
  466. const [logs, state] = await Promise.all([
  467. readOperationLogs(profileId),
  468. readProfileState(profileId),
  469. ]);
  470. const phase = logs.at(-1)?.phase;
  471. if (state?.state !== "updating" || !phase || !REMOTE_STAGE_PHASES.has(phase)) return false;
  472. remoteStage = { phase, state, buttons: await readWizardButtons() };
  473. return true;
  474. },
  475. {
  476. timeout: 180_000,
  477. interval: 200,
  478. timeoutMsg: `${CASE_MARKER}: 没有观察到更新进入远端阶段`,
  479. },
  480. );
  481. facts.remoteStage = remoteStage;
  482. expect((remoteStage!.state as { updateCancelable?: boolean }).updateCancelable).toBeUndefined();
  483. const remoteButtons = remoteStage!.buttons as Array<{ text: string; disabled: boolean }>;
  484. expect(remoteButtons.filter((button) => isCancelButton(button.text)).length).toBeGreaterThan(0);
  485. expect(
  486. remoteButtons.filter((button) => isCancelButton(button.text)).every((b) => b.disabled),
  487. ).toBe(true);
  488. await mark("remote-stage-observed");
  489. const reconnected = await waitForRemoteTab({
  490. caseMarker: CASE_MARKER,
  491. expectedIdentity: identity,
  492. expectedPath: workspacePath,
  493. timeoutMs: 5 * 60_000,
  494. });
  495. expect(reconnected.remoteSessionId).toBeTruthy();
  496. expect(await readRemotePackageJson(config)).toBe(installedPackage);
  497. facts.reconnected = reconnected;
  498. await mark("reinstalled");
  499. context = { config, profileId, identity, workspacePath, versionCacheDir };
  500. });
  501. // CR-02:在线设备的更新在本机下载期间,旧在线连接关闭(更新的预期断线,只做连接失效)。修复前失效投影
  502. // 重新写入 updating 时丢掉 updateCancelable,Host 实际仍可取消;修复后该字段只由更新 flight 推导。
  503. it("R3-UPDATE-CANCEL-03 在线设备本机下载期间旧连接关闭,快照仍可取消;取消立即中止并恢复在线", async function () {
  504. this.timeout(10 * 60_000);
  505. const { config, profileId, identity, workspacePath, versionCacheDir } = requireContext();
  506. expect((await readProfileState(profileId))?.state).toBe("online");
  507. await rm(cacheDir, { recursive: true, force: true });
  508. proxy!.setArchiveBytesPerSecond(HELD_ARCHIVE_BYTES_PER_SECOND);
  509. const transfersBefore = proxy!.transfers.length;
  510. // 模拟设备卡「更新」:经 Host RPC 对在线设备发起更新,不经过向导。
  511. const updateKey = await startSourceManagementCall("updateSource", [{ profileId }]);
  512. const downloading = await waitForLocalDownload(profileId, transfersBefore);
  513. const transfer = proxy!.transfers.at(-1)!;
  514. await mark("03-local-download");
  515. // 停远端服务让在线连接关闭;Host 把它当作更新的预期断线,做连接失效并重新写入 updating。
  516. await stopRemoteService(config);
  517. const afterClose = await pollFor(
  518. () => readProfileState(profileId),
  519. (state) => (state?.updatedAt ?? 0) > (downloading?.updatedAt ?? 0),
  520. 60_000,
  521. );
  522. facts.closeDuringDownload03 = { downloading, afterClose, transfer: { ...transfer } };
  523. await mark("03-closed-during-download");
  524. // 先取消并等收口,再断言:修复前快照虽丢了字段,Host 仍能取消;04 需要恢复在线的设备。
  525. const canceledAt = Date.now();
  526. const cancel = await callSourceManagement<{ canceled: boolean }>("cancelSourceUpdate", [
  527. profileId,
  528. ]);
  529. const aborted = await pollFor(() => transfer.aborted, Boolean, 15_000);
  530. const abortLatencyMs = Date.now() - canceledAt;
  531. const update = await pollFor(() => readSourceManagementCall(updateKey), Boolean, 30_000);
  532. const recovered = await pollFor(
  533. () => readProfileState(profileId),
  534. (state) => state?.state === "online",
  535. 120_000,
  536. );
  537. const leftovers = await readdir(versionCacheDir).catch(() => [] as string[]);
  538. facts.canceled03 = {
  539. cancel,
  540. abortLatencyMs,
  541. transfer: { ...transfer },
  542. update,
  543. recovered,
  544. leftovers,
  545. };
  546. await mark("03-canceled");
  547. expect(afterClose?.updatedAt).toBeGreaterThan(downloading?.updatedAt ?? 0);
  548. expect(afterClose).toMatchObject({ state: "updating", updateCancelable: true });
  549. expect(cancel.canceled).toBe(true);
  550. expect(aborted).toBe(true);
  551. expect(transfer.sentBytes).toBeLessThan(transfer.totalBytes);
  552. expect(update).toMatchObject({ ok: false, code: "remote-connection-canceled" });
  553. expect(leftovers.filter((name) => name.endsWith(".tmp"))).toEqual([]);
  554. // 取消不是断开:恢复意图仍在,Host 重新拉起远端服务恢复在线,原项目重新连接。
  555. expect(recovered).toMatchObject({ state: "online" });
  556. expect(recovered?.updateCancelable).toBeUndefined();
  557. expect(recovered?.errorCode).toBeUndefined();
  558. const reconnected = await waitForRemoteTab({
  559. caseMarker: CASE_MARKER,
  560. expectedIdentity: identity,
  561. expectedPath: workspacePath,
  562. timeoutMs: 3 * 60_000,
  563. });
  564. expect(reconnected.remoteSessionId).toBeTruthy();
  565. await mark("03-recovered");
  566. });
  567. // CR-01:同一线路连续两次更新。修复前 Host 允许并存,后一次把前一次写的 updating 记成更新前状态,
  568. // 取消后可能一直停在“更新中”;修复后第二次在写操作日志前被拒绝,前一次收口后才能再次更新。
  569. it("R3-UPDATE-CANCEL-04 同一线路已有更新时第二次更新被拒绝;取消后恢复在线,之后可再次更新", async function () {
  570. this.timeout(10 * 60_000);
  571. const { profileId, versionCacheDir } = requireContext();
  572. expect((await readProfileState(profileId))?.state).toBe("online");
  573. await rm(cacheDir, { recursive: true, force: true });
  574. proxy!.setArchiveBytesPerSecond(HELD_ARCHIVE_BYTES_PER_SECOND);
  575. const transfersBefore = proxy!.transfers.length;
  576. const firstKey = await startSourceManagementCall("updateSource", [{ profileId }]);
  577. await waitForLocalDownload(profileId, transfersBefore);
  578. // 模拟两个入口在 updating 快照到达前各发一次:绕过 UI 的按钮禁用,直接经 Host RPC 再发一次。
  579. const secondKey = await startSourceManagementCall("updateSource", [{ profileId }]);
  580. const second = await pollFor(() => readSourceManagementCall(secondKey), Boolean, 15_000);
  581. facts.second04 = second ?? "pending after 15s";
  582. await mark("04-second-update-sent");
  583. const cancel = await callSourceManagement<{ canceled: boolean }>("cancelSourceUpdate", [
  584. profileId,
  585. ]);
  586. const first = await pollFor(() => readSourceManagementCall(firstKey), Boolean, 30_000);
  587. const secondSettled =
  588. second ?? (await pollFor(() => readSourceManagementCall(secondKey), Boolean, 30_000));
  589. // 两次请求都已收口后,设备不能停在“更新中”。
  590. const settled = await pollFor(
  591. () => readProfileState(profileId),
  592. (state) => state?.state !== "updating",
  593. 20_000,
  594. );
  595. // 代理侧在 socket 关闭时才标记 aborted,先等它落定再取快照。
  596. await pollFor(
  597. () => proxy!.transfers.slice(transfersBefore).every((item) => item.aborted),
  598. Boolean,
  599. 15_000,
  600. );
  601. const transfers = proxy!.transfers.slice(transfersBefore).map((item) => ({ ...item }));
  602. const logs = await readOperationLogs(profileId);
  603. facts.settled04 = {
  604. cancel,
  605. first,
  606. second: secondSettled,
  607. settled,
  608. transfers,
  609. lastLog: logs.at(-1),
  610. };
  611. await mark("04-settled");
  612. expect(second).toMatchObject({ ok: false, code: "source-server-operation-in-progress" });
  613. expect(cancel.canceled).toBe(true);
  614. expect(first).toMatchObject({ ok: false, code: "remote-connection-canceled" });
  615. expect(settled).toMatchObject({ state: "online" });
  616. expect(settled?.updateCancelable).toBeUndefined();
  617. expect(settled?.errorCode).toBeUndefined();
  618. // 被拒绝的更新没有下载,也没有替换设备操作日志。
  619. expect(transfers.length).toBe(1);
  620. expect(transfers.every((item) => item.aborted)).toBe(true);
  621. expect(logs.at(-1)).toMatchObject({ operation: "update", level: "info" });
  622. // 前一次收口后同一线路可以再次更新:互斥只持续到前一次结束。
  623. const retryBefore = proxy!.transfers.length;
  624. const thirdKey = await startSourceManagementCall("updateSource", [{ profileId }]);
  625. await waitForLocalDownload(profileId, retryBefore);
  626. const thirdCancel = await callSourceManagement<{ canceled: boolean }>("cancelSourceUpdate", [
  627. profileId,
  628. ]);
  629. const third = await pollFor(() => readSourceManagementCall(thirdKey), Boolean, 30_000);
  630. const final = await pollFor(
  631. () => readProfileState(profileId),
  632. (state) => state?.state === "online",
  633. 30_000,
  634. );
  635. const leftovers = await readdir(versionCacheDir).catch(() => [] as string[]);
  636. facts.third04 = { thirdCancel, third, final, leftovers };
  637. await mark("04-third-update-canceled");
  638. expect(thirdCancel.canceled).toBe(true);
  639. expect(third).toMatchObject({ ok: false, code: "remote-connection-canceled" });
  640. expect(final).toMatchObject({ state: "online" });
  641. expect(leftovers.filter((name) => name.endsWith(".tmp"))).toEqual([]);
  642. });
  643. // RDUX-13-LOG-01:远端下载由容器内 wget 完成,进度是远端脚本每秒输出的纯文本行(不带 progress)。
  644. // 修复前 Host 只合并带 progress 的进度,这类行逐条追加进 100 行窗口:设备页刷屏,下载超过约 100 秒后
  645. // 同次更新的开始日志也被挤出。修复后 Host 写入时按传输键只保留最新一行。
  646. it("RDUX-13-LOG-01 远端下载的纯文本进度在 Host 日志与设备页只占一行,开始日志保留", async function () {
  647. this.timeout(12 * 60_000);
  648. const { config, profileId } = requireContext();
  649. expect((await readProfileState(profileId))?.state).toBe("online");
  650. const profile = (await readSettings()).connectionProfiles?.find(
  651. (item) => item.profileId === profileId,
  652. );
  653. if (profile?.target.kind !== "ssh") throw new Error(`${CASE_MARKER}: 缺少 SSH 线路`);
  654. const {
  655. passwordCredentialKey: _passwordKey,
  656. privateKeyPassphraseCredentialKey: _passphraseKey,
  657. ...target
  658. } = profile.target;
  659. const saveTarget = (next: typeof target) =>
  660. callSourceManagement("updateProfile", [
  661. {
  662. profileId,
  663. // 与编辑线路弹窗的默认名一致,不改变线路名称。
  664. profileDisplayName: profile.displayName ?? profile.transport,
  665. sshAuthMethod: "password",
  666. target: { ...next, password: config.password },
  667. },
  668. ]);
  669. // 容器经 host.docker.internal 访问宿主回环上的测试 CDN 代理;远端 wget 读 ~/.wgetrc 走代理。
  670. const containerProxyUrl = `http://host.docker.internal:${new URL(proxy!.proxyUrl).port}/`;
  671. await runSSHCommand(
  672. config,
  673. `printf 'use_proxy = on\\nhttp_proxy = %s\\n' '${containerProxyUrl}' > "$HOME/.wgetrc"`,
  674. );
  675. proxy!.setArchiveBytesPerSecond(REMOTE_ARCHIVE_BYTES_PER_SECOND);
  676. await saveTarget({ ...target, assetInstallMode: "remote-download" });
  677. try {
  678. const transfersBefore = proxy!.transfers.length;
  679. const updateKey = await startSourceManagementCall("updateSource", [{ profileId }]);
  680. const first = await pollFor(
  681. () => readOperationLogs(profileId),
  682. (logs) => logs.some(isRemoteTextProgress),
  683. 180_000,
  684. );
  685. const firstSampleAt = Date.now();
  686. const firstSample = first.find(isRemoteTextProgress)?.message;
  687. facts.remoteFirst = first;
  688. await mark("log-01-remote-progress");
  689. expect(firstSample).toBeTruthy();
  690. // 第二条样本到达后 Host 仍只有一行;修复前此时已有两行。
  691. const second = await pollFor(
  692. () => readOperationLogs(profileId),
  693. (logs) => {
  694. const rows = logs.filter(isRemoteTextProgress);
  695. return rows.length > 1 || rows[0]?.message !== firstSample;
  696. },
  697. 30_000,
  698. );
  699. facts.remoteSecond = second;
  700. // 文本进度来自远端经测试 CDN 的下载,而不是本机下载;代理读完 archive 才登记传输,需要等待。
  701. const remoteTransfer = await pollFor(
  702. () => proxy!.transfers.length > transfersBefore,
  703. Boolean,
  704. 30_000,
  705. );
  706. expect(remoteTransfer).toBe(true);
  707. expect(second.filter(isRemoteTextProgress)).toHaveLength(1);
  708. expect(second.find(isRemoteTextProgress)?.message).not.toBe(firstSample);
  709. // 设备页直接展示 Host 查询结果:进度刷新后仍只有一行。
  710. await openDeviceUpdateLog();
  711. await browser.waitUntil(async () => (await readDeviceDownloadRows()).length > 0, {
  712. timeout: 15_000,
  713. timeoutMsg: `${CASE_MARKER}: 设备更新日志未显示远端下载进度`,
  714. });
  715. const initialRows = (await readDeviceDownloadRows()).join("\n");
  716. await browser.waitUntil(
  717. async () => (await readDeviceDownloadRows()).join("\n") !== initialRows,
  718. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 设备更新日志的远端下载进度未刷新` },
  719. );
  720. const deviceRows = await readDeviceDownloadRows();
  721. facts.remoteDeviceRows = deviceRows;
  722. expect(deviceRows).toHaveLength(1);
  723. await captureThemeScreenshots("device-remote-download-single-line");
  724. // 样本数超过 Host 的 100 行窗口、下载仍未结束时,同次更新的开始日志仍在。
  725. await browser.pause(Math.max(0, firstSampleAt + REMOTE_PROGRESS_OVER_WINDOW_MS - Date.now()));
  726. const late = await readOperationLogs(profileId);
  727. facts.remoteLate = late;
  728. await mark("log-01-remote-progress-over-window");
  729. const lateRows = late.filter(isRemoteTextProgress);
  730. expect(lateRows).toHaveLength(1);
  731. expect(Number(/ (\d+(?:\.\d+)?)%/u.exec(lateRows[0]!.message)?.[1])).toBeLessThan(100);
  732. expect(late[0]).toMatchObject({ operation: "update", message: "Checking the remote device" });
  733. // 远端阶段不可取消:等更新完成,结束后仍只有一行进度。
  734. const update = await pollFor(() => readSourceManagementCall(updateKey), Boolean, 5 * 60_000);
  735. const online = await pollFor(
  736. () => readProfileState(profileId),
  737. (state) => state?.state === "online",
  738. 120_000,
  739. );
  740. const finalLogs = await readOperationLogs(profileId);
  741. facts.remoteFinal = { update, online, logs: finalLogs };
  742. await mark("log-01-remote-update-completed");
  743. expect(update).toMatchObject({ ok: true });
  744. expect(online).toMatchObject({ state: "online" });
  745. expect(finalLogs.filter(isRemoteTextProgress)).toHaveLength(1);
  746. expect(finalLogs[0]).toMatchObject({ message: "Checking the remote device" });
  747. expect(finalLogs.at(-1)).toMatchObject({ phase: "ready" });
  748. } finally {
  749. proxy!.setArchiveBytesPerSecond(null);
  750. await runSSHCommand(config, 'rm -f "$HOME/.wgetrc"').catch(() => undefined);
  751. await saveTarget(target).catch(() => undefined);
  752. }
  753. });
  754. });