subagent-host-branches.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. import { subagentUpdateCursor } from "./subagent-snapshot-wait.js";
  2. import { readMessageTextBlocks } from "./subagent-listing-assertions.js";
  3. import { readFile, readdir, writeFile, mkdir, rename, rm } from "node:fs/promises";
  4. import { join } from "node:path";
  5. import { getE2EAppDataPaths } from "./desktop-app.js";
  6. import {
  7. saveRefreshProfile,
  8. setRefreshProfileEnabled,
  9. deleteRefreshProfile,
  10. setRefreshModelOverride,
  11. type RefreshProfile,
  12. } from "./subagent-refresh-settings.js";
  13. import { getV4PaneSnapshot, sendV4PromptAndWaitAccepted, sendV4Prompt } from "./v4-conversation.js";
  14. import { finishSubagentTurn } from "./subagent-refresh-conversation.js";
  15. import {
  16. readSubagentCapture,
  17. assertSubagentProfile,
  18. readChildSessionIds,
  19. boundaryRpcReads,
  20. } from "./subagent-refresh-capture.js";
  21. import { setHostFaults, waitForHostBoundary, readHostBoundary } from "./subagent-host-window.js";
  22. import {
  23. assertRequestCacheBreakpoint,
  24. assertParentRequestHistory,
  25. type CapturedPrompt,
  26. } from "./provider-prefix.js";
  27. import { assertUpstreamThoughtLevelCapture } from "./upstream-capture.js";
  28. import { exportPromptTrajectory } from "./prompt-trajectory-export.js";
  29. import { UPSTREAM_MODEL, UPSTREAM_THOUGHT_LEVEL } from "./upstream-provider.js";
  30. type Peer = { handle: string; sessionId: string; hostPid: number; cliPid: number };
  31. export async function exerciseSubagentHostBranches(
  32. peers: { a: Peer; b: Peer },
  33. base: RefreshProfile,
  34. updated: RefreshProfile,
  35. ) {
  36. const profilePath = join(getE2EAppDataPaths().storageRoot, "agents", `${base.name}.md`);
  37. const extraTurns = { a: 0, b: 0 };
  38. const previousListing: Record<string, string[]> = {};
  39. async function run(
  40. peer: "a" | "b",
  41. stage: string,
  42. expected: RefreshProfile | "missing" | "fallback" | "override" | "default",
  43. startOnly = false,
  44. ) {
  45. const target = peers[peer];
  46. await browser.switchToWindow(target.handle);
  47. const children = readChildSessionIds(target.sessionId);
  48. const beforeCount = (await readSubagentCapture()).filter(
  49. (r) => r.replay?.fixtureId === `shb-${stage}-final`,
  50. ).length;
  51. const marker = `E2E_SHB_${stage.toUpperCase()}`;
  52. const prompt = `${marker}: Execute the requested Agent verification for Host ${peer}.`;
  53. if (startOnly) await sendV4Prompt(prompt);
  54. else await sendV4PromptAndWaitAccepted(prompt, marker, `未接收 ${marker}`);
  55. extraTurns[peer]++;
  56. const finish = async () => {
  57. await finishSubagentTurn(`${marker}_DONE`, 60000);
  58. expect((await getV4PaneSnapshot()).sessionId).toBe(target.sessionId);
  59. const captured = await readSubagentCapture();
  60. const final = captured.filter((r) => r.replay?.fixtureId === `shb-${stage}-final`)[
  61. beforeCount
  62. ]!;
  63. expect(final?.status).toBe("complete");
  64. const body = final.requestJson as CapturedPrompt;
  65. const listing = readMessageTextBlocks(body)
  66. .filter((b) =>
  67. /(?:Available agent types|New agent types|The following agent types are no longer available)/u.test(
  68. b.text,
  69. ),
  70. )
  71. .map((b) => b.text);
  72. const changes: Record<string, [string, string[]]> = {
  73. add: ["New agent types", ["e2e-host-added"]],
  74. disabled: ["no longer available", ["e2e-host-added"]],
  75. reenabled: ["New agent types", ["e2e-host-renamed"]],
  76. renamed_old: ["no longer available", ["e2e-host-renamed", "e2e-host-final"]],
  77. deleted: ["no longer available", ["e2e-host-final"]],
  78. };
  79. if (previousListing[peer]) {
  80. const change = changes[stage];
  81. if (change) {
  82. expect(listing.slice(0, previousListing[peer].length)).toEqual(previousListing[peer]);
  83. expect(listing.length).toBeGreaterThan(previousListing[peer].length);
  84. const delta = listing.slice(previousListing[peer].length).join("\n");
  85. expect(delta).toContain(change[0]);
  86. for (const name of change[1]) expect(delta).toContain(name);
  87. } else if (expected === "fallback" || stage.endsWith("retried_b")) {
  88. expect(listing.slice(0, previousListing[peer].length)).toEqual(previousListing[peer]);
  89. expect(listing.length).toBeGreaterThan(previousListing[peer].length);
  90. expect(listing.slice(previousListing[peer].length).join("\n")).toContain(
  91. expected === "fallback" ? "no longer available" : "New agent types",
  92. );
  93. } else expect(listing).toEqual(previousListing[peer]);
  94. }
  95. previousListing[peer] = listing;
  96. const results = (
  97. body.messages.at(-1)!.content as Array<{
  98. type: string;
  99. tool_use_id: string;
  100. content: unknown;
  101. is_error?: boolean;
  102. }>
  103. ).filter((r) => r.type === "tool_result");
  104. if (expected === "missing" || expected === "fallback") {
  105. if (expected === "missing") expect(readChildSessionIds(target.sessionId)).toEqual(children);
  106. else {
  107. expect(readChildSessionIds(target.sessionId)).toHaveLength(children.length + 1);
  108. const child = captured.filter((r) => r.replay?.fixtureId === `shb-${stage}-child`)[
  109. beforeCount
  110. ]!;
  111. expect(child?.status).toBe("complete");
  112. expect(child.requestJson).toMatchObject({ model: UPSTREAM_MODEL });
  113. assertRequestCacheBreakpoint(child.requestJson as CapturedPrompt);
  114. }
  115. expect(results).toHaveLength(expected === "fallback" ? 3 : 2);
  116. for (const result of results.filter((r) => !r.tool_use_id.endsWith("_builtin"))) {
  117. expect(JSON.stringify(result.content)).toMatch(/not found|unavailable/u);
  118. }
  119. expect(results.find((r) => r.tool_use_id.endsWith("_spawn"))?.is_error).toBe(true);
  120. } else {
  121. expect(readChildSessionIds(target.sessionId)).toHaveLength(children.length + 1);
  122. const child = captured.filter((r) => r.replay?.fixtureId === `shb-${stage}-child`)[
  123. beforeCount
  124. ]!;
  125. expect(child?.status).toBe("complete");
  126. if (typeof expected === "object") assertSubagentProfile(child, expected);
  127. else {
  128. expect(child.requestJson).toMatchObject({
  129. model: expected === "override" ? updated.model : UPSTREAM_MODEL,
  130. });
  131. assertUpstreamThoughtLevelCapture(
  132. child,
  133. expected === "override" ? base.effort : UPSTREAM_THOUGHT_LEVEL,
  134. );
  135. }
  136. assertRequestCacheBreakpoint(child.requestJson as CapturedPrompt);
  137. }
  138. return final;
  139. };
  140. return startOnly ? finish : finish();
  141. }
  142. async function both(stage: string, expected: Parameters<typeof run>[2]) {
  143. await run("a", stage, expected);
  144. await run("b", stage, expected);
  145. }
  146. const save = async (peer: "a" | "b", profile: RefreshProfile, previous = profile.name) => {
  147. await browser.switchToWindow(peers[peer].handle);
  148. await saveRefreshProfile(profile, previous);
  149. };
  150. async function received(
  151. action: () => Promise<void>,
  152. pids = [peers.a.hostPid, peers.b.hostPid],
  153. changedPaths: string[] = [],
  154. ) {
  155. const updated = await subagentUpdateCursor();
  156. await action();
  157. await updated(pids, changedPaths);
  158. }
  159. // 双向保存由各 Host 的原生文件事件独立消费。
  160. let current = { ...base, prompt: "E2E_SHB_REVERSE_PROFILE" };
  161. await received(() => save("b", current));
  162. await both("reverse", current);
  163. let added = { ...updated, name: "e2e-host-added", prompt: "E2E_SHB_ADDED_PROFILE" };
  164. await received(async () => {
  165. await browser.switchToWindow(peers.a.handle);
  166. await saveRefreshProfile(added);
  167. });
  168. await both("add", added);
  169. added = {
  170. ...added,
  171. description: "Updated same-name description",
  172. prompt: "E2E_SHB_UPDATED_PROFILE",
  173. };
  174. await received(() => save("b", added));
  175. await both("update", added);
  176. await browser.switchToWindow(peers.b.handle);
  177. await received(() => setRefreshProfileEnabled(added.name, false));
  178. await both("disabled", "missing");
  179. const renamed = { ...added, name: "e2e-host-renamed" };
  180. await received(() => save("a", renamed, added.name), undefined, [`${renamed.name}.md`]);
  181. await both("renamed_disabled", "missing");
  182. await browser.switchToWindow(peers.b.handle);
  183. await received(() => setRefreshProfileEnabled(renamed.name, true));
  184. await both("reenabled", renamed);
  185. const finalName = { ...renamed, name: "e2e-host-final" };
  186. await received(() => save("a", finalName, renamed.name), undefined, [`${finalName.name}.md`]);
  187. await both("renamed_old", "missing");
  188. await both("renamed_new", finalName);
  189. await browser.switchToWindow(peers.b.handle);
  190. await received(() => deleteRefreshProfile(finalName.name));
  191. await both("deleted", "missing");
  192. for (const [name, id, tag] of [
  193. ["Explore", "Explore", "explore"],
  194. ["e2e-subagent-refresh:reviewer", "plugin:e2e-subagent-refresh@e2e-fixture:reviewer", "plugin"],
  195. ] as const) {
  196. await browser.switchToWindow(peers.a.handle);
  197. await received(() => setRefreshModelOverride(name, id, { ...updated, effort: base.effort }));
  198. await both(`override_${tag}`, "override");
  199. await browser.switchToWindow(peers.b.handle);
  200. await received(() => setRefreshModelOverride(name, id));
  201. await both(`clear_${tag}`, "default");
  202. }
  203. // 写盘失败:真实 UI 留在编辑表单,双方缓存/原文件不变,不发布持久化事件。
  204. const original = await readFile(profilePath, "utf8");
  205. await setHostFaults({
  206. files: [{ id: "save-failure", operation: "writeFile", path: profilePath, action: "fail" }],
  207. });
  208. await browser.switchToWindow(peers.b.handle);
  209. await saveRefreshProfile({ ...updated, name: base.name, prompt: "E2E_SHB_UNSAVED" }, base.name, {
  210. expectedError: "E2E writeFile failed",
  211. });
  212. expect(await readFile(profilePath, "utf8")).toBe(original);
  213. await setHostFaults({});
  214. await both("save_failed", current);
  215. // 外部编辑采用相同 watcher;重复快速写入只读最终文件,不扫描其他范围。
  216. const tracePaths = [
  217. profilePath,
  218. join(getE2EAppDataPaths().storageRoot, "agents"),
  219. join(getE2EAppDataPaths().storageRoot, "v2", "agents-state.json"),
  220. join(getE2EAppDataPaths().workspace, ".zcode", "agents"),
  221. ];
  222. await setHostFaults({ tracePaths });
  223. current = { ...current, prompt: "E2E_SHB_VALIDATED_PROFILE" };
  224. await received(async () => {
  225. const original = await readFile(profilePath, "utf8");
  226. const content = original.replace("E2E_SHB_REVERSE_PROFILE", current.prompt);
  227. await writeFile(profilePath, content + "\n");
  228. await writeFile(profilePath, content);
  229. });
  230. await both("duplicated", current);
  231. const configReads = async () => {
  232. const calls = (await readHostBoundary()).filter((r) => r.kind === "file-called");
  233. // 原生监听库为发现增删文件需要枚举目录;配置 loader 的目录扫描仍不允许。
  234. for (const call of calls.filter((r) => r.operation === "readdir"))
  235. expect(call.stack).toMatch(/ReaddirpStream/);
  236. return calls.filter((r) => r.operation !== "readdir");
  237. };
  238. const readsAfterReload = await configReads();
  239. expect(readsAfterReload).toHaveLength(1);
  240. expect(new Set(readsAfterReload.flatMap((r) => r.paths ?? []))).toEqual(new Set([profilePath]));
  241. await both("cache_hit", current);
  242. expect(await configReads()).toEqual(readsAfterReload);
  243. const unrelated = join(getE2EAppDataPaths().homeDir, "unrelated.md");
  244. await writeFile(unrelated, "external unrelated file");
  245. await both("unrelated_b", current);
  246. expect(await configReads()).toEqual(readsAfterReload);
  247. await setHostFaults({});
  248. // 文件读取失败:A 正常,B 自定义 spawn/resume 失败,但普通对话和内置 Agent 继续。
  249. await setHostFaults({
  250. files: [{ id: "read-failure", operation: "readFile", path: profilePath, action: "fail" }],
  251. });
  252. current = { ...current, prompt: "E2E_SHB_RETRY_PROFILE" };
  253. await received(() => save("a", current));
  254. await waitForHostBoundary("file-failed", "read-failure");
  255. await run("a", "read_ok_a", current);
  256. await run("b", "read_failed", "fallback");
  257. await setHostFaults({});
  258. await received(() =>
  259. (async () => {
  260. const content = await readFile(profilePath, "utf8");
  261. await writeFile(profilePath, content + "\n");
  262. })(),
  263. );
  264. await run("b", "read_retried_b", current);
  265. // 目录重建和全局 state 分别验证回退与事件恢复。
  266. for (const tag of ["directory", "state"] as const) {
  267. const path =
  268. tag === "state"
  269. ? join(getE2EAppDataPaths().storageRoot, "v2", "agents-state.json")
  270. : join(getE2EAppDataPaths().storageRoot, "agents");
  271. await setHostFaults({
  272. files: [
  273. { id: tag, operation: tag === "state" ? "readFile" : "readdir", path, action: "fail" },
  274. ],
  275. });
  276. await browser.switchToWindow(peers.a.handle);
  277. if (tag === "state")
  278. await received(() => setRefreshModelOverride("Explore", "Explore", updated));
  279. else {
  280. await received(async () => {
  281. const removed = await subagentUpdateCursor();
  282. await rename(path, path + "-saved");
  283. await removed([peers.a.hostPid, peers.b.hostPid], [path]);
  284. const recreated = await subagentUpdateCursor();
  285. await mkdir(path);
  286. for (const file of await readdir(path + "-saved"))
  287. await writeFile(join(path, file), await readFile(join(path + "-saved", file)));
  288. await rm(path + "-saved", { recursive: true });
  289. await recreated([peers.a.hostPid, peers.b.hostPid], [path]);
  290. });
  291. }
  292. await waitForHostBoundary("file-failed", tag);
  293. await run("a", `${tag}_ok_a`, current);
  294. await run("b", `${tag}_failed`, "fallback");
  295. await setHostFaults({});
  296. await received(async () => {
  297. const target = tag === "state" ? path : profilePath;
  298. const content = await readFile(target, "utf8");
  299. await writeFile(target, content + "\n");
  300. });
  301. await run("b", `${tag}_retried_b`, current);
  302. if (tag === "state") {
  303. await browser.switchToWindow(peers.a.handle);
  304. await received(() => setRefreshModelOverride("Explore", "Explore"));
  305. }
  306. }
  307. // 重载期间 RPC 立即返回旧快照;两次保存后迟到的旧读取成功/失败都不能覆盖最新结果。
  308. for (const rejection of [false, true]) {
  309. const id = rejection ? "stale_reject" : "stale_resolve";
  310. const readCount = Math.max(
  311. 0,
  312. ...(await readHostBoundary()).map((r) => r.readCounts?.[profilePath] ?? 0),
  313. );
  314. await setHostFaults({
  315. tracePaths: [profilePath],
  316. files: [
  317. {
  318. id,
  319. path: profilePath,
  320. operation: "readFile",
  321. action: "hold",
  322. once: true,
  323. rejectAfterRelease: rejection,
  324. },
  325. ],
  326. });
  327. await received(() => save("a", { ...current, prompt: `E2E_SHB_${id}_OLD` }), [peers.a.hostPid]);
  328. await waitForHostBoundary("file-held", id);
  329. const expected = { ...current, prompt: `E2E_SHB_${id}_LATEST` };
  330. // 完整父子请求必须先完成,之后才释放文件屏障,证明对话没有等待后台 I/O。
  331. await run("b", id, current);
  332. expect((await readHostBoundary()).some((r) => r.kind === "file-released" && r.id === id)).toBe(
  333. false,
  334. );
  335. await received(() => save("a", expected), [peers.a.hostPid]);
  336. await setHostFaults({ released: [id], tracePaths: [profilePath] });
  337. await waitForHostBoundary("file-released", id);
  338. await browser.waitUntil(
  339. async () =>
  340. (await readHostBoundary()).some(
  341. (r) =>
  342. r.kind === "snapshot-published" && (r.readCounts?.[profilePath] ?? 0) >= readCount + 2,
  343. ),
  344. { timeout: 20000, timeoutMsg: "B 未完成两次写入后的配置更新" },
  345. );
  346. await run("b", `${id}_published`, expected);
  347. current = expected;
  348. }
  349. await setHostFaults({});
  350. // 初始化各一次,之后每个父 turn 一次配置 RPC;失败/迟到结果不增加 turn 或替换 CLI。
  351. for (const [key, peer] of Object.entries(peers) as Array<["a" | "b", Peer]>) {
  352. const reads = (await boundaryRpcReads()).filter(
  353. // 计数属于当前 Host;另一窗口恢复同一历史时的初始化读取应单独归属。
  354. (r) => r.sessionId === peer.sessionId && r.hostPid === peer.hostPid && r.kind === "read",
  355. );
  356. expect(reads).toHaveLength(1 + (key === "a" ? 2 : 6) + extraTurns[key]);
  357. expect(new Set(reads.map((r) => `${r.hostPid}/${r.pid}`))).toEqual(
  358. new Set([`${peer.hostPid}/${peer.cliPid}`]),
  359. );
  360. const all = (await readSubagentCapture())
  361. .filter((r) => {
  362. const id = r.replay?.fixtureId ?? "";
  363. return (
  364. (/^shi-.*(seed|tool|final|notification)$/u.test(id) ||
  365. /^shb-.*-(tool|final)$/u.test(id)) &&
  366. JSON.stringify(r.requestJson).includes(`E2E_SHI_${key.toUpperCase()}_SEED:`)
  367. );
  368. })
  369. .map((r) => r.requestJson as CapturedPrompt);
  370. expect(all).toHaveLength((key === "a" ? 3 : 10) + extraTurns[key] * 2);
  371. assertParentRequestHistory(all);
  372. const exported = await exportPromptTrajectory(peer.sessionId, `subagent-host-branches-${key}`);
  373. expect(exported.trajectories).toEqual([
  374. expect.objectContaining({ reason: "initial", requestCount: all.length }),
  375. ]);
  376. }
  377. return current;
  378. }