conversation-session-r3-mobile-permission.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. import { openMobilePairingPage, seedMobileFixtureLogin } from "#e2e/helpers/mobile-pairing";
  2. import { readRemoteToolExecutionEvents } from "#e2e/helpers/remote-tool-execution-evidence";
  3. import { execFile } from "node:child_process";
  4. import { mkdir, writeFile } from "node:fs/promises";
  5. import {
  6. PERMISSION_INTERACTION_PREFIX,
  7. readPermissionInteractionIdsInBrowser,
  8. waitForPermissionInteractionId,
  9. } from "#e2e/helpers/permission-interaction-id";
  10. import { resolve } from "node:path";
  11. import { promisify } from "node:util";
  12. import { TID_TASK_ITEM, testId } from "@zcode/shared/test-ids";
  13. import { clearAppData } from "#e2e/helpers/desktop-app";
  14. import {
  15. getUpstreamRequestRecordCount,
  16. waitForUpstreamRequest,
  17. } from "#e2e/helpers/conversation-session-network";
  18. import {
  19. connectSSHWorkspaceAndSendFirstTurn,
  20. listRemoteAgentProcesses,
  21. prepareSSHLifecycle,
  22. type SSHLifecycleProvider,
  23. } from "#e2e/helpers/ssh-remote-lifecycle";
  24. import {
  25. readHostProcesses,
  26. readRemoteTabSnapshot,
  27. runSSHCommand,
  28. } from "#e2e/helpers/ssh-remote-p0";
  29. import {
  30. getV4ConversationState,
  31. hasV4PermissionDialog,
  32. sendV4Prompt,
  33. waitForV4AssistantMessageContaining,
  34. waitForV4ConversationState,
  35. waitForV4PermissionDialogInComposerDock,
  36. } from "#e2e/helpers/v4-conversation";
  37. const CASE_MARKER = "E2E_R3_MOBILE_PERMISSION";
  38. const artifactDir = resolve(
  39. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/r3-mobile-permission",
  40. );
  41. // Linux e2e 服务器上没有 macOS 版 Chrome:用 R3_MOBILE_CHROME 指向该机 playwright 下载的
  42. // chromium(缺省仍回退开发机 macOS 路径),否则本 case 在服务器上直接起不了手机浏览器。
  43. const CHROME =
  44. process.env.R3_MOBILE_CHROME?.trim() ||
  45. "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
  46. const MOBILE_VIEWPORT = { width: 390, height: 844 };
  47. const run = promisify(execFile);
  48. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  49. type PwPage = any;
  50. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  51. type PwContext = any;
  52. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  53. type PwBrowser = any;
  54. async function countRemoteSshSessions(container: string): Promise<number> {
  55. const { stdout } = await run("docker", [
  56. "exec",
  57. container,
  58. "sh",
  59. "-c",
  60. "ps -o user=,args= -C sshd | grep -c '^dev ' || true",
  61. ]);
  62. return Number.parseInt(stdout.trim() || "0", 10);
  63. }
  64. /** 打开 Desktop 的“移动端远程控制”对话框并拦截剪贴板取得配对链接(含配对材料,只留内存、不落记录)。 */
  65. async function obtainPairUrl(): Promise<string> {
  66. await browser.execute(() => {
  67. const clipboard = navigator.clipboard;
  68. const original = clipboard.writeText.bind(clipboard);
  69. (
  70. window as Window & { __r3RestoreClipboard?: () => void; __r3PairUrl?: string }
  71. ).__r3RestoreClipboard = () => {
  72. clipboard.writeText = original;
  73. };
  74. clipboard.writeText = async (text: string) => {
  75. (window as Window & { __r3PairUrl?: string }).__r3PairUrl = text;
  76. };
  77. });
  78. const trigger = $('button[aria-label="移动端远程控制"]');
  79. await trigger.waitForClickable({ timeout: 30_000 });
  80. await trigger.click();
  81. await $('[data-testid="web-remote-control-dialog-scroll"]').waitForDisplayed({ timeout: 30_000 });
  82. await browser.waitUntil(
  83. () =>
  84. browser.execute(() => {
  85. const button = Array.from(
  86. document.querySelectorAll<HTMLButtonElement>(
  87. '[data-testid="web-remote-control-dialog-scroll"] button',
  88. ),
  89. ).find((b) => b.innerText.trim() === "复制链接" && !b.disabled);
  90. button?.click();
  91. return Boolean(button);
  92. }),
  93. {
  94. timeout: 60_000,
  95. interval: 500,
  96. timeoutMsg: `${CASE_MARKER}: 复制链接按钮不可用(relay 未就绪?)`,
  97. },
  98. );
  99. let url = "";
  100. await browser.waitUntil(
  101. async () => {
  102. url = (await browser.execute(
  103. () => (window as Window & { __r3PairUrl?: string }).__r3PairUrl ?? "",
  104. )) as string;
  105. return url.startsWith("http");
  106. },
  107. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 没有取得配对链接` },
  108. );
  109. await browser.execute(() => {
  110. const w = window as Window & { __r3RestoreClipboard?: () => void; __r3PairUrl?: string };
  111. w.__r3RestoreClipboard?.();
  112. delete w.__r3RestoreClipboard;
  113. delete w.__r3PairUrl;
  114. });
  115. return url;
  116. }
  117. async function readDesktopMobileStatus(): Promise<string> {
  118. return browser.execute(
  119. () =>
  120. document
  121. .querySelector<HTMLElement>('[data-testid="web-remote-control-connection-card"]')
  122. ?.innerText.replace(/\s+/gu, " ")
  123. .slice(0, 200) ?? "",
  124. );
  125. }
  126. async function closeRemoteControlDialog(): Promise<void> {
  127. await browser.keys(["Escape"]);
  128. await browser
  129. .waitUntil(
  130. () =>
  131. browser.execute(
  132. () => !document.querySelector('[data-testid="web-remote-control-dialog-scroll"]'),
  133. ),
  134. { timeout: 10_000, timeoutMsg: `${CASE_MARKER}: 远程控制对话框没有关闭` },
  135. )
  136. .catch(() => undefined);
  137. }
  138. async function mobileText(page: PwPage): Promise<string> {
  139. return (await page.evaluate(() => document.body?.innerText ?? "")) as string;
  140. }
  141. const REMOTE_PERMISSION_DIR = "/home/dev/r3-workspace-a/.zcode-e2e/r3-mobile-permission";
  142. const REMOTE_PERMISSION_FILE = `${REMOTE_PERMISSION_DIR}/permission-output.txt`;
  143. const PERMISSION_EXECUTION = { toolCallId: "toolu_r3_mobp_permission", toolName: "Write" };
  144. async function readMobilePermission(
  145. page: PwPage,
  146. ): Promise<{ visible: boolean; text: string; optionCount: number; interactionIds: string[] }> {
  147. const state = (await page.evaluate(() => {
  148. const listbox = Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).find(
  149. (node) => node.getClientRects().length && node.querySelector('button[role="option"]'),
  150. );
  151. const dock = listbox?.closest<HTMLElement>("[data-testid], form, section") ?? listbox;
  152. return {
  153. visible: Boolean(listbox),
  154. text: (dock?.innerText ?? "").replace(/\s+/gu, " ").slice(0, 300),
  155. optionCount: listbox?.querySelectorAll('button[role="option"]').length ?? 0,
  156. };
  157. })) as { visible: boolean; text: string; optionCount: number };
  158. const interactionIds = await page.evaluate(
  159. readPermissionInteractionIdsInBrowser,
  160. PERMISSION_INTERACTION_PREFIX,
  161. );
  162. return { ...state, interactionIds };
  163. }
  164. describe(`${CASE_MARKER}: 权限阻塞在手机端呈现、重建手机 bridge 后同一阻塞恢复、手机回答后各端清除`, () => {
  165. let provider: SSHLifecycleProvider | null = null;
  166. let mobileBrowser: PwBrowser = null;
  167. const facts: Record<string, unknown> = {};
  168. after(async () => {
  169. await mkdir(artifactDir, { recursive: true });
  170. await writeFile(resolve(artifactDir, "mobile-permission.json"), JSON.stringify(facts, null, 2));
  171. await mobileBrowser?.close().catch(() => undefined);
  172. mobileBrowser = null;
  173. await provider?.tunnel.close().catch(() => undefined);
  174. provider = null;
  175. await browser.electron.restoreAllMocks();
  176. await clearAppData();
  177. });
  178. it("R3A-MOB-04 远端 Write 权限 pending → 手机显示同一阻塞;关闭手机上下文重建 bridge 后阻塞仍在且同一 ID;手机允许后桌面与手机都清除、远端工具真实执行且只执行一次", async function () {
  179. this.timeout(40 * 60_000);
  180. const container = process.env.ZCODE_E2E_SSH_CONTAINER?.trim();
  181. if (!container) throw new Error(`${CASE_MARKER}: 缺少 ZCODE_E2E_SSH_CONTAINER`);
  182. const prepared = await prepareSSHLifecycle(CASE_MARKER, {
  183. apiType: "anthropic-messages",
  184. tunnelUsername: "tunnel",
  185. });
  186. provider = prepared.provider;
  187. const [workspaceA] = prepared.config.workspacePaths;
  188. await runSSHCommand(prepared.config, `rm -rf "${REMOTE_PERMISSION_DIR}"`);
  189. const taskA = await connectSSHWorkspaceAndSendFirstTurn({
  190. caseMarker: CASE_MARKER,
  191. config: prepared.config,
  192. label: "A",
  193. provider,
  194. workspacePath: workspaceA,
  195. });
  196. const baseline = {
  197. hosts: (await readHostProcesses()).length,
  198. ssh: await countRemoteSshSessions(container),
  199. agents: (await listRemoteAgentProcesses(prepared.config)).length,
  200. };
  201. facts.baseline = baseline;
  202. const pairUrl = await obtainPairUrl();
  203. const { chromium } = (await import("playwright-core")) as {
  204. chromium: { launch(o: object): Promise<PwBrowser> };
  205. };
  206. mobileBrowser = await chromium.launch({ headless: true, executablePath: CHROME });
  207. let pairingAttempt = 0;
  208. const newMobileContext = async (): Promise<{ context: PwContext; page: PwPage }> => {
  209. const context = await mobileBrowser.newContext({
  210. viewport: MOBILE_VIEWPORT,
  211. isMobile: true,
  212. hasTouch: true,
  213. locale: "zh-CN",
  214. });
  215. await seedMobileFixtureLogin(context);
  216. const page = await context.newPage();
  217. await openMobilePairingPage(page, pairUrl, {
  218. artifactDir,
  219. caseMarker: CASE_MARKER,
  220. phase: `pairing-${++pairingAttempt}`,
  221. readySelector: `[data-testid="${testId(TID_TASK_ITEM, taskA.taskId)}"]`,
  222. });
  223. return { context, page };
  224. };
  225. let { context: mobileContext, page: mobile } = await newMobileContext();
  226. await browser.waitUntil(async () => (await readDesktopMobileStatus()).includes("手机已连接"), {
  227. timeout: 60_000,
  228. timeoutMsg: `${CASE_MARKER}: Desktop 未显示手机已连接`,
  229. });
  230. await closeRemoteControlDialog();
  231. await mobile
  232. .locator(`[data-testid="${testId(TID_TASK_ITEM, taskA.taskId)}"]`)
  233. .first()
  234. .click();
  235. await mobile.getByText(taskA.firstReply, { exact: false }).first().waitFor({ timeout: 60_000 });
  236. // 桌面触发远端 Write 权限(build 模式)→ 阻塞。
  237. const permissionStart = await getUpstreamRequestRecordCount();
  238. await sendV4Prompt(`${CASE_MARKER}_PERMISSION 写文件`);
  239. await waitForUpstreamRequest(
  240. { lastUserMessageIncludes: [`${CASE_MARKER}_PERMISSION`] },
  241. `${CASE_MARKER}: 权限回合没有到达回放`,
  242. 60_000,
  243. { afterIndex: permissionStart - 1 },
  244. );
  245. const dock = await waitForV4PermissionDialogInComposerDock(90_000);
  246. facts.desktopPermission = dock;
  247. expect(dock.inDock).toBe(true);
  248. const pendingId = await waitForPermissionInteractionId(CASE_MARKER);
  249. facts.permissionInteractionId = pendingId;
  250. let mobilePermission = await readMobilePermission(mobile);
  251. await browser.waitUntil(
  252. async () => {
  253. mobilePermission = await readMobilePermission(mobile);
  254. return mobilePermission.visible && mobilePermission.interactionIds.length === 1;
  255. },
  256. { timeout: 60_000, interval: 1000, timeoutMsg: `${CASE_MARKER}: 手机端没有显示权限阻塞` },
  257. );
  258. facts.mobilePermissionFirst = mobilePermission;
  259. expect(mobilePermission.interactionIds).toEqual([pendingId]);
  260. const remoteBeforeApprove = await runSSHCommand(
  261. prepared.config,
  262. `test -f "${REMOTE_PERMISSION_FILE}" && echo EXISTS || echo ABSENT`,
  263. );
  264. expect(remoteBeforeApprove.stdout.trim()).toBe("ABSENT");
  265. // 手机 attachment 失效:关闭上下文(相当于手机页面被杀)→ 桌面阻塞保持;重建 bridge → 同一阻塞。
  266. await mobileContext.close();
  267. await browser.pause(5_000);
  268. facts.desktopStillBlockedAfterMobileGone = await hasV4PermissionDialog();
  269. expect(facts.desktopStillBlockedAfterMobileGone).toBe(true);
  270. ({ context: mobileContext, page: mobile } = await newMobileContext());
  271. await mobile
  272. .locator(`[data-testid="${testId(TID_TASK_ITEM, taskA.taskId)}"]`)
  273. .first()
  274. .click();
  275. await browser.waitUntil(
  276. async () => {
  277. mobilePermission = await readMobilePermission(mobile);
  278. return mobilePermission.visible && mobilePermission.interactionIds.length === 1;
  279. },
  280. {
  281. timeout: 60_000,
  282. interval: 1000,
  283. timeoutMsg: `${CASE_MARKER}: 重建 bridge 后手机端没有恢复权限阻塞`,
  284. },
  285. );
  286. facts.mobilePermissionAfterRepair = mobilePermission;
  287. expect(mobilePermission.interactionIds).toEqual([pendingId]);
  288. expect(await waitForPermissionInteractionId(CASE_MARKER)).toBe(pendingId);
  289. // 同一阻塞:重建后仍是同一文件的权限请求、同样的选项数(文本含“工作中 N 秒”计时与截断,不做全文相等比较)。
  290. const first = facts.mobilePermissionFirst as { text: string; optionCount: number };
  291. expect(mobilePermission.optionCount).toBe(first.optionCount);
  292. expect(mobilePermission.text).toContain("permission-output.txt");
  293. expect(mobilePermission.text).toContain("需要权限");
  294. expect(first.text).toContain("需要权限");
  295. const executionQuery = { sessionId: taskA.taskId, toolName: PERMISSION_EXECUTION.toolName };
  296. expect(await readRemoteToolExecutionEvents(prepared.config, executionQuery)).toEqual([]);
  297. // 手机允许(第一个选项)→ 桌面阻塞清除、远端文件写入一次、回合收口。
  298. await mobile.locator('[role="listbox"] button[role="option"]').first().click();
  299. await browser.waitUntil(async () => !(await hasV4PermissionDialog()), {
  300. timeout: 60_000,
  301. timeoutMsg: `${CASE_MARKER}: 手机允许后桌面阻塞没有清除`,
  302. });
  303. await waitForV4AssistantMessageContaining("R3_MOBILE_PERMISSION_DONE", 120_000);
  304. await waitForV4ConversationState(
  305. (s) => s.taskId === taskA.taskId && s.state === "idle",
  306. `${CASE_MARKER}: 权限回合没有收口`,
  307. 120_000,
  308. );
  309. await browser.pause(3_000);
  310. const mobileAfter = await readMobilePermission(mobile);
  311. const remoteFile = await runSSHCommand(
  312. prepared.config,
  313. `cat "${REMOTE_PERMISSION_FILE}" 2>/dev/null | wc -l; cat "${REMOTE_PERMISSION_FILE}" 2>/dev/null`,
  314. );
  315. facts.afterApprove = {
  316. mobilePermissionVisible: mobileAfter.visible,
  317. remoteFile: remoteFile.stdout.trim().split("\n"),
  318. desktopState: (await getV4ConversationState()).state,
  319. };
  320. expect(mobileAfter.visible).toBe(false);
  321. expect(remoteFile.stdout).toContain("R3_MOBILE_PERMISSION_RESULT");
  322. expect(remoteFile.stdout.trim().split("\n")[0]).toBe("1");
  323. // Write 会覆盖同一行,文件行数不能证明只执行一次;用真实 executor 的开始/完成事件对账。
  324. let executions = await readRemoteToolExecutionEvents(prepared.config, executionQuery);
  325. await browser.waitUntil(
  326. async () => {
  327. executions = await readRemoteToolExecutionEvents(prepared.config, executionQuery);
  328. facts.remoteToolExecutions = executions;
  329. return executions.some((event) => event.event === "tool.call.completed");
  330. },
  331. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 远端 Write 缺少完成事件` },
  332. );
  333. expect(executions.filter((event) => event.event === "tool.call.started")).toHaveLength(1);
  334. expect(executions.filter((event) => event.event === "tool.call.completed")).toHaveLength(1);
  335. expect(executions.every((event) => event.toolCallId === PERMISSION_EXECUTION.toolCallId)).toBe(
  336. true,
  337. );
  338. const after = {
  339. hosts: (await readHostProcesses()).length,
  340. ssh: await countRemoteSshSessions(container),
  341. agents: (await listRemoteAgentProcesses(prepared.config)).length,
  342. };
  343. facts.after = after;
  344. expect(after.hosts).toBe(baseline.hosts);
  345. expect(after.ssh).toBeLessThanOrEqual(baseline.ssh);
  346. expect(after.agents).toBeLessThanOrEqual(baseline.agents);
  347. await mobileContext.close();
  348. });
  349. });