conversation-session-r3-mobile.test.ts 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. import { openMobilePairingPage, seedMobileFixtureLogin } from "#e2e/helpers/mobile-pairing";
  2. import { readV4UserMessagesInBrowser } from "#e2e/helpers/mobile-message-evidence";
  3. import { releaseControlledReplay } from "#e2e/helpers/controlled-replay";
  4. import { execFile } from "node:child_process";
  5. import { mkdir, writeFile } from "node:fs/promises";
  6. import { resolve } from "node:path";
  7. import { promisify } from "node:util";
  8. import { parseRemoteWorkspaceIdentity, parseWebRemoteControlAppPayload } from "@zcode/shared";
  9. import { BufferReader, deserialize, VSBuffer } from "@zcode/rpc";
  10. import type { Page, WebSocketRoute } from "playwright-core";
  11. import {
  12. TID_TASK_ITEM,
  13. TID_V4_COMPOSER_INPUT,
  14. TID_V4_COMPOSER_SEND,
  15. TID_V4_SESSION_PANE,
  16. TID_SSH_CONNECT_TRIGGER,
  17. testId,
  18. } from "@zcode/shared/test-ids";
  19. import { clearAppData, DEFAULT_WORKSPACE } from "#e2e/helpers/desktop-app";
  20. import { openWorkspaceDraftFromSidebar } from "#e2e/helpers/workspace-agent-warmup";
  21. import { disconnectRemoteSource } from "#e2e/helpers/remote-project-actions";
  22. import {
  23. countUpstreamRequests,
  24. getUpstreamRequestEvidence,
  25. getUpstreamRequestRecordCount,
  26. waitForUpstreamRequest,
  27. } from "#e2e/helpers/conversation-session-network";
  28. import {
  29. connectSSHWorkspaceAndSendFirstTurn,
  30. listRemoteAgentProcesses,
  31. prepareSSHLifecycle,
  32. type SSHLifecycleProvider,
  33. } from "#e2e/helpers/ssh-remote-lifecycle";
  34. import {
  35. connectSSHWorkspace,
  36. prepareSSHConnectionPage,
  37. readSSHRuntimeConfig,
  38. readHostProcesses,
  39. readRemoteTabSnapshot,
  40. runSSHCommand,
  41. } from "#e2e/helpers/ssh-remote-p0";
  42. import {
  43. prepareV4ConversationE2E,
  44. getV4ConversationState,
  45. getV4Messages,
  46. getV4QueueItems,
  47. sendV4Prompt,
  48. waitForV4AssistantMessageContaining,
  49. waitForV4ConversationState,
  50. waitForV4Pane,
  51. waitForV4QueueCount,
  52. waitForV4TimelineContaining,
  53. } from "#e2e/helpers/v4-conversation";
  54. const CASE_MARKER = "E2E_R3_MOBILE";
  55. const artifactDir = resolve(process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/r3-mobile");
  56. // Linux e2e 服务器上没有 macOS 版 Chrome:用 R3_MOBILE_CHROME 指向该机 playwright 下载的
  57. // chromium(缺省仍回退开发机 macOS 路径),否则本 case 在服务器上直接起不了手机浏览器。
  58. const CHROME =
  59. process.env.R3_MOBILE_CHROME?.trim() ||
  60. "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
  61. const MOBILE_VIEWPORT = { width: 390, height: 844 };
  62. const run = promisify(execFile);
  63. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  64. type PwPage = any;
  65. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  66. type PwContext = any;
  67. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  68. type PwBrowser = any;
  69. async function countRemoteSshSessions(container: string): Promise<number> {
  70. const { stdout } = await run("docker", [
  71. "exec",
  72. container,
  73. "sh",
  74. "-c",
  75. "ps -o user=,args= -C sshd | grep -c '^dev ' || true",
  76. ]);
  77. return Number.parseInt(stdout.trim() || "0", 10);
  78. }
  79. /** 打开 Desktop 的“移动端远程控制”对话框并拦截剪贴板取得配对链接(含配对材料,只留内存、不落记录)。 */
  80. async function obtainPairUrl(): Promise<string> {
  81. await browser.execute(() => {
  82. const clipboard = navigator.clipboard;
  83. const original = clipboard.writeText.bind(clipboard);
  84. (
  85. window as Window & { __r3RestoreClipboard?: () => void; __r3PairUrl?: string }
  86. ).__r3RestoreClipboard = () => {
  87. clipboard.writeText = original;
  88. };
  89. clipboard.writeText = async (text: string) => {
  90. (window as Window & { __r3PairUrl?: string }).__r3PairUrl = text;
  91. };
  92. });
  93. const trigger = $('button[aria-label="移动端远程控制"]');
  94. await trigger.waitForClickable({ timeout: 30_000 });
  95. await trigger.click();
  96. await $('[data-testid="web-remote-control-dialog-scroll"]').waitForDisplayed({ timeout: 30_000 });
  97. await browser.waitUntil(
  98. () =>
  99. browser.execute(() => {
  100. const button = Array.from(
  101. document.querySelectorAll<HTMLButtonElement>(
  102. '[data-testid="web-remote-control-dialog-scroll"] button',
  103. ),
  104. ).find((b) => b.innerText.trim() === "复制链接" && !b.disabled);
  105. button?.click();
  106. return Boolean(button);
  107. }),
  108. {
  109. timeout: 60_000,
  110. interval: 500,
  111. timeoutMsg: `${CASE_MARKER}: 复制链接按钮不可用(relay 未就绪?)`,
  112. },
  113. );
  114. let url = "";
  115. await browser.waitUntil(
  116. async () => {
  117. url = (await browser.execute(
  118. () => (window as Window & { __r3PairUrl?: string }).__r3PairUrl ?? "",
  119. )) as string;
  120. return url.startsWith("http");
  121. },
  122. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 没有取得配对链接` },
  123. );
  124. await browser.execute(() => {
  125. const w = window as Window & { __r3RestoreClipboard?: () => void; __r3PairUrl?: string };
  126. w.__r3RestoreClipboard?.();
  127. delete w.__r3RestoreClipboard;
  128. delete w.__r3PairUrl;
  129. });
  130. return url;
  131. }
  132. async function readDesktopMobileStatus(): Promise<string> {
  133. return browser.execute(
  134. () =>
  135. document
  136. .querySelector<HTMLElement>('[data-testid="web-remote-control-connection-card"]')
  137. ?.innerText.replace(/\s+/gu, " ")
  138. .slice(0, 200) ?? "",
  139. );
  140. }
  141. async function closeRemoteControlDialog(): Promise<void> {
  142. await browser.keys(["Escape"]);
  143. await browser
  144. .waitUntil(
  145. () =>
  146. browser.execute(
  147. () => !document.querySelector('[data-testid="web-remote-control-dialog-scroll"]'),
  148. ),
  149. { timeout: 10_000, timeoutMsg: `${CASE_MARKER}: 远程控制对话框没有关闭` },
  150. )
  151. .catch(() => undefined);
  152. }
  153. async function mobileText(page: PwPage): Promise<string> {
  154. return (await page.evaluate(() => document.body?.innerText ?? "")) as string;
  155. }
  156. async function mobileUserRows(page: PwPage): Promise<Array<{ id: string; text: string }>> {
  157. return page.evaluate(readV4UserMessagesInBrowser, testId(TID_V4_SESSION_PANE, "workspace-main"));
  158. }
  159. /** 只扣真实发送前读取帧;SSH、Host 与业务服务不替换,恢复仍走产品的失效通知入口。 */
  160. async function installSubmissionBridgeProbe(page: Page) {
  161. let armed = false;
  162. let bridgeId: string | undefined;
  163. let held: { bridgeId: string; sequence: number; release(): void; invalidate(): void } | undefined;
  164. let commandMarker: string | undefined;
  165. let accepted:
  166. | { bridgeId: string; rpcId: unknown; invalidate(): void; releaseLate(): void }
  167. | undefined;
  168. let lateReply: string | Buffer | undefined;
  169. let currentRoute: WebSocketRoute | undefined;
  170. let currentServer: WebSocketRoute | undefined;
  171. await page.routeWebSocket(/\/api\/v1\/remote\/ws2(?:\?|$)/u, (route) => {
  172. const server = route.connectToServer();
  173. currentRoute = route;
  174. currentServer = server;
  175. route.onMessage((message) => {
  176. const payload = parseWebRemoteControlAppPayload(JSON.parse(String(message)).payload);
  177. if (
  178. commandMarker &&
  179. !accepted &&
  180. payload?.zcode_type === "rpc-frame" &&
  181. payload.fragmentCount === 1
  182. ) {
  183. const reader = new BufferReader(VSBuffer.wrap(Buffer.from(payload.dataBase64, "base64")));
  184. const header = deserialize(reader) as unknown[];
  185. if (
  186. header[0] === 100 &&
  187. header[2] === "zcode-agent" &&
  188. header[3] === "sendConversationCommandV4"
  189. ) {
  190. const args = deserialize(reader) as Array<{ envelope?: { payload?: { text?: string } } }>;
  191. if (args[0]?.envelope?.payload?.text?.includes(commandMarker)) {
  192. accepted = {
  193. bridgeId: payload.bridgeSessionId,
  194. rpcId: header[1],
  195. invalidate: () =>
  196. route.send(
  197. JSON.stringify({
  198. type: "data",
  199. payload: {
  200. zcode_type: "bridge-degraded",
  201. bridgeSessionId: payload.bridgeSessionId,
  202. reason: "rpc-transport-fault",
  203. },
  204. }),
  205. ),
  206. releaseLate: () => {
  207. if (lateReply) currentRoute?.send(lateReply);
  208. },
  209. };
  210. }
  211. }
  212. }
  213. // 扣帧期间也扣住其 replay 与后续旧 bridge 数据,避免夹具自己制造缺片或漏放原请求。
  214. if (
  215. held &&
  216. payload?.zcode_type === "rpc-frame" &&
  217. payload.bridgeSessionId === held.bridgeId &&
  218. payload.messageSeq >= held.sequence
  219. )
  220. return;
  221. if (armed && !held && payload?.zcode_type === "rpc-frame" && payload.fragmentCount === 1) {
  222. const header = deserialize(
  223. new BufferReader(VSBuffer.wrap(Buffer.from(payload.dataBase64, "base64"))),
  224. ) as unknown[];
  225. if (header[0] === 100 && header[2] === "gen-ui" && header[3] === "listState") {
  226. armed = false;
  227. held = {
  228. bridgeId: payload.bridgeSessionId,
  229. sequence: payload.messageSeq,
  230. release: () => currentServer?.send(message),
  231. invalidate: () =>
  232. route.send(
  233. JSON.stringify({
  234. type: "data",
  235. payload: {
  236. zcode_type: "bridge-degraded",
  237. bridgeSessionId: payload.bridgeSessionId,
  238. reason: "rpc-transport-fault",
  239. },
  240. }),
  241. ),
  242. };
  243. return;
  244. }
  245. }
  246. server.send(message);
  247. });
  248. server.onMessage((message) => {
  249. const payload = parseWebRemoteControlAppPayload(JSON.parse(String(message)).payload);
  250. // MRS06 放行真实提交,只扣该代下行;模型请求是远端接纳的独立证据。
  251. if (
  252. accepted &&
  253. payload?.zcode_type === "rpc-frame" &&
  254. payload.bridgeSessionId === accepted.bridgeId
  255. ) {
  256. if (payload.fragmentCount === 1) {
  257. const header = deserialize(
  258. new BufferReader(VSBuffer.wrap(Buffer.from(payload.dataBase64, "base64"))),
  259. ) as unknown[];
  260. if (header[0] === 201 && header[1] === accepted.rpcId) lateReply = message;
  261. }
  262. return;
  263. }
  264. if (payload?.zcode_type === "workspace-bridge-ready") bridgeId = payload.bridgeSessionId;
  265. route.send(message);
  266. });
  267. });
  268. return {
  269. arm: () => {
  270. armed = true;
  271. },
  272. held: () => held,
  273. bridgeId: () => bridgeId,
  274. armAcceptedCommand: (marker: string) => {
  275. commandMarker = marker;
  276. },
  277. accepted: () => accepted,
  278. hasLateReply: () => lateReply !== undefined,
  279. };
  280. }
  281. async function readMobileControllerServices(
  282. page: Page,
  283. target: {
  284. remoteSessionId: string;
  285. workspacePath: string;
  286. identity: string;
  287. taskId: string;
  288. },
  289. ) {
  290. return page.evaluate(
  291. async ({ moduleUrl, target }) => {
  292. // 读取当前真实服务注册,不向 store 写入测试状态,也不另建 RPC 连接。
  293. const { getRemoteWorkspaceSession } = await import(moduleUrl);
  294. const services = getRemoteWorkspaceSession(target.remoteSessionId)?.services;
  295. if (!services) throw new Error("MRS05 remote services unavailable");
  296. const device = await services.feedbackService.getDeviceSnapshot();
  297. const widgets = await services.genUiService.listState({
  298. workspacePath: target.workspacePath,
  299. workspaceIdentity: target.identity,
  300. sessionId: target.taskId,
  301. });
  302. return {
  303. osPlatform: device.osPlatform,
  304. appVersion: device.appVersion,
  305. widgets: widgets.length,
  306. };
  307. },
  308. {
  309. moduleUrl: `/@fs${resolve(process.cwd(), "../ui/src/store/remoteWorkspaceSessionStore.ts")}`,
  310. target,
  311. },
  312. );
  313. }
  314. describe(`${CASE_MARKER}: 手机 viewport 经真实 relay 配对,选择 SSH task、断网恢复、双端交替输入`, () => {
  315. let provider: SSHLifecycleProvider | null = null;
  316. let mobileBrowser: PwBrowser = null;
  317. const facts: Record<string, unknown> = {};
  318. after(async () => {
  319. await mkdir(artifactDir, { recursive: true });
  320. await writeFile(resolve(artifactDir, "mobile.json"), JSON.stringify(facts, null, 2));
  321. await mobileBrowser?.close().catch(() => undefined);
  322. mobileBrowser = null;
  323. await provider?.tunnel.close().catch(() => undefined);
  324. provider = null;
  325. await browser.electron.restoreAllMocks();
  326. await clearAppData();
  327. });
  328. it("R3A-MOB-01/02/03/07 配对成功且 Host/SSH/Agent 数不增;手机断网恢复独立 replay、桌面 continuous 持续;双端交替输入同一 FIFO 无丢失重复;手机无新建远程能力", async function () {
  329. this.timeout(40 * 60_000);
  330. const container = process.env.ZCODE_E2E_SSH_CONTAINER?.trim();
  331. if (!container) throw new Error(`${CASE_MARKER}: 缺少 ZCODE_E2E_SSH_CONTAINER`);
  332. const prepared = await prepareSSHLifecycle(CASE_MARKER, {
  333. apiType: "anthropic-messages",
  334. tunnelUsername: "tunnel",
  335. });
  336. provider = prepared.provider;
  337. const [workspaceA] = prepared.config.workspacePaths;
  338. const taskA = await connectSSHWorkspaceAndSendFirstTurn({
  339. caseMarker: CASE_MARKER,
  340. config: prepared.config,
  341. label: "A",
  342. provider,
  343. workspacePath: workspaceA,
  344. });
  345. const baseline = {
  346. hosts: (await readHostProcesses()).length,
  347. ssh: await countRemoteSshSessions(container),
  348. agents: (await listRemoteAgentProcesses(prepared.config)).length,
  349. };
  350. facts.baseline = baseline;
  351. // MOB-01:配对。
  352. const pairUrl = await obtainPairUrl();
  353. const parsed = new URL(pairUrl);
  354. facts.pairEntry = {
  355. origin: parsed.origin,
  356. pathname: parsed.pathname,
  357. hasPairingMaterial: Boolean(parsed.search || parsed.hash),
  358. };
  359. const { chromium } = (await import("playwright-core")) as {
  360. chromium: { launch(o: object): Promise<PwBrowser> };
  361. };
  362. mobileBrowser = await chromium.launch({ headless: true, executablePath: CHROME });
  363. let pairingAttempt = 0;
  364. const newMobileContext = async (instrumentSubmission = false) => {
  365. const context = await mobileBrowser.newContext({
  366. viewport: MOBILE_VIEWPORT,
  367. isMobile: true,
  368. hasTouch: true,
  369. locale: "zh-CN",
  370. });
  371. await seedMobileFixtureLogin(context);
  372. const page = await context.newPage();
  373. const submissionProbe = instrumentSubmission
  374. ? await installSubmissionBridgeProbe(page)
  375. : undefined;
  376. await openMobilePairingPage(page, pairUrl, {
  377. artifactDir,
  378. caseMarker: CASE_MARKER,
  379. phase: `pairing-${++pairingAttempt}`,
  380. readySelector: `[data-testid="${testId(TID_TASK_ITEM, taskA.taskId)}"]`,
  381. });
  382. return { context, page, submissionProbe };
  383. };
  384. const first = await newMobileContext(true);
  385. if (!first.submissionProbe) throw new Error("MRS05 wire probe unavailable");
  386. const submissionProbe = first.submissionProbe;
  387. let mobile: PwPage = first.page;
  388. let mobileContext: PwContext = first.context;
  389. await browser.waitUntil(async () => (await readDesktopMobileStatus()).includes("手机已连接"), {
  390. timeout: 60_000,
  391. timeoutMsg: `${CASE_MARKER}: Desktop 未显示手机已连接`,
  392. });
  393. facts.paired = { desktopCard: await readDesktopMobileStatus() };
  394. await closeRemoteControlDialog();
  395. // 手机首页列出远程 workspace 与 SSH task;点击进入。
  396. const homeText = await mobileText(mobile);
  397. const hasNewRemoteEntry = await mobile.evaluate(
  398. (triggerId: string) =>
  399. Array.from(
  400. document.querySelectorAll<HTMLElement>(
  401. `[data-testid="${triggerId}"], button, [role="menuitem"]`,
  402. ),
  403. ).some(
  404. (node) =>
  405. node.getClientRects().length > 0 &&
  406. !node.hasAttribute("disabled") &&
  407. node.getAttribute("aria-disabled") !== "true" &&
  408. (node.dataset.testid === triggerId ||
  409. /新建远程|添加设备|新建连接|New remote|Add device|New connection/iu.test(
  410. node.innerText || node.getAttribute("aria-label") || "",
  411. )),
  412. ),
  413. TID_SSH_CONNECT_TRIGGER,
  414. );
  415. facts.mobileHome = {
  416. hasRemoteKind: homeText.includes("远程"),
  417. hasWorkspaceA: homeText.includes("r3-workspace-a"),
  418. hasTask: homeText.includes(taskA.firstPrompt.slice(0, 20)),
  419. summary: homeText.match(/\d+ 个工作区 · \d+ 个任务/u)?.[0] ?? null,
  420. hasNewRemoteEntry,
  421. };
  422. expect(hasNewRemoteEntry).toBe(false);
  423. const taskLocator = mobile.locator(`[data-testid="${testId(TID_TASK_ITEM, taskA.taskId)}"]`);
  424. await taskLocator.first().waitFor({ timeout: 30_000 });
  425. await taskLocator.first().click();
  426. await mobile.getByText(taskA.firstReply, { exact: false }).first().waitFor({ timeout: 60_000 });
  427. const afterOpen = {
  428. hosts: (await readHostProcesses()).length,
  429. ssh: await countRemoteSshSessions(container),
  430. agents: (await listRemoteAgentProcesses(prepared.config)).length,
  431. };
  432. facts.afterMobileOpen = afterOpen;
  433. expect(afterOpen.hosts).toBe(baseline.hosts);
  434. expect(afterOpen.ssh).toBeLessThanOrEqual(baseline.ssh);
  435. expect(afterOpen.agents).toBeLessThanOrEqual(baseline.agents);
  436. expect((await readRemoteTabSnapshot(taskA.identity)).remoteSessionId).toBe(
  437. taskA.remoteSessionId,
  438. );
  439. // MRS05:控制端反馈/Gen UI 读取经过真实手机 attachment,不落到 Linux Source 或等待未知频道。
  440. const controllerServices = await readMobileControllerServices(mobile, {
  441. remoteSessionId: taskA.remoteSessionId,
  442. workspacePath: workspaceA,
  443. identity: taskA.identity,
  444. taskId: taskA.taskId,
  445. });
  446. expect(controllerServices.osPlatform).toBe(process.platform);
  447. expect(controllerServices.widgets).toBeGreaterThanOrEqual(0);
  448. const submissionMarker = `${CASE_MARKER}_MRS_UNSENT`;
  449. const submissionInput = mobile.getByTestId(TID_V4_COMPOSER_INPUT).first();
  450. submissionProbe.arm();
  451. await submissionInput.fill(submissionMarker);
  452. await mobile.getByTestId(TID_V4_COMPOSER_SEND).first().click();
  453. await browser.waitUntil(() => Boolean(submissionProbe.held()), {
  454. timeout: 30_000,
  455. timeoutMsg: "MRS05 没有捕获真实 gen-ui.listState 请求",
  456. });
  457. const heldSubmission = submissionProbe.held()!;
  458. heldSubmission.invalidate();
  459. await browser.waitUntil(() => submissionProbe.bridgeId() !== heldSubmission.bridgeId, {
  460. timeout: 60_000,
  461. timeoutMsg: "MRS05 未重建失效 bridge",
  462. });
  463. await mobile.waitForFunction(
  464. (marker: string) =>
  465. document.querySelector('[data-testid="v4-composer-input"]')?.textContent?.includes(marker),
  466. submissionMarker,
  467. );
  468. heldSubmission.release();
  469. expect(await countUpstreamRequests({ lastUserMessageIncludes: [submissionMarker] })).toBe(0);
  470. await mobile.screenshot({ path: resolve(artifactDir, "mrs05-draft-recovered.png") });
  471. await submissionInput.fill("");
  472. facts.mrs05 = { controllerServices, draftRestored: true, staleFrameReleased: true };
  473. // MRS06:真实 Agent 已接纳,手机还没收到 ACK/投影;终结旧 RPC 不能重复发送或清除后续草稿。
  474. const acceptedMarker = `${CASE_MARKER}_MRS_ACK`;
  475. const laterDraft = `${CASE_MARKER}_MRS_LATER_DRAFT`;
  476. const acceptedStart = await getUpstreamRequestRecordCount();
  477. submissionProbe.armAcceptedCommand(acceptedMarker);
  478. await submissionInput.fill(acceptedMarker);
  479. await mobile.getByTestId(TID_V4_COMPOSER_SEND).first().click();
  480. await waitForUpstreamRequest(
  481. { lastUserMessageIncludes: [acceptedMarker] },
  482. "MRS06 原命令没有到达远端模型",
  483. 60_000,
  484. { afterIndex: acceptedStart - 1 },
  485. );
  486. const accepted = submissionProbe.accepted();
  487. expect(accepted).toBeDefined();
  488. await browser.waitUntil(() => submissionProbe.hasLateReply(), {
  489. timeout: 30_000,
  490. timeoutMsg: "MRS06 未扣住真实 command ACK,不能注入恢复故障",
  491. });
  492. await submissionInput.fill(laterDraft);
  493. accepted!.invalidate();
  494. await browser.waitUntil(() => submissionProbe.bridgeId() !== accepted!.bridgeId, {
  495. timeout: 60_000,
  496. timeoutMsg: "MRS06 已接纳命令后的 bridge 未恢复",
  497. });
  498. await browser.waitUntil(
  499. async () => (await mobileUserRows(mobile)).some((row) => row.text.includes(acceptedMarker)),
  500. {
  501. timeout: 60_000,
  502. timeoutMsg: "MRS06 手机未恢复已接纳输入",
  503. },
  504. );
  505. await mobile.waitForFunction(
  506. (marker: string) =>
  507. document.querySelector('[data-testid="v4-composer-input"]')?.textContent?.includes(marker),
  508. laterDraft,
  509. );
  510. expect(submissionProbe.hasLateReply()).toBe(true);
  511. accepted!.releaseLate();
  512. await readMobileControllerServices(mobile, {
  513. remoteSessionId: taskA.remoteSessionId,
  514. workspacePath: workspaceA,
  515. identity: taskA.identity,
  516. taskId: taskA.taskId,
  517. });
  518. expect(
  519. (await mobileUserRows(mobile)).filter((row) => row.text.includes(acceptedMarker)),
  520. ).toHaveLength(1);
  521. expect(await submissionInput.textContent()).toContain(laterDraft);
  522. expect(
  523. await countUpstreamRequests(
  524. { lastUserMessageIncludes: [acceptedMarker] },
  525. { afterIndex: acceptedStart - 1 },
  526. ),
  527. ).toBe(1);
  528. expect(await countUpstreamRequests({ lastUserMessageIncludes: [laterDraft] })).toBe(0);
  529. facts.mrs06 = { acceptedOnce: true, laterDraftPreserved: true, lateReplyReleased: true };
  530. await mobile.screenshot({ path: resolve(artifactDir, "mrs06-accepted-recovered.png") });
  531. await submissionInput.fill("");
  532. // WebSocket 路由只用于 MRS05 扣帧。原有 setOffline 回归必须使用未经拦截的新连接,
  533. // 避免 Playwright 的转发连接改变浏览器真实断网行为。
  534. await mobileContext.close();
  535. const uninstrumented = await newMobileContext();
  536. mobile = uninstrumented.page;
  537. mobileContext = uninstrumented.context;
  538. await mobile
  539. .locator(`[data-testid="${testId(TID_TASK_ITEM, taskA.taskId)}"]`)
  540. .first()
  541. .click();
  542. await mobile.getByText(taskA.firstReply, { exact: false }).first().waitFor({ timeout: 60_000 });
  543. // MOB-02:桌面发起慢回合(running),手机断网 15s 再恢复:手机独立 replay 补齐,桌面持续推进。
  544. const slowStart = await getUpstreamRequestRecordCount();
  545. await sendV4Prompt(`${CASE_MARKER}_SLOW 慢慢回答`);
  546. await waitForV4TimelineContaining("R3_MOBILE_STREAMING", 60_000);
  547. await waitForUpstreamRequest(
  548. { lastUserMessageIncludes: [`${CASE_MARKER}_SLOW`] },
  549. `${CASE_MARKER}: 慢回合没有到达回放`,
  550. 60_000,
  551. { afterIndex: slowStart - 1 },
  552. );
  553. await mobile
  554. .getByText(`${CASE_MARKER}_SLOW`, { exact: false })
  555. .first()
  556. .waitFor({ timeout: 30_000 });
  557. const mobileSawSlowStart = (await mobileText(mobile)).includes(`${CASE_MARKER}_SLOW`);
  558. await mobileContext.setOffline(true);
  559. await browser.pause(15_000);
  560. const desktopDuringOffline = await getV4ConversationState();
  561. expect(desktopDuringOffline.state).toBe("streaming");
  562. // 手机仍离线时结束桌面流,独立完成标记只能在手机恢复 replay 后出现。
  563. await releaseControlledReplay("r3-mob-slow");
  564. await waitForV4AssistantMessageContaining("R3_MOBILE_STREAM_DONE", 120_000);
  565. await waitForV4ConversationState(
  566. (s) => s.taskId === taskA.taskId && s.state === "idle",
  567. `${CASE_MARKER}: 慢回合没有收口`,
  568. 120_000,
  569. );
  570. expect(await mobile.getByText("R3_MOBILE_STREAM_DONE", { exact: false }).count()).toBe(0);
  571. facts.desktopCompletedWhileMobileOffline = true;
  572. await mobileContext.setOffline(false);
  573. let mobileRecovered = false;
  574. for (let i = 0; i < 30 && !mobileRecovered; i += 1) {
  575. const text = await mobileText(mobile);
  576. mobileRecovered =
  577. text.includes("R3_MOBILE_STREAM_DONE") && !/连接中|重新连接/u.test(text.slice(0, 200));
  578. if (!mobileRecovered) await browser.pause(2_000);
  579. }
  580. facts.offlineRecovery = {
  581. mobileSawSlowStart,
  582. desktopStateDuringMobileOffline: desktopDuringOffline.state,
  583. mobileRecovered,
  584. desktopCard: await readDesktopMobileStatus().catch(() => ""),
  585. };
  586. expect(desktopDuringOffline.state).toBe("streaming");
  587. expect(mobileRecovered).toBe(true);
  588. expect(
  589. await countUpstreamRequests(
  590. {
  591. lastUserMessageIncludes: [`${CASE_MARKER}_SLOW`],
  592. excludes: ["Generate a concise title"],
  593. },
  594. { afterIndex: slowStart - 1 },
  595. ),
  596. ).toBe(1);
  597. // 隧道健康探针:远端 loopback 上的回放隧道端口在手机发送前必须仍可连接(区分隧道掉线与产品问题)。
  598. const tunnelPort = new URL(provider.tunnel.baseURL).port;
  599. const probeTunnel = async (label: string) => {
  600. const result = await runSSHCommand(
  601. prepared.config,
  602. `python3 - <<'PY'
  603. import socket
  604. s=socket.socket();s.settimeout(3)
  605. try:
  606. s.connect(("127.0.0.1",${tunnelPort}));print("open")
  607. except Exception as e:
  608. print("closed:"+str(e))
  609. finally:
  610. s.close()
  611. PY`,
  612. );
  613. const value = result.stdout.trim();
  614. (facts.tunnelProbes as Record<string, string>)[label] = value;
  615. return value;
  616. };
  617. facts.tunnelProbes = {};
  618. await probeTunnel("afterOfflineRecovery");
  619. // MOB-03:手机回合运行时桌面输入进入同一队列;释放后按顺序消费,两端各显示一次。
  620. const fifoStart = await getUpstreamRequestRecordCount();
  621. const mobilePrompt = `${CASE_MARKER}_FROM_MOBILE 请回复`;
  622. const composer = mobile.locator(`[data-testid="${TID_V4_COMPOSER_INPUT}"]`).first();
  623. await composer.waitFor({ timeout: 30_000 });
  624. await composer.click();
  625. await mobile.keyboard.type(mobilePrompt);
  626. await mobile.locator(`[data-testid="${TID_V4_COMPOSER_SEND}"]`).first().click();
  627. await waitForUpstreamRequest(
  628. { lastUserMessageIncludes: [`${CASE_MARKER}_FROM_MOBILE`] },
  629. `${CASE_MARKER}: 手机输入没有到达回放`,
  630. 90_000,
  631. { afterIndex: fifoStart - 1 },
  632. ).catch(async (error) => {
  633. await probeTunnel("mobilePromptNoRequest");
  634. throw error;
  635. });
  636. await probeTunnel("afterMobilePromptRequest");
  637. await waitForV4AssistantMessageContaining("R3_MOBILE_FROM_MOBILE_RUNNING", 90_000);
  638. await waitForV4ConversationState(
  639. (s) => s.taskId === taskA.taskId && s.state === "streaming",
  640. `${CASE_MARKER}: 桌面没有看到手机回合运行`,
  641. 30_000,
  642. );
  643. const desktopPrompt = `${CASE_MARKER}_FROM_DESKTOP 请回复`;
  644. await sendV4Prompt(desktopPrompt);
  645. await waitForV4QueueCount(1, 30_000);
  646. const queued = await getV4QueueItems();
  647. expect(queued[0]?.text).toContain(desktopPrompt);
  648. expect(
  649. await countUpstreamRequests(
  650. {
  651. lastUserMessageIncludes: [`${CASE_MARKER}_FROM_DESKTOP`],
  652. excludes: ["Generate a concise title"],
  653. },
  654. { afterIndex: fifoStart - 1 },
  655. ),
  656. ).toBe(0);
  657. facts.desktopInputQueuedBehindMobile = true;
  658. await releaseControlledReplay("r3-mob-from-mobile");
  659. await waitForV4AssistantMessageContaining("R3_MOBILE_FROM_MOBILE_REPLY", 90_000);
  660. await waitForUpstreamRequest(
  661. { lastUserMessageIncludes: [`${CASE_MARKER}_FROM_DESKTOP`] },
  662. `${CASE_MARKER}: 桌面输入没有到达回放`,
  663. 90_000,
  664. { afterIndex: fifoStart - 1 },
  665. );
  666. await waitForV4AssistantMessageContaining("R3_MOBILE_FROM_DESKTOP_REPLY", 90_000);
  667. await waitForV4ConversationState(
  668. (s) => s.taskId === taskA.taskId && s.state === "idle",
  669. `${CASE_MARKER}: 桌面回合没有收口`,
  670. 120_000,
  671. );
  672. await mobile
  673. .getByText("R3_MOBILE_FROM_DESKTOP_REPLY", { exact: false })
  674. .first()
  675. .waitFor({ timeout: 60_000 });
  676. const desktopUsers = (await getV4Messages("user")).map((m) => m.text ?? "");
  677. const mobileUsers = (await mobileUserRows(mobile)).map((row) => row.text);
  678. const sequence = (rows: string[]) =>
  679. rows
  680. .filter(
  681. (text) =>
  682. text.includes(`${CASE_MARKER}_FROM_MOBILE`) ||
  683. text.includes(`${CASE_MARKER}_FROM_DESKTOP`),
  684. )
  685. .map((text) => (text.includes(`${CASE_MARKER}_FROM_MOBILE`) ? "mobile" : "desktop"));
  686. const requestCounts = await Promise.all(
  687. ["MOBILE", "DESKTOP"].map((side) =>
  688. countUpstreamRequests(
  689. {
  690. lastUserMessageIncludes: [`${CASE_MARKER}_FROM_${side}`],
  691. excludes: ["Generate a concise title"],
  692. },
  693. { afterIndex: fifoStart - 1 },
  694. ),
  695. ),
  696. );
  697. const requestOrder = (await getUpstreamRequestEvidence({}, { afterIndex: fifoStart - 1 }))
  698. .map((request) => request.fixtureId)
  699. .filter((id) => id === "r3-mob-from-mobile" || id === "r3-mob-from-desktop");
  700. facts.fifo = {
  701. desktopMobilePromptCount: desktopUsers.filter((t) => t.includes(`${CASE_MARKER}_FROM_MOBILE`))
  702. .length,
  703. desktopDesktopPromptCount: desktopUsers.filter((t) =>
  704. t.includes(`${CASE_MARKER}_FROM_DESKTOP`),
  705. ).length,
  706. mobileMobilePromptCount: mobileUsers.filter((text) =>
  707. text.includes(`${CASE_MARKER}_FROM_MOBILE`),
  708. ).length,
  709. mobileDesktopPromptCount: mobileUsers.filter((text) =>
  710. text.includes(`${CASE_MARKER}_FROM_DESKTOP`),
  711. ).length,
  712. desktopSequence: sequence(desktopUsers),
  713. mobileSequence: sequence(mobileUsers),
  714. requestCounts,
  715. requestOrder,
  716. };
  717. expect(facts.fifo).toMatchObject({
  718. desktopMobilePromptCount: 1,
  719. desktopDesktopPromptCount: 1,
  720. mobileMobilePromptCount: 1,
  721. mobileDesktopPromptCount: 1,
  722. desktopSequence: ["mobile", "desktop"],
  723. mobileSequence: ["mobile", "desktop"],
  724. requestCounts: [1, 1],
  725. requestOrder: ["r3-mob-from-mobile", "r3-mob-from-desktop"],
  726. });
  727. // 全新浏览器上下文重新配对(同一链接):恢复到同一 task,不新增 Host/SSH/Agent。
  728. await mobileContext.close();
  729. const second = await newMobileContext();
  730. mobile = second.page;
  731. mobileContext = second.context;
  732. await mobile
  733. .locator(`[data-testid="${testId(TID_TASK_ITEM, taskA.taskId)}"]`)
  734. .first()
  735. .click();
  736. await mobile
  737. .getByText("R3_MOBILE_FROM_DESKTOP_REPLY", { exact: false })
  738. .first()
  739. .waitFor({ timeout: 60_000 });
  740. const afterRepair = {
  741. hosts: (await readHostProcesses()).length,
  742. ssh: await countRemoteSshSessions(container),
  743. agents: (await listRemoteAgentProcesses(prepared.config)).length,
  744. };
  745. facts.afterRepair = afterRepair;
  746. // 合同是“不增加”:远端 Agent 可能因空闲回收而减少。
  747. expect(afterRepair.hosts).toBe(baseline.hosts);
  748. expect(afterRepair.ssh).toBeLessThanOrEqual(baseline.ssh);
  749. expect(afterRepair.agents).toBeLessThanOrEqual(baseline.agents);
  750. await waitForV4Pane(
  751. (s) => s.sessionId === taskA.taskId,
  752. `${CASE_MARKER}: 桌面 pane 不在 task A`,
  753. 10_000,
  754. );
  755. // RDUX-08:手机网络保持在线,断开真实 SSH Source,验证设备断线投影与手机原地重连。
  756. const sourceId = parseRemoteWorkspaceIdentity(taskA.identity)?.sourceServerId;
  757. if (!sourceId) throw new Error(`${CASE_MARKER}: 缺少 Source identity`);
  758. const unsentDraft = `${CASE_MARKER}_DISCONNECTED_DRAFT`;
  759. const mobileDraftInput = mobile.locator(`[data-testid="${TID_V4_COMPOSER_INPUT}"]`).first();
  760. await mobileDraftInput.click();
  761. await mobile.keyboard.type(unsentDraft);
  762. await disconnectRemoteSource(sourceId, CASE_MARKER);
  763. const disconnectedBanner = mobile.getByTestId("remote-conversation-banner");
  764. await disconnectedBanner.waitFor({ timeout: 30_000 }).catch(async (error: unknown) => {
  765. await mobile.screenshot({
  766. path: resolve(artifactDir, "mobile-source-disconnect-failure.png"),
  767. });
  768. facts.sourceDisconnectFailure = {
  769. bannerCount: await disconnectedBanner.count(),
  770. composerCount: await mobileDraftInput.count(),
  771. };
  772. throw error;
  773. });
  774. expect(await disconnectedBanner.getAttribute("data-connection-state")).toBe("offline");
  775. expect(await mobileDraftInput.textContent()).toContain(unsentDraft);
  776. expect(
  777. await mobile.locator(`[data-testid="${TID_V4_COMPOSER_SEND}"]`).first().isDisabled(),
  778. ).toBe(true);
  779. await mobile.getByTestId("remote-send-unavailable").waitFor();
  780. // 同一真实手机 Web attachment 下检查设备断线时的深浅主题,保留现有 replayable 链路。
  781. await mkdir(artifactDir, { recursive: true });
  782. for (const [theme, label] of [
  783. ["light", "浅色主题"],
  784. ["dark", "深色主题"],
  785. ]) {
  786. await mobile.getByRole("button", { name: "选择主题", exact: true }).click();
  787. await mobile.getByRole("menuitemradio", { name: label, exact: true }).click();
  788. await mobile.waitForFunction(
  789. (value: string) => document.documentElement.classList.contains(`theme-zai-${value}`),
  790. theme,
  791. );
  792. await mobile.getByRole("menu").waitFor({ state: "hidden" });
  793. await mobile.screenshot({
  794. path: resolve(artifactDir, `mobile-disconnected-conversation-${theme}.png`),
  795. fullPage: true,
  796. animations: "disabled",
  797. });
  798. }
  799. await disconnectedBanner.getByRole("button", { name: "重新连接", exact: true }).click();
  800. await disconnectedBanner.waitFor({ state: "hidden", timeout: 60_000 });
  801. await mobileDraftInput.waitFor().catch(async (error: unknown) => {
  802. await mobile.screenshot({
  803. path: resolve(artifactDir, "mobile-source-reconnect-failure.png"),
  804. });
  805. facts.sourceReconnectFailure = {
  806. text: (await mobileText(mobile)).slice(0, 3000),
  807. historyPage: await mobile.evaluate(() => window.history.state?.zcodeMobilePage ?? null),
  808. };
  809. throw error;
  810. });
  811. expect(await mobileDraftInput.textContent()).toContain(unsentDraft);
  812. expect(await getV4QueueItems()).toHaveLength(0);
  813. expect((await mobileUserRows(mobile)).some((row) => row.text.includes(unsentDraft))).toBe(
  814. false,
  815. );
  816. expect(await countUpstreamRequests({ lastUserMessageIncludes: [unsentDraft] })).toBe(0);
  817. facts.sourceDisconnect = {
  818. draftRetained: true,
  819. sendDisabledWhileOffline: true,
  820. mobileReconnected: true,
  821. draftAutoSubmitted: false,
  822. themes: ["light", "dark"],
  823. };
  824. expect(await countUpstreamRequests({ lastUserMessageIncludes: [submissionMarker] })).toBe(0);
  825. await mobileContext.close();
  826. });
  827. it("RDUX-MOBILE-DRAFT 无模型消息:手机保留草稿在深浅主题禁止发送,横幅重连回原项目", async function () {
  828. this.timeout(15 * 60_000);
  829. const marker = `${CASE_MARKER}_DRAFT_ONLY`;
  830. const config = readSSHRuntimeConfig(marker);
  831. const workspacePath = config.workspacePaths[0];
  832. await mkdir(artifactDir, { recursive: true });
  833. await prepareSSHConnectionPage(marker);
  834. // 上个场景仍停在远程任务;准备函数要求默认项目,不能空等它自动切回。
  835. // 单独运行时保留正常登录路径;已有侧栏才执行项目导航。
  836. if (await $('[data-testid="sidebar"]').isDisplayed())
  837. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  838. await prepareV4ConversationE2E({ skipProvider: true });
  839. const requestBaseline = await getUpstreamRequestRecordCount();
  840. const connected = await connectSSHWorkspace({ caseMarker: marker, config, workspacePath });
  841. const identity = connected.workspaceIdentity;
  842. const sourceId = identity ? parseRemoteWorkspaceIdentity(identity)?.sourceServerId : undefined;
  843. if (!identity || !sourceId) throw new Error(`${marker}: SSH 项目缺少稳定设备身份`);
  844. const projectId = await $(`[data-project-workspace-identity="${identity}"]`).getAttribute(
  845. "data-project-id",
  846. );
  847. if (!projectId) throw new Error(`${marker}: SSH 项目缺少 projectId`);
  848. // 项目创建已打开所属 Source 的草稿;全局新建会改为本地未分类任务。
  849. await browser.execute(() => {
  850. const actions = (window as Window & { __testActions?: { setLocale(locale: string): void } })
  851. .__testActions;
  852. if (!actions) throw new Error("Missing locale actions");
  853. actions.setLocale("zh-CN");
  854. });
  855. await waitForV4Pane((pane) => pane.sessionId === "draft", `${marker}: 桌面不是空草稿`);
  856. expect(await getV4Messages("user")).toHaveLength(0);
  857. const pairUrl = await obtainPairUrl();
  858. const { chromium } = await import("playwright-core");
  859. // 前一场景仅关闭了 context;覆盖句柄前关闭本轮拥有的旧浏览器,避免泄漏进程。
  860. await mobileBrowser?.close();
  861. mobileBrowser = null;
  862. mobileBrowser = await chromium.launch({ headless: true, executablePath: CHROME });
  863. const context: import("playwright-core").BrowserContext = await mobileBrowser.newContext({
  864. viewport: MOBILE_VIEWPORT,
  865. isMobile: true,
  866. hasTouch: true,
  867. locale: "zh-CN",
  868. });
  869. await seedMobileFixtureLogin(context);
  870. const mobile = await context.newPage();
  871. let phase = "pairing";
  872. try {
  873. await openMobilePairingPage(mobile, pairUrl, {
  874. artifactDir,
  875. caseMarker: marker,
  876. phase: "draft-only-pairing",
  877. readySelector: `[data-project-id="${projectId}"]`,
  878. });
  879. await browser.waitUntil(
  880. async () => (await readDesktopMobileStatus()).includes("手机已连接"),
  881. { timeout: 60_000 },
  882. );
  883. await closeRemoteControlDialog();
  884. // 手机与桌面共用 ProjectSidebar;通过原项目的新建入口进入空草稿,不发送准备消息。
  885. const workspaceCard = mobile.locator(`[data-project-id="${projectId}"]`);
  886. await workspaceCard.waitFor();
  887. expect(await workspaceCard.count()).toBe(1);
  888. phase = "open-draft";
  889. await workspaceCard.getByTestId("virtual-project-create-task").click();
  890. const composer = mobile.getByTestId(TID_V4_COMPOSER_INPUT).first();
  891. await composer.waitFor({ timeout: 60_000 });
  892. const pane = mobile.getByTestId(testId(TID_V4_SESSION_PANE, "workspace-main"));
  893. expect(await pane.getAttribute("data-session-id")).toBe("draft");
  894. const unsentDraft = `${marker}_UNSENT`;
  895. await composer.click();
  896. await mobile.keyboard.type(unsentDraft);
  897. // 项目草稿已按 client/host/project 隔离;旧 workspace 草稿 key 不再承载 __draft__。
  898. // 核对本项目的持久正文,不能用旧 key 超时误判为产品丢草稿。
  899. await mobile.waitForFunction(
  900. ({ text, projectId, hostId }: { text: string; projectId: string; hostId: string }) => {
  901. const prefix = "zcode-v4-composer-project-drafts:v1:";
  902. return Object.keys(localStorage).some((key) => {
  903. if (!key.startsWith(prefix)) return false;
  904. const [client, host, project] = JSON.parse(key.slice(prefix.length));
  905. if (!String(client).startsWith("mobile:") || host !== hostId || project !== projectId)
  906. return false;
  907. const stored = JSON.parse(localStorage.getItem(key) ?? "{}");
  908. return stored.scopes?.__draft__?.text === text;
  909. });
  910. },
  911. { text: unsentDraft, projectId, hostId: `remote:server:${sourceId}` },
  912. );
  913. expect(await mobileUserRows(mobile)).toHaveLength(0);
  914. // 沿用 RDUX-08-07:手机保持当前聊天 owner,不用首页/浏览器历史制造额外冷态。
  915. phase = "disconnect-source";
  916. await disconnectRemoteSource(sourceId, marker);
  917. await browser.waitUntil(
  918. async () => !(await readRemoteTabSnapshot(identity)).remoteSessionId,
  919. { timeout: 30_000 },
  920. );
  921. phase = "retained-disconnected-draft";
  922. const banner = mobile.getByTestId("remote-conversation-banner");
  923. await banner.waitFor({ timeout: 60_000 });
  924. expect(await banner.getAttribute("data-connection-state")).toBe("offline");
  925. expect(await composer.textContent()).toContain(unsentDraft);
  926. expect(await mobile.getByTestId(TID_V4_COMPOSER_SEND).first().isDisabled()).toBe(true);
  927. await mobile.getByTestId("remote-send-unavailable").waitFor();
  928. expect(await composer.evaluate((element) => Boolean(element.closest("[inert]")))).toBe(true);
  929. for (const [theme, label] of [
  930. ["light", "浅色主题"],
  931. ["dark", "深色主题"],
  932. ] as const) {
  933. await mobile.getByRole("button", { name: "选择主题", exact: true }).click();
  934. await mobile.getByRole("menuitemradio", { name: label, exact: true }).click();
  935. await mobile.waitForFunction(
  936. (value: string) => document.documentElement.classList.contains(`theme-zai-${value}`),
  937. theme,
  938. );
  939. await mobile.getByRole("menu").waitFor({ state: "hidden" });
  940. phase = `disconnected-${theme}`;
  941. expect(await composer.textContent()).toContain(unsentDraft);
  942. expect(await mobile.getByTestId(TID_V4_COMPOSER_SEND).first().isDisabled()).toBe(true);
  943. await mobile.screenshot({
  944. path: resolve(artifactDir, `mobile-retained-draft-${theme}.png`),
  945. fullPage: true,
  946. animations: "disabled",
  947. });
  948. }
  949. phase = "reconnect-original-project";
  950. await banner.getByRole("button", { name: "重新连接", exact: true }).click();
  951. await banner.waitFor({ state: "hidden", timeout: 120_000 });
  952. await composer.waitFor({ timeout: 60_000 });
  953. expect(await composer.textContent()).toContain(unsentDraft);
  954. expect(await pane.getAttribute("data-session-id")).toBe("draft");
  955. const restored = await readRemoteTabSnapshot(identity);
  956. expect(restored.workspaceIdentity).toBe(identity);
  957. expect(restored.workspacePath).toBe(workspacePath);
  958. expect(restored.remoteSessionId).toBeTruthy();
  959. expect(await mobileUserRows(mobile)).toHaveLength(0);
  960. expect(await getV4Messages("user")).toHaveLength(0);
  961. expect(await getV4QueueItems()).toHaveLength(0);
  962. const capturedModelRequests = process.env.E2E_PROVIDER_CAPTURE_PATH?.trim()
  963. ? await countUpstreamRequests({}, { afterIndex: requestBaseline - 1 })
  964. : null;
  965. if (capturedModelRequests !== null) expect(capturedModelRequests).toBe(0);
  966. facts.draftOnly = {
  967. identity,
  968. workspacePath,
  969. viewport: MOBILE_VIEWPORT,
  970. themes: ["light", "dark"],
  971. draftRetained: true,
  972. noSubmission: true,
  973. capturedModelRequests,
  974. scope: "retained draft owner; not cold placeholder, page bootstrap, or streaming gap",
  975. };
  976. } catch (error) {
  977. facts.draftOnlyFailure = {
  978. phase,
  979. desktop: await readRemoteTabSnapshot(identity).catch(() => null),
  980. mobile: await mobile
  981. .evaluate(
  982. (ids) => {
  983. const composer = document.querySelector(`[data-testid="${ids.input}"]`);
  984. const send = document.querySelector<HTMLButtonElement>(`[data-testid="${ids.send}"]`);
  985. const banner = document.querySelector('[data-testid="remote-conversation-banner"]');
  986. return {
  987. chatVisible: Boolean(document.querySelector('[data-mobile-page="chat"]')),
  988. bannerState: banner?.getAttribute("data-connection-state") ?? null,
  989. composerPresent: Boolean(composer),
  990. composerInert: Boolean(composer?.closest("[inert]")),
  991. sendDisabled: send?.disabled ?? null,
  992. unavailableHint: Boolean(
  993. document.querySelector('[data-testid="remote-send-unavailable"]'),
  994. ),
  995. coldPlaceholder: Boolean(
  996. document.querySelector('[data-testid="remote-conversation-unavailable"]'),
  997. ),
  998. };
  999. },
  1000. { input: TID_V4_COMPOSER_INPUT, send: TID_V4_COMPOSER_SEND },
  1001. )
  1002. .catch(() => null),
  1003. };
  1004. await mobile
  1005. .screenshot({
  1006. path: resolve(artifactDir, "mobile-retained-draft-failure.png"),
  1007. fullPage: true,
  1008. })
  1009. .catch(() => undefined);
  1010. throw error;
  1011. } finally {
  1012. await context.close();
  1013. }
  1014. });
  1015. });