conversation-session-r3-soak-dual.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import { openMobilePairingPage, seedMobileFixtureLogin } from "#e2e/helpers/mobile-pairing";
  2. import { execFile } from "node:child_process";
  3. import { mkdir, writeFile } from "node:fs/promises";
  4. import { resolve } from "node:path";
  5. import { promisify } from "node:util";
  6. import {
  7. TID_TASK_ITEM,
  8. TID_V4_COMPOSER_INPUT,
  9. TID_V4_COMPOSER_SEND,
  10. testId,
  11. } from "@zcode/shared/test-ids";
  12. import { clearAppData } from "#e2e/helpers/desktop-app";
  13. import {
  14. getUpstreamRequestRecordCount,
  15. waitForUpstreamRequest,
  16. } from "#e2e/helpers/conversation-session-network";
  17. import {
  18. connectSSHWorkspaceAndSendFirstTurn,
  19. listRemoteAgentProcesses,
  20. prepareSSHLifecycle,
  21. type SSHLifecycleProvider,
  22. } from "#e2e/helpers/ssh-remote-lifecycle";
  23. import {
  24. readHostProcesses,
  25. readRemoteTabSnapshot,
  26. runSSHCommand,
  27. } from "#e2e/helpers/ssh-remote-p0";
  28. import {
  29. getV4Messages,
  30. sendV4PromptAndWaitAccepted,
  31. waitForV4AssistantMessageContaining,
  32. waitForV4ConversationState,
  33. } from "#e2e/helpers/v4-conversation";
  34. const CASE_MARKER = "E2E_R3_SOAK_DUAL";
  35. const artifactDir = resolve(process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/r3-soak-dual");
  36. // Linux e2e 服务器上没有 macOS 版 Chrome:用 R3_MOBILE_CHROME 指向该机 playwright 下载的
  37. // chromium(缺省仍回退开发机 macOS 路径),否则本 case 在服务器上直接起不了手机浏览器。
  38. const CHROME =
  39. process.env.R3_MOBILE_CHROME?.trim() ||
  40. "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
  41. const MOBILE_VIEWPORT = { width: 390, height: 844 };
  42. const run = promisify(execFile);
  43. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  44. type PwPage = any;
  45. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  46. type PwContext = any;
  47. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  48. type PwBrowser = any;
  49. async function countRemoteSshSessions(container: string): Promise<number> {
  50. const { stdout } = await run("docker", [
  51. "exec",
  52. container,
  53. "sh",
  54. "-c",
  55. "ps -o user=,args= -C sshd | grep -c '^dev ' || true",
  56. ]);
  57. return Number.parseInt(stdout.trim() || "0", 10);
  58. }
  59. /** 打开 Desktop 的“移动端远程控制”对话框并拦截剪贴板取得配对链接(含配对材料,只留内存、不落记录)。 */
  60. async function obtainPairUrl(): Promise<string> {
  61. await browser.execute(() => {
  62. const clipboard = navigator.clipboard;
  63. const original = clipboard.writeText.bind(clipboard);
  64. (
  65. window as Window & { __r3RestoreClipboard?: () => void; __r3PairUrl?: string }
  66. ).__r3RestoreClipboard = () => {
  67. clipboard.writeText = original;
  68. };
  69. clipboard.writeText = async (text: string) => {
  70. (window as Window & { __r3PairUrl?: string }).__r3PairUrl = text;
  71. };
  72. });
  73. const trigger = $('button[aria-label="移动端远程控制"]');
  74. await trigger.waitForClickable({ timeout: 30_000 });
  75. await trigger.click();
  76. await $('[data-testid="web-remote-control-dialog-scroll"]').waitForDisplayed({ timeout: 30_000 });
  77. await browser.waitUntil(
  78. () =>
  79. browser.execute(() => {
  80. const button = Array.from(
  81. document.querySelectorAll<HTMLButtonElement>(
  82. '[data-testid="web-remote-control-dialog-scroll"] button',
  83. ),
  84. ).find((b) => b.innerText.trim() === "复制链接" && !b.disabled);
  85. button?.click();
  86. return Boolean(button);
  87. }),
  88. {
  89. timeout: 60_000,
  90. interval: 500,
  91. timeoutMsg: `${CASE_MARKER}: 复制链接按钮不可用(relay 未就绪?)`,
  92. },
  93. );
  94. let url = "";
  95. await browser.waitUntil(
  96. async () => {
  97. url = (await browser.execute(
  98. () => (window as Window & { __r3PairUrl?: string }).__r3PairUrl ?? "",
  99. )) as string;
  100. return url.startsWith("http");
  101. },
  102. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 没有取得配对链接` },
  103. );
  104. await browser.execute(() => {
  105. const w = window as Window & { __r3RestoreClipboard?: () => void; __r3PairUrl?: string };
  106. w.__r3RestoreClipboard?.();
  107. delete w.__r3RestoreClipboard;
  108. delete w.__r3PairUrl;
  109. });
  110. return url;
  111. }
  112. async function readDesktopMobileStatus(): Promise<string> {
  113. return browser.execute(
  114. () =>
  115. document
  116. .querySelector<HTMLElement>('[data-testid="web-remote-control-connection-card"]')
  117. ?.innerText.replace(/\s+/gu, " ")
  118. .slice(0, 200) ?? "",
  119. );
  120. }
  121. async function closeRemoteControlDialog(): Promise<void> {
  122. await browser.keys(["Escape"]);
  123. await browser
  124. .waitUntil(
  125. () =>
  126. browser.execute(
  127. () => !document.querySelector('[data-testid="web-remote-control-dialog-scroll"]'),
  128. ),
  129. { timeout: 10_000, timeoutMsg: `${CASE_MARKER}: 远程控制对话框没有关闭` },
  130. )
  131. .catch(() => undefined);
  132. }
  133. async function mobileText(page: PwPage): Promise<string> {
  134. return (await page.evaluate(() => document.body?.innerText ?? "")) as string;
  135. }
  136. const SOAK_MINUTES = Number(process.env.R3_SOAK2_MINUTES?.trim() || "25");
  137. interface Sample {
  138. round: number;
  139. t: number;
  140. hosts: number;
  141. agents: number;
  142. ssh: number;
  143. remoteLogBytes: number;
  144. desktopTurnMs: number;
  145. mobileTurnMs: number;
  146. mobileOfflineRecovered: boolean | null;
  147. mobileEchoOk: boolean | null;
  148. rssMb: number | null;
  149. }
  150. describe(`${CASE_MARKER}: Desktop continuous + Mobile replayable 同时运行的缩短版 soak`, () => {
  151. let provider: SSHLifecycleProvider | null = null;
  152. let mobileBrowser: PwBrowser = null;
  153. const facts: Record<string, unknown> = {};
  154. const samples: Sample[] = [];
  155. after(async () => {
  156. facts.samples = samples;
  157. await mkdir(artifactDir, { recursive: true });
  158. await writeFile(resolve(artifactDir, "soak-dual.json"), JSON.stringify(facts, null, 2));
  159. await mobileBrowser?.close().catch(() => undefined);
  160. mobileBrowser = null;
  161. await provider?.tunnel.close().catch(() => undefined);
  162. provider = null;
  163. await browser.electron.restoreAllMocks();
  164. await clearAppData();
  165. });
  166. it(`R3A-SOAK-02 ${SOAK_MINUTES} 分钟:桌面与手机交替输入、每 3 轮手机断网恢复;无挂死/丢输入;Host/Agent/远端日志体积趋势可解释`, async function () {
  167. if (!Number.isFinite(SOAK_MINUTES) || SOAK_MINUTES <= 0) {
  168. throw new Error(`${CASE_MARKER}: R3_SOAK2_MINUTES 必须是正数,不能跳过长稳循环`);
  169. }
  170. this.timeout((SOAK_MINUTES + 20) * 60_000);
  171. const container = process.env.ZCODE_E2E_SSH_CONTAINER?.trim();
  172. if (!container) throw new Error(`${CASE_MARKER}: 缺少 ZCODE_E2E_SSH_CONTAINER`);
  173. const prepared = await prepareSSHLifecycle(CASE_MARKER, {
  174. apiType: "anthropic-messages",
  175. tunnelUsername: "tunnel",
  176. });
  177. provider = prepared.provider;
  178. const [workspaceA] = prepared.config.workspacePaths;
  179. const taskA = await connectSSHWorkspaceAndSendFirstTurn({
  180. caseMarker: CASE_MARKER,
  181. config: prepared.config,
  182. label: "A",
  183. provider,
  184. workspacePath: workspaceA,
  185. });
  186. const remoteLogBytes = async () =>
  187. Number.parseInt(
  188. (
  189. await runSSHCommand(
  190. prepared.config,
  191. 'F=$(ls -t ~/.zcode/cli/log/*.jsonl | head -n1); stat -c %s "$F"',
  192. )
  193. ).stdout.trim() || "0",
  194. 10,
  195. );
  196. const rss = async () => {
  197. const value = await browser.electron.execute((electron) =>
  198. electron.app.getAppMetrics().reduce((sum, m) => sum + (m.memory?.workingSetSize ?? 0), 0),
  199. );
  200. return typeof value === "number" ? Math.round(value / 1024) : null;
  201. };
  202. const baseline = {
  203. hosts: (await readHostProcesses()).length,
  204. ssh: await countRemoteSshSessions(container),
  205. agents: (await listRemoteAgentProcesses(prepared.config)).length,
  206. remoteLogBytes: await remoteLogBytes(),
  207. rssMb: await rss(),
  208. };
  209. facts.baseline = baseline;
  210. const pairUrl = await obtainPairUrl();
  211. const { chromium } = (await import("playwright-core")) as {
  212. chromium: { launch(o: object): Promise<PwBrowser> };
  213. };
  214. mobileBrowser = await chromium.launch({ headless: true, executablePath: CHROME });
  215. const mobileContext: PwContext = await mobileBrowser.newContext({
  216. viewport: MOBILE_VIEWPORT,
  217. isMobile: true,
  218. hasTouch: true,
  219. locale: "zh-CN",
  220. });
  221. // 新浏览器上下文不继承 Desktop 的测试账号;否则停在登录页,尚未进入长稳循环。
  222. await seedMobileFixtureLogin(mobileContext);
  223. const mobile: PwPage = await mobileContext.newPage();
  224. await openMobilePairingPage(mobile, pairUrl, {
  225. artifactDir,
  226. caseMarker: CASE_MARKER,
  227. phase: "initial",
  228. readySelector: `[data-testid="${testId(TID_TASK_ITEM, taskA.taskId)}"]`,
  229. });
  230. await browser.waitUntil(async () => (await readDesktopMobileStatus()).includes("手机已连接"), {
  231. timeout: 60_000,
  232. timeoutMsg: `${CASE_MARKER}: Desktop 未显示手机已连接`,
  233. });
  234. await closeRemoteControlDialog();
  235. await mobile
  236. .locator(`[data-testid="${testId(TID_TASK_ITEM, taskA.taskId)}"]`)
  237. .first()
  238. .click();
  239. await mobile.getByText(taskA.firstReply, { exact: false }).first().waitFor({ timeout: 60_000 });
  240. const deadline = Date.now() + SOAK_MINUTES * 60_000;
  241. let round = 0;
  242. let lostInputs = 0;
  243. // 0911 修复(首跑 214 轮实录):getV4Messages/mobileText 读的是 DOM 虚拟化窗口,
  244. // 收尾全量对账在 replay 秒回的高轮次(428+ 条消息)下窗口只含少量行,
  245. // desktopMissing=207/214 假失败。改为逐轮增量对账:标记刚发送必在窗口底部。
  246. let desktopMissingLive = 0;
  247. let mobileMissingOnDesktopLive = 0;
  248. let mobileEchoMissing = 0;
  249. while (Date.now() < deadline) {
  250. round += 1;
  251. const sample: Sample = {
  252. round,
  253. t: 0,
  254. hosts: 0,
  255. agents: 0,
  256. ssh: 0,
  257. remoteLogBytes: 0,
  258. desktopTurnMs: 0,
  259. mobileTurnMs: 0,
  260. mobileOfflineRecovered: null,
  261. mobileEchoOk: null,
  262. rssMb: null,
  263. };
  264. const t0 = Date.now();
  265. // 桌面回合。
  266. const d0 = Date.now();
  267. const dMarker = `${CASE_MARKER}_D${round}`;
  268. const start = await getUpstreamRequestRecordCount();
  269. await sendV4PromptAndWaitAccepted(
  270. `${dMarker} 请回复`,
  271. dMarker,
  272. `round ${round}: 桌面输入未被接受`,
  273. );
  274. await waitForUpstreamRequest(
  275. { lastUserMessageIncludes: [dMarker] },
  276. `round ${round}: 桌面输入没有到达回放`,
  277. 90_000,
  278. { afterIndex: start - 1 },
  279. );
  280. await waitForV4ConversationState(
  281. (s) => s.taskId === taskA.taskId && s.state === "idle",
  282. `round ${round}: 桌面回合没有收口`,
  283. 120_000,
  284. );
  285. sample.desktopTurnMs = Date.now() - d0;
  286. // 手机回合(每 3 轮先断网 10s 再恢复后发送)。
  287. if (round % 3 === 0) {
  288. await mobileContext.setOffline(true);
  289. await browser.pause(10_000);
  290. await mobileContext.setOffline(false);
  291. let recovered = false;
  292. for (let i = 0; i < 20 && !recovered; i += 1) {
  293. recovered = (await mobileText(mobile)).includes(dMarker);
  294. if (!recovered) await browser.pause(1_500);
  295. }
  296. sample.mobileOfflineRecovered = recovered;
  297. }
  298. const m0 = Date.now();
  299. const mMarker = `${CASE_MARKER}_M${round}`;
  300. const start2 = await getUpstreamRequestRecordCount();
  301. const composer = mobile.locator(`[data-testid="${TID_V4_COMPOSER_INPUT}"]`).first();
  302. await composer.waitFor({ timeout: 30_000 });
  303. await composer.click();
  304. await mobile.keyboard.type(`${mMarker} 请回复`);
  305. await mobile.locator(`[data-testid="${TID_V4_COMPOSER_SEND}"]`).first().click();
  306. const arrived = await waitForUpstreamRequest(
  307. { lastUserMessageIncludes: [mMarker] },
  308. "mobile",
  309. 90_000,
  310. { afterIndex: start2 - 1 },
  311. )
  312. .then(() => true)
  313. .catch(() => false);
  314. if (!arrived) lostInputs += 1;
  315. await waitForV4ConversationState(
  316. (s) => s.taskId === taskA.taskId && s.state === "idle",
  317. `round ${round}: 手机回合没有收口`,
  318. 120_000,
  319. );
  320. // 增量对账:本轮 _D/_M 刚发生,均在桌面 timeline 虚拟化窗口底部;手机回显同理。
  321. const usersNow = (await getV4Messages("user")).map((m) => m.text ?? "");
  322. if (!usersNow.some((t) => t.includes(dMarker))) desktopMissingLive += 1;
  323. if (!usersNow.some((t) => t.includes(mMarker))) mobileMissingOnDesktopLive += 1;
  324. // 0911 修复(round 29 实录 24/225):手机 DOM 同为虚拟化,断网恢复轮重挂载后
  325. // 立即读 innerText 可能尚未含最新消息。改等待式(最多 ~15s)容忍重挂载,
  326. // 逐轮结果记入 sample 供分布分析。
  327. let mobileEchoOk = false;
  328. for (let i = 0; i < 10 && !mobileEchoOk; i += 1) {
  329. mobileEchoOk = (await mobileText(mobile)).includes(mMarker);
  330. if (!mobileEchoOk) await browser.pause(1_500);
  331. }
  332. if (!mobileEchoOk) mobileEchoMissing += 1;
  333. sample.mobileEchoOk = mobileEchoOk;
  334. sample.mobileTurnMs = Date.now() - m0;
  335. sample.hosts = (await readHostProcesses()).length;
  336. sample.ssh = await countRemoteSshSessions(container);
  337. sample.agents = (await listRemoteAgentProcesses(prepared.config)).length;
  338. sample.remoteLogBytes = await remoteLogBytes();
  339. sample.rssMb = await rss();
  340. sample.t = Date.now() - t0;
  341. samples.push(sample);
  342. }
  343. facts.summary = {
  344. rounds: round,
  345. lostInputs,
  346. desktopMissing: desktopMissingLive,
  347. mobileMissingOnDesktop: mobileMissingOnDesktopLive,
  348. mobileEchoMissing: mobileEchoMissing,
  349. hostsMax: Math.max(...samples.map((s) => s.hosts)),
  350. agentsMax: Math.max(...samples.map((s) => s.agents)),
  351. remoteLogGrowthBytes: (samples.at(-1)?.remoteLogBytes ?? 0) - baseline.remoteLogBytes,
  352. rssMbFirst: samples[0]?.rssMb ?? null,
  353. rssMbLast: samples.at(-1)?.rssMb ?? null,
  354. offlineRecoveryFailures: samples.filter((s) => s.mobileOfflineRecovered === false).length,
  355. };
  356. expect(lostInputs).toBe(0);
  357. // 零轮/未触发断网的样本不能证明长稳;恢复失败必须影响 verdict,不能只写入 facts。
  358. expect(samples.length).toBeGreaterThanOrEqual(3);
  359. expect(samples.some((sample) => sample.mobileOfflineRecovered !== null)).toBe(true);
  360. expect(samples.filter((sample) => sample.mobileOfflineRecovered === false)).toHaveLength(0);
  361. expect((facts.summary as { desktopMissing: number }).desktopMissing).toBe(0);
  362. expect((facts.summary as { mobileMissingOnDesktop: number }).mobileMissingOnDesktop).toBe(0);
  363. expect((facts.summary as { mobileEchoMissing: number }).mobileEchoMissing).toBe(0);
  364. expect((facts.summary as { hostsMax: number }).hostsMax).toBe(baseline.hosts);
  365. expect((facts.summary as { agentsMax: number }).agentsMax).toBeLessThanOrEqual(
  366. baseline.agents + 1,
  367. );
  368. await mobileContext.close();
  369. });
  370. });