agent-runtime-exit-notice.test.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. // 后台 runtime(app-server)意外退出后,会话底部给出原因横幅(docs/ui/agent-runtime-exit-notice.md)。
  2. // 复现方式与用户现场一致:直接 SIGKILL app-server 子进程。只在 Linux 上按 /proc 定位本次 E2E 的进程。
  3. // 运行:ZCODE_E2E_MANUAL_REVIEW=1 pnpm --filter @zcode/desktop test:e2e -- \
  4. // --spec './test/e2e/workspace/runtime/manual-review/pending/agent-runtime-exit-notice.test.ts'
  5. // ARE-02 借用 v4 后台工作用例的回放夹具产出一个后台 Bash,并用 prlimit 让 Host 暂时无法创建子进程;需要另设
  6. // E2E_PROVIDER_REPLAY_FIXTURE_PATH=packages/desktop/test/e2e/fixtures/upstream/common.json,\
  7. // packages/desktop/test/e2e/fixtures/upstream/conversation-session/conversation-session-v4-background-work.json
  8. // 未设置时 ARE-02 跳过。
  9. import { execFileSync } from "node:child_process";
  10. import { readdir, readFile, readlink } from "node:fs/promises";
  11. import { TID_V4_BACKGROUND_WORK_ITEM, TID_V4_RETRY_SUBSCRIBE } from "@zcode/shared/test-ids";
  12. import { prepareConversationE2E, sendPrompt } from "#e2e/helpers/conversation-session";
  13. import {
  14. approveV4Permission,
  15. getV4BackgroundWorks,
  16. openV4ComposerRunningBackgroundWorks,
  17. prepareV4ConversationE2E,
  18. sendV4Prompt,
  19. waitForV4PermissionDialog,
  20. } from "#e2e/helpers/v4-conversation";
  21. /**
  22. * 本次 E2E 工作区的 app-server 进程:命令行含 app-server(或已改名为 zcode-cli),cwd 在本次隔离
  23. * HOME 的工作区下。
  24. * 不按环境变量 HOME 判断:Host 给 agent 的 HOME 不一定是 E2E HOME。plugin-workspace 泳道排除。
  25. */
  26. async function findE2EAppServerPids(homeDir: string): Promise<number[]> {
  27. const pids: number[] = [];
  28. for (const entry of await readdir("/proc")) {
  29. if (!/^\d+$/.test(entry)) continue;
  30. try {
  31. const cmdline = (await readFile(`/proc/${entry}/cmdline`, "utf8")).split("\0");
  32. // CLI 启动后把进程标题改成 zcode-cli,会覆盖 cmdline;两种形态都要认。
  33. if (!cmdline.includes("app-server") && !cmdline[0]?.startsWith("zcode-cli")) continue;
  34. const cwd = await readlink(`/proc/${entry}/cwd`);
  35. if (cwd.startsWith(`${homeDir}/`) && !cwd.includes("/.zcode/")) pids.push(Number(entry));
  36. } catch {
  37. // 进程在扫描期间退出或不可读:跳过。
  38. }
  39. }
  40. return pids;
  41. }
  42. async function describeAppServers(): Promise<string> {
  43. const rows: string[] = [];
  44. for (const entry of await readdir("/proc")) {
  45. if (!/^\d+$/.test(entry)) continue;
  46. try {
  47. const cmdline = (await readFile(`/proc/${entry}/cmdline`, "utf8")).split("\0");
  48. if (!cmdline.some((arg) => arg.includes("app-server"))) continue;
  49. const home = (await readFile(`/proc/${entry}/environ`, "utf8"))
  50. .split("\0")
  51. .find((line) => line.startsWith("HOME="));
  52. rows.push(`${entry} ${cmdline.slice(0, 4).join(" ")} ${home ?? ""}`);
  53. } catch {
  54. // 跳过
  55. }
  56. }
  57. return rows.join("; ") || "无";
  58. }
  59. /**
  60. * 让 Host 进程暂时无法创建子进程(RLIMIT_NPROC 软限制压到 1,fork 返回 EAGAIN),模拟系统资源耗尽时
  61. * 重新拉起 runtime 失败:spawn 不成功就没有 available,窗格的三次自动重连用完后进入订阅错误态。
  62. * 只改这一个进程的软限制;返回恢复函数。
  63. */
  64. function blockHostSpawns(hostPid: number): () => void {
  65. const pid = String(hostPid);
  66. const [soft] = execFileSync("prlimit", [
  67. "--pid",
  68. pid,
  69. "--nproc",
  70. "--output",
  71. "SOFT",
  72. "--noheadings",
  73. ])
  74. .toString()
  75. .trim()
  76. .split(/\s+/);
  77. execFileSync("prlimit", ["--pid", pid, "--nproc=1:"]);
  78. return () => execFileSync("prlimit", ["--pid", pid, `--nproc=${soft}:`]);
  79. }
  80. async function readParentPid(pid: number): Promise<number> {
  81. const status = await readFile(`/proc/${pid}/status`, "utf8");
  82. const ppid = Number(status.match(/^PPid:\s+(\d+)/m)?.[1]);
  83. if (!Number.isInteger(ppid) || ppid <= 1) throw new Error(`读不到 app-server ${pid} 的父进程`);
  84. return ppid;
  85. }
  86. function readBackgroundWorkElapsed(workId: string): Promise<string | null> {
  87. return browser.execute(
  88. (selector) =>
  89. document.querySelector<HTMLElement>(`${selector} .tabular-nums`)?.textContent ?? null,
  90. `[data-testid="${TID_V4_BACKGROUND_WORK_ITEM}-${workId}"]`,
  91. );
  92. }
  93. describe("后台 runtime 意外退出提示", () => {
  94. before(function () {
  95. if (process.platform !== "linux") this.skip();
  96. });
  97. it("ARE-01 SIGKILL app-server 后会话底部出现通用原因横幅,可关闭", async function () {
  98. this.timeout(180_000);
  99. const homeDir = process.env.ZCODE_E2E_HOME_DIR;
  100. if (!homeDir) throw new Error("缺少 ZCODE_E2E_HOME_DIR");
  101. // 发一条消息让工作区确定拉起 runtime(provider 指向不可达的占位地址,本轮请求失败无妨)。
  102. await prepareConversationE2E();
  103. await sendPrompt("E2E_ARE01 start the runtime");
  104. let pids: number[] = [];
  105. try {
  106. await browser.waitUntil(
  107. async () => {
  108. pids = await findE2EAppServerPids(homeDir);
  109. return pids.length > 0;
  110. },
  111. { timeout: 60_000 },
  112. );
  113. } catch {
  114. throw new Error(
  115. `工作区没有拉起 app-server(HOME=${homeDir}):${await describeAppServers()}`,
  116. );
  117. }
  118. expect(await $('[data-testid="agent-runtime-exit-banner"]').isExisting()).toBe(false);
  119. for (const pid of pids) process.kill(pid, "SIGKILL");
  120. const banner = $('[data-testid="agent-runtime-exit-banner"]');
  121. await banner.waitForDisplayed({ timeout: 30_000, timeoutMsg: "app-server 被杀后没有出现横幅" });
  122. if (process.env.ZCODE_E2E_ARE_SCREENSHOT) {
  123. await browser.saveScreenshot(process.env.ZCODE_E2E_ARE_SCREENSHOT);
  124. }
  125. // Linux 的 SIGKILL 不是可判定的内存不足签名,走通用文案。
  126. expect(await banner.getAttribute("data-exit-cause")).toBe("unknown");
  127. expect(await banner.getText()).toMatch(
  128. /后台运行时异常退出|background runtime exited unexpectedly/,
  129. );
  130. // 面板会自动重连并拉起新进程;横幅在用户关闭前保留。
  131. await browser.waitUntil(async () => (await findE2EAppServerPids(homeDir)).length > 0, {
  132. timeout: 60_000,
  133. timeoutMsg: "自动重连没有拉起新的 app-server",
  134. });
  135. for (const button of await banner.$$("button")) {
  136. if (/关闭|Dismiss/.test(await button.getText())) {
  137. await button.click();
  138. break;
  139. }
  140. }
  141. await banner.waitForDisplayed({ reverse: true, timeout: 10_000 });
  142. });
  143. it("ARE-02 重连失败时原因横幅随错误面板保留;胶囊里后台 Bash 的计时冻结、取消入口隐藏", async function () {
  144. if (!process.env.E2E_PROVIDER_REPLAY_FIXTURE_PATH?.includes("v4-background-work")) this.skip();
  145. this.timeout(240_000);
  146. const homeDir = process.env.ZCODE_E2E_HOME_DIR;
  147. if (!homeDir) throw new Error("缺少 ZCODE_E2E_HOME_DIR");
  148. await prepareV4ConversationE2E({ resetDraftBeforeProvider: true });
  149. await sendV4Prompt("E2E_V4_BGWORK 起一个后台任务");
  150. try {
  151. await waitForV4PermissionDialog(15_000);
  152. await approveV4Permission();
  153. } catch {
  154. // 默认放行 Bash 时没有权限弹窗。
  155. }
  156. // 胶囊的明细行只在展开后渲染:先从 Composer 入口直达展开的运行中明细。
  157. await openV4ComposerRunningBackgroundWorks(60_000);
  158. let workId = "";
  159. await browser.waitUntil(
  160. async () => {
  161. workId =
  162. (await getV4BackgroundWorks()).find((work) => work.status === "running")?.workId ?? "";
  163. return workId !== "";
  164. },
  165. { timeout: 30_000, timeoutMsg: "胶囊里没有出现运行中的后台 Bash" },
  166. );
  167. const cancel = $(`[data-testid="v4-background-work-cancel-${workId}"]`);
  168. await cancel.waitForExist({ timeout: 10_000, timeoutMsg: "在线时应有取消入口" });
  169. const pids = await findE2EAppServerPids(homeDir);
  170. if (pids.length === 0)
  171. throw new Error(`没有找到本次工作区的 app-server:${await describeAppServers()}`);
  172. const hostPid = await readParentPid(pids[0]!);
  173. const restoreSpawns = blockHostSpawns(hostPid);
  174. try {
  175. for (const pid of pids) process.kill(pid, "SIGKILL");
  176. await $(`[data-testid="${TID_V4_RETRY_SUBSCRIBE}"]`).waitForDisplayed({
  177. timeout: 60_000,
  178. timeoutMsg: "runtime 拉不起来时窗格没有进入订阅错误态",
  179. });
  180. // 三项各自独立,收齐后一起断言,任何一项回退都能单独看出来。
  181. const problems: string[] = [];
  182. // 错误面板替换了时间线;原因横幅要跟着留在窗格里。
  183. const bannerShown = await $('[data-testid="agent-runtime-exit-banner"]')
  184. .waitForDisplayed({ timeout: 10_000 })
  185. .then(
  186. () => true,
  187. () => false,
  188. );
  189. if (!bannerShown) problems.push("重连失败后原因横幅消失了");
  190. if (process.env.ZCODE_E2E_ARE_SCREENSHOT) {
  191. await browser.saveScreenshot(
  192. process.env.ZCODE_E2E_ARE_SCREENSHOT.replace(/(\.png)?$/, "-errored.png"),
  193. );
  194. }
  195. // 胶囊仍显示断开前的后台 Bash,但计时停住、取消入口隐藏(目标执行已不存在)。
  196. const before = await readBackgroundWorkElapsed(workId);
  197. if (before === null) throw new Error("错误态下胶囊里找不到该后台 Bash 的计时");
  198. await browser.pause(2_500);
  199. const after = await readBackgroundWorkElapsed(workId);
  200. if (after !== before) problems.push(`离线时计时仍在走:${before} → ${after}`);
  201. if (await cancel.isExisting()) problems.push("离线时仍显示取消按钮");
  202. expect(problems).toEqual([]);
  203. } finally {
  204. restoreSpawns();
  205. }
  206. // 停止干预后用错误面板的「重新连接」恢复,横幅在用户关闭前保留。
  207. await $(`[data-testid="${TID_V4_RETRY_SUBSCRIBE}"]`).click();
  208. await $(`[data-testid="${TID_V4_RETRY_SUBSCRIBE}"]`).waitForExist({
  209. reverse: true,
  210. timeout: 60_000,
  211. timeoutMsg: "手动重新连接后仍停在错误面板",
  212. });
  213. await $('[data-testid="agent-runtime-exit-banner"]').waitForDisplayed({ timeout: 10_000 });
  214. });
  215. });