conversation-session-shared-cli.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. import { basename, join } from "node:path";
  2. import { readFile } from "node:fs/promises";
  3. import { chromium, type Browser, type Page } from "playwright-core";
  4. import {
  5. testId,
  6. TID_TASK_ITEM,
  7. TID_WORKSPACE_MORE_BUTTON,
  8. TID_CONFIRM_DIALOG_CONFIRM,
  9. } from "@zcode/shared/test-ids";
  10. import { clearAppData, DEFAULT_WORKSPACE } from "#e2e/helpers/desktop-app";
  11. import { openMobilePairingPage, seedMobileFixtureLogin } from "#e2e/helpers/mobile-pairing";
  12. import { obtainUnreadPairingUrl } from "#e2e/helpers/web-remote-unread";
  13. import { waitForUpstreamNetworkRequestStarted } from "#e2e/helpers/upstream-capture";
  14. import {
  15. getV4ConversationState,
  16. prepareV4ConversationE2E,
  17. sendV4Prompt,
  18. startNewV4Draft,
  19. waitForV4TimelineContaining,
  20. waitForV4ConversationState,
  21. getV4Messages,
  22. clickV4Stop,
  23. waitForV4PermissionDialog,
  24. approveV4Permission,
  25. hasV4PermissionDialog,
  26. } from "#e2e/helpers/v4-conversation";
  27. import {
  28. isMainRendererUrl,
  29. isResourceManagerUrl,
  30. listAgentProcessIdentities,
  31. openResourceManagerFromHelpMenu,
  32. switchToElectronRendererTarget,
  33. waitForResourceManagerReady,
  34. } from "#e2e/helpers/resource-manager";
  35. async function readAgents() {
  36. await openResourceManagerFromHelpMenu();
  37. await switchToElectronRendererTarget(isResourceManagerUrl);
  38. await waitForResourceManagerReady();
  39. const agents = await listAgentProcessIdentities();
  40. await switchToElectronRendererTarget(isMainRendererUrl);
  41. return agents;
  42. }
  43. async function currentDirectory() {
  44. return browser.execute(
  45. () =>
  46. (
  47. window as Window & {
  48. __zcodeTabStoreE2E?: { getState(): { activeWorkspacePath?: string | null } };
  49. }
  50. ).__zcodeTabStoreE2E?.getState().activeWorkspacePath,
  51. );
  52. }
  53. async function sendAndFinish(marker: string) {
  54. const before = (await getV4Messages("assistant")).at(-1)?.id;
  55. await sendV4Prompt(`${marker} reply briefly`);
  56. // 虚拟列表收到新回复后可能移除旧行,可见数量不增长;用末条回复身份确认本轮结果。
  57. await browser.waitUntil(
  58. async () => {
  59. const latest = (await getV4Messages("assistant")).at(-1);
  60. return Boolean(latest && latest.id !== before && latest.text.includes("shared-cli-ok"));
  61. },
  62. { timeout: 60_000, timeoutMsg: `${marker} 没有独立回复` },
  63. );
  64. await waitForV4ConversationState((s) => s.state === "idle", `${marker} 未完成`);
  65. }
  66. describe("无项目工作区共享 CLI", () => {
  67. let webBrowser: Browser | undefined;
  68. let mobile: Page | undefined;
  69. after(async () => {
  70. if (mobile && process.env.ZCODE_E2E_ARTIFACT_DIR)
  71. await mobile
  72. .screenshot({ path: join(process.env.ZCODE_E2E_ARTIFACT_DIR, "STCLI-mobile.png") })
  73. .catch(() => undefined);
  74. await webBrowser?.close();
  75. await browser.electron.restoreAllMocks();
  76. await clearAppData();
  77. });
  78. it("STCLI01–07 共享、草稿释放、单任务重启、移动与进程退出恢复保持身份隔离", async function () {
  79. this.timeout(360_000);
  80. await prepareV4ConversationE2E();
  81. await startNewV4Draft();
  82. await sendV4Prompt("E2E_SHARED_CLI_A reply briefly");
  83. await waitForV4TimelineContaining("shared-cli-ok", 60_000);
  84. await waitForV4ConversationState((s) => s.state === "idle", "A 未完成");
  85. const taskA = (await getV4ConversationState()).taskId;
  86. const cwdA = await currentDirectory();
  87. const agentsA = await readAgents();
  88. const shared = agentsA.find((agent) => agent.name.endsWith("-zcode"));
  89. expect(shared).toBeDefined();
  90. expect(agentsA.some((agent) => agent.name.endsWith("-zcodeproject"))).toBe(true);
  91. await startNewV4Draft();
  92. await sendV4Prompt("E2E_SHARED_CLI_B reply briefly");
  93. await waitForV4TimelineContaining("shared-cli-ok", 60_000);
  94. await waitForV4ConversationState((s) => s.state === "idle", "B 未完成");
  95. const taskB = (await getV4ConversationState()).taskId;
  96. const cwdB = await currentDirectory();
  97. expect(cwdB).toBeTruthy();
  98. expect(cwdB).not.toBe(cwdA);
  99. expect(taskA).toBeTruthy();
  100. expect(taskB).toBeTruthy();
  101. expect(taskB).not.toBe(taskA);
  102. expect(await readAgents()).toEqual(agentsA);
  103. // 同一个工具调用 ID 在两个 session 中分别审批,文件必须落在各自目录。
  104. await $(`[data-testid="${testId(TID_TASK_ITEM, taskA!)}"]`).click();
  105. await sendV4Prompt("E2E_SHARED_CLI_TOOL_A");
  106. await waitForV4PermissionDialog();
  107. await $(`[data-testid="${testId(TID_TASK_ITEM, taskB!)}"]`).click();
  108. expect(await hasV4PermissionDialog()).toBe(false);
  109. await sendV4Prompt("E2E_SHARED_CLI_TOOL_B");
  110. await waitForV4PermissionDialog();
  111. await approveV4Permission();
  112. await waitForV4ConversationState((s) => s.state === "idle", "B 工具未完成");
  113. expect(await readFile(join(cwdB!, "shared-cli-proof.txt"), "utf8")).toBe(cwdB);
  114. await $(`[data-testid="${testId(TID_TASK_ITEM, taskA!)}"]`).click();
  115. await waitForV4PermissionDialog();
  116. await approveV4Permission();
  117. await waitForV4ConversationState((s) => s.state === "idle", "A 工具未完成");
  118. expect(await readFile(join(cwdA!, "shared-cli-proof.txt"), "utf8")).toBe(cwdA);
  119. await startNewV4Draft();
  120. await $(`[data-testid="${testId(TID_TASK_ITEM, taskB!)}"]`).click();
  121. await sendAndFinish("E2E_SHARED_CLI_B_CONTINUE");
  122. expect((await getV4ConversationState()).taskId).toBe(taskB);
  123. expect(await readAgents()).toEqual(agentsA);
  124. // 用上游请求已开始作屏障;A 流式执行期间,B 仍可完成自己的发送。
  125. await $(`[data-testid="${testId(TID_TASK_ITEM, taskA!)}"]`).click();
  126. await sendV4Prompt("E2E_SHARED_CLI_RUNNING");
  127. await waitForUpstreamNetworkRequestStarted("E2E_SHARED_CLI_RUNNING");
  128. await $(`[data-testid="${testId(TID_TASK_ITEM, taskB!)}"]`).click();
  129. await sendAndFinish("E2E_SHARED_CLI_B_PARALLEL");
  130. await $(`[data-testid="${testId(TID_TASK_ITEM, taskA!)}"]`).click();
  131. await waitForV4ConversationState((s) => s.state === "streaming", "B 完成前 A 已意外结束");
  132. await clickV4Stop();
  133. await waitForV4ConversationState((s) => s.state === "idle", "停止 A 未完成");
  134. await $(`[data-testid="${testId(TID_TASK_ITEM, taskA!)}"]`).click();
  135. const paneA = `[data-session-id="${taskA}"]`;
  136. const generation = Number(await $(paneA).getAttribute("data-session-generation"));
  137. await $(`[data-testid="${TID_WORKSPACE_MORE_BUTTON}"]`).click();
  138. await $('[data-testid="task-restart"]').click();
  139. await browser.waitUntil(
  140. async () =>
  141. (await $(paneA).getAttribute("data-session-lifecycle")) === "ready" &&
  142. Number(await $(paneA).getAttribute("data-session-generation")) > generation,
  143. { timeout: 60_000 },
  144. );
  145. expect(await readAgents()).toEqual(agentsA);
  146. await sendAndFinish("E2E_SHARED_CLI_A_RESTARTED");
  147. const pairingUrl = await obtainUnreadPairingUrl(
  148. new URL(process.env.ZCODE_WEB_REMOTE_CONTROL_URL!).origin,
  149. );
  150. webBrowser = await chromium.launch({
  151. executablePath: process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE,
  152. headless: true,
  153. args: ["--no-sandbox"],
  154. });
  155. const context = await webBrowser.newContext({
  156. viewport: { width: 390, height: 844 },
  157. isMobile: true,
  158. hasTouch: true,
  159. locale: "zh-CN",
  160. });
  161. await seedMobileFixtureLogin(context);
  162. mobile = await context.newPage();
  163. await openMobilePairingPage(mobile, pairingUrl, {
  164. artifactDir: process.env.ZCODE_E2E_ARTIFACT_DIR!,
  165. caseMarker: "STCLI07",
  166. phase: "shared",
  167. readySelector: `[data-testid="${testId(TID_TASK_ITEM, taskB!)}"]`,
  168. });
  169. await mobile.getByTestId(testId(TID_TASK_ITEM, taskB!)).first().tap();
  170. await mobile.locator(`[data-session-id="${taskB}"]`).waitFor();
  171. await mobile.getByText("E2E_SHARED_CLI_B_CONTINUE reply briefly", { exact: true }).waitFor();
  172. expect(
  173. await mobile.getByText("E2E_SHARED_CLI_A_RESTARTED reply briefly", { exact: true }).count(),
  174. ).toBe(0);
  175. await mobile.reload();
  176. await mobile.getByText("E2E_SHARED_CLI_B_CONTINUE reply briefly", { exact: true }).waitFor();
  177. expect(await readAgents()).toEqual(agentsA);
  178. // 移动只更改项目归属,既有运行实例和 cwd 保持稳定。
  179. const project = $(`[data-project-name="${basename(DEFAULT_WORKSPACE)}"]`);
  180. await $(`[data-testid="${testId(TID_TASK_ITEM, taskA!)}"]`).dragAndDrop(
  181. project.$('[data-testid="virtual-project-toggle"]'),
  182. { duration: 700 },
  183. );
  184. const confirm = $(`[data-testid="${TID_CONFIRM_DIALOG_CONFIRM}"]`);
  185. await confirm.waitForDisplayed();
  186. await confirm.click();
  187. await project.$(`[data-testid="${testId(TID_TASK_ITEM, taskA!)}"]`).waitForDisplayed();
  188. expect(await currentDirectory()).toBe(cwdA);
  189. await sendAndFinish("E2E_SHARED_CLI_A_MOVED");
  190. expect(await readAgents()).toEqual(agentsA);
  191. const aUsers = (await getV4Messages("user")).length;
  192. // 只终止本用例观察到的共享 PID;真实退出用于验证全部订阅失效与下一次重新分配。
  193. process.kill(shared!.pid, "SIGKILL");
  194. await $(`[data-testid="${testId(TID_TASK_ITEM, taskB!)}"]`).click();
  195. await waitForV4TimelineContaining("E2E_SHARED_CLI_B_CONTINUE", 60_000);
  196. await sendAndFinish("E2E_SHARED_CLI_B_RECOVERED");
  197. const afterB = await readAgents();
  198. expect(afterB.some((agent) => agent.pid === shared!.pid)).toBe(false);
  199. const nextShared = afterB.find((agent) => agent.name.endsWith("-zcode"));
  200. expect(nextShared).toBeDefined();
  201. await $(`[data-testid="${testId(TID_TASK_ITEM, taskA!)}"]`).click();
  202. await waitForV4TimelineContaining("E2E_SHARED_CLI_A_MOVED", 60_000);
  203. expect((await getV4Messages("user")).length).toBe(aUsers);
  204. await sendAndFinish("E2E_SHARED_CLI_A_RECOVERED");
  205. expect(await currentDirectory()).toBe(cwdA);
  206. const afterA = await readAgents();
  207. expect(afterA.some((agent) => agent.pid === nextShared!.pid)).toBe(true);
  208. // 资源管理器显示名截断长目录;真实 cwd 已通过页面身份与 Host 日志独立核验。
  209. expect(
  210. afterA.some((agent) => agent.pid !== nextShared!.pid && agent.name.includes("-draft-")),
  211. ).toBe(true);
  212. expect(afterA.length).toBeGreaterThan(agentsA.length);
  213. // 清理与换代只恢复订阅,手机不能重放原输入,也不能订阅到移入项目的 A。
  214. await mobile.reload();
  215. await mobile.getByText("E2E_SHARED_CLI_B_RECOVERED reply briefly", { exact: true }).waitFor();
  216. expect(
  217. await mobile.getByText("E2E_SHARED_CLI_B_RECOVERED reply briefly", { exact: true }).count(),
  218. ).toBe(1);
  219. expect(
  220. await mobile.getByText("E2E_SHARED_CLI_A_RECOVERED reply briefly", { exact: true }).count(),
  221. ).toBe(0);
  222. });
  223. });