conversation-session-subagent-context-boundaries.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. // 原因:本用例的回放 Provider 只声明 high/max;保留两个不同合法档位验证配置更新与隔离。
  2. import {
  3. useEnglishSubagentSettings,
  4. finishSubagentTurn,
  5. waitForSubagentIdle,
  6. assertSubagentTurnFailed,
  7. } from "#e2e/helpers/subagent-refresh-conversation";
  8. import { clearAppData } from "#e2e/helpers/desktop-app";
  9. import { saveRefreshProfile, type RefreshProfile } from "#e2e/helpers/subagent-refresh-settings";
  10. import {
  11. UPSTREAM_MODEL,
  12. UPSTREAM_PROVIDER_ID,
  13. UPSTREAM_ALTERNATE_MODEL,
  14. UPSTREAM_ALTERNATE_PROVIDER_ID,
  15. } from "#e2e/helpers/upstream-provider";
  16. import {
  17. prepareV4ConversationE2E,
  18. getV4PaneSnapshot,
  19. sendV4PromptAndWaitAccepted,
  20. sendV4Prompt,
  21. waitForV4AssistantMessageContaining,
  22. } from "#e2e/helpers/v4-conversation";
  23. import {
  24. readSubagentCapture,
  25. waitForSubagentRequest,
  26. assertSubagentProfile,
  27. readChildSessionIds,
  28. readSubagentId,
  29. failBoundaryReads,
  30. boundaryRpcReads,
  31. assertChildTrajectory,
  32. } from "#e2e/helpers/subagent-refresh-capture";
  33. import {
  34. assertProviderPrefix,
  35. assertRequestCacheBreakpoint,
  36. type CapturedPrompt,
  37. } from "#e2e/helpers/provider-prefix";
  38. import { exportPromptTrajectory } from "#e2e/helpers/prompt-trajectory-export";
  39. const old: RefreshProfile = {
  40. name: "e2e-context-reviewer",
  41. description: "Context boundaries",
  42. prompt: "E2E_SCB_PROFILE_OLD",
  43. model: UPSTREAM_MODEL,
  44. provider: UPSTREAM_PROVIDER_ID,
  45. effort: "high",
  46. tools: ["Read"],
  47. };
  48. const updated: RefreshProfile = {
  49. ...old,
  50. prompt: "E2E_SCB_PROFILE_NEW",
  51. model: UPSTREAM_ALTERNATE_MODEL,
  52. provider: UPSTREAM_ALTERNATE_PROVIDER_ID,
  53. effort: "max",
  54. tools: ["Grep"],
  55. };
  56. const later: RefreshProfile = { ...old, prompt: "E2E_SCB_PROFILE_LATER" };
  57. describe("Subagent 上下文边界与故障", () => {
  58. let terminalSession: string;
  59. let runningSession: string;
  60. let crossSession: string;
  61. // 修复原因:wdio 的 Mocha 单 case 上限固定 120s,用例内 this.timeout 不生效;原单个 it 串行跑 9 个父轮,
  62. // 本机空载已需约 115s,CI 稍慢即 Mocha Timeout。按叙事阶段拆成共享同一会话状态、顺序执行的多个 it,
  63. // 每段独占一份 120s 预算,断言与原用例一致。
  64. let parent: string;
  65. let terminal: string;
  66. let running: string;
  67. after(async () => {
  68. await failBoundaryReads([]);
  69. await browser.electron.restoreAllMocks();
  70. await clearAppData();
  71. });
  72. it("SHR10-SHR13: running 保留旧配置,读取失败结束父轮", async () => {
  73. await prepareV4ConversationE2E();
  74. await useEnglishSubagentSettings();
  75. await saveRefreshProfile(old);
  76. await turn("SEED", `Launch ${old.name} with prompt E2E_SCB_SEED_CHILD.`);
  77. parent = (await getV4PaneSnapshot()).sessionId!;
  78. terminal = readSubagentId(await waitForSubagentRequest("scb-seed-final"));
  79. terminalSession = readChildSessionIds(parent)[0]!;
  80. await turn("RUNNING", `Launch ${old.name} in background with prompt E2E_SCB_RUNNING_CHILD.`);
  81. running = readSubagentId(await waitForSubagentRequest("scb-running-final"));
  82. runningSession = readChildSessionIds(parent).find((id) => id !== terminalSession)!;
  83. await started("E2E_SCB_RUNNING_CHILD", true);
  84. await saveRefreshProfile(updated, old.name);
  85. await failBoundaryReads([parent]);
  86. try {
  87. await sendV4Prompt(
  88. `E2E_SCB_FAIL_TERMINAL: Attempt Agent ${old.name} and SendMessage E2E_SCB_REJECTED to agentId: ${terminal}.`,
  89. );
  90. await assertSubagentTurnFailed("E2E_SCB_FAIL_TERMINAL:", "E2E_CONFIG_UNAVAILABLE");
  91. await sendV4Prompt(
  92. `E2E_SCB_FAIL_RUNNING: SendMessage E2E_SCB_REJECTED_MESSAGE to agentId: ${running}.`,
  93. );
  94. await assertSubagentTurnFailed("E2E_SCB_FAIL_RUNNING:", "E2E_CONFIG_UNAVAILABLE");
  95. expect(readChildSessionIds(parent)).toEqual([terminalSession, runningSession]);
  96. expect(
  97. (await boundaryRpcReads()).filter((r) => r.sessionId === parent && r.failed),
  98. ).toHaveLength(2);
  99. } finally {
  100. await failBoundaryReads([]);
  101. }
  102. });
  103. it("SHR10-SHR13: 读取恢复后消息投递,新 child 使用新配置", async () => {
  104. // 失败轮没有执行 SendMessage;成功重新读取后正常投递,child 继续使用启动时配置。
  105. await turn("DELIVER_RUNNING", `SendMessage E2E_SCB_DELIVER_RECOVERED to agentId: ${running}.`);
  106. const recovered = await waitForSubagentRequest("scb-deliver-running-tool");
  107. for (const marker of ["E2E_SCB_FAIL_TERMINAL:", "E2E_SCB_FAIL_RUNNING:"])
  108. expect(JSON.stringify(recovered.requestJson).split(marker)).toHaveLength(2);
  109. // 同一个 running child 跨到成功读取 v2 的父轮;新 child 使用 v2。
  110. await turn(
  111. "CROSS",
  112. `SendMessage E2E_SCB_DELIVER_NEXT and spawn ${old.name} with E2E_SCB_CROSS_CHILD; agentId: ${running}.`,
  113. );
  114. assertSubagentProfile(await waitForSubagentRequest("scb-cross-child"), updated);
  115. crossSession = readChildSessionIds(parent).find(
  116. (id) => ![terminalSession, runningSession].includes(id),
  117. )!;
  118. expect(
  119. (await readSubagentCapture()).some((r) => r.replay?.fixtureId === "scb-running-message-next"),
  120. ).toBe(false);
  121. // 两条引导在 child 的同一个边界按 FIFO 一次取出,合进同一个后续请求。
  122. const delivered = await waitForSubagentRequest("scb-running-message-next");
  123. assertSubagentProfile(delivered, old);
  124. const deliveredBody = JSON.stringify(delivered.requestJson);
  125. expect(deliveredBody.indexOf("E2E_SCB_DELIVER_RECOVERED")).toBeGreaterThanOrEqual(0);
  126. expect(deliveredBody.indexOf("E2E_SCB_DELIVER_RECOVERED")).toBeLessThan(
  127. deliveredBody.indexOf("E2E_SCB_DELIVER_NEXT"),
  128. );
  129. expect(deliveredBody).not.toContain("E2E_SCB_REJECTED_MESSAGE");
  130. await waitForV4AssistantMessageContaining("E2E_SCB_BACKGROUND_NOTED", 120000);
  131. await idle();
  132. await turn(
  133. "RUNNING_RESUME",
  134. `SendMessage E2E_SCB_RUNNING_RESUME_CHILD to agentId: ${running}.`,
  135. );
  136. assertSubagentProfile(await waitForSubagentRequest("scb-running-resume-child"), updated);
  137. await waitForV4AssistantMessageContaining("E2E_SCB_RUNNING_RESUME_NOTED", 60000);
  138. await idle();
  139. });
  140. it("SHR10-SHR13: running resume 与 503 自动重试期间不重读配置", async () => {
  141. // 首次请求延迟后返回 503;保存发生在首次请求与自动重试之前。
  142. await send("STABLE", `SendMessage E2E_SCB_STABLE_CHILD to agentId: ${terminal}.`);
  143. await started("E2E_SCB_STABLE:");
  144. await saveRefreshProfile(later, old.name);
  145. expect(
  146. (await readSubagentCapture()).some((r) => r.replay?.fixtureId === "scb-stable-child"),
  147. ).toBe(false);
  148. const first = await waitForSubagentRequest("scb-stable-retry");
  149. expect(first.statusCode).toBe(503);
  150. const retry = await waitForSubagentRequest("scb-stable-tool");
  151. expect(retry.requestJson).toEqual(first.requestJson);
  152. assertSubagentProfile(await waitForSubagentRequest("scb-stable-child"), updated);
  153. await finish("STABLE");
  154. await waitForV4AssistantMessageContaining("E2E_SCB_STABLE_NOTED", 60000);
  155. await idle();
  156. // 首次 provider 请求到自动重试之间没有新配置 RPC。
  157. const wire = await boundaryRpcReads();
  158. expect(
  159. wire.filter(
  160. (r) =>
  161. r.kind === "read" &&
  162. r.sessionId === parent &&
  163. r.time > Date.parse(first.startedAt) &&
  164. r.time <= Date.parse(retry.startedAt),
  165. ),
  166. ).toHaveLength(0);
  167. });
  168. it("SHR10-SHR13: 后续轮使用最新配置且请求前缀保持连续", async () => {
  169. await turn("NEXT", `SendMessage E2E_SCB_NEXT_CHILD to agentId: ${terminal}.`);
  170. assertSubagentProfile(await waitForSubagentRequest("scb-next-child"), later);
  171. await waitForV4AssistantMessageContaining("E2E_SCB_NEXT_NOTED", 60000);
  172. await idle();
  173. expect(readChildSessionIds(parent)).toHaveLength(3);
  174. const bodies = (await readSubagentCapture())
  175. .filter(
  176. (r) =>
  177. r.replay?.fixtureId?.startsWith("scb-") &&
  178. r.replay?.fixtureId !== "scb-title" &&
  179. !JSON.stringify((r.requestJson as CapturedPrompt)?.system).includes("E2E_SCB_PROFILE_"),
  180. )
  181. .map((r) => r.requestJson as CapturedPrompt);
  182. for (let index = 1; index < bodies.length; index++)
  183. assertProviderPrefix(bodies[index - 1]!, bodies[index]!);
  184. const listing = (body: CapturedPrompt) =>
  185. body.messages
  186. .flatMap((m) => (Array.isArray(m.content) ? m.content : []))
  187. .filter(
  188. (b) => b.type === "text" && b.text.includes("Available agent types for the Agent tool:"),
  189. );
  190. expect(listing(bodies.at(-1)!)).toHaveLength(1);
  191. expect(JSON.stringify(bodies)).not.toContain(
  192. "The following agent types are no longer available:",
  193. );
  194. const exported = await exportPromptTrajectory(parent, "subagent-boundary-parent");
  195. expect(exported.trajectories).toHaveLength(1);
  196. expect(bodies).toHaveLength(19);
  197. // 一次 503 自动重试产生两次 wire 请求,对应同一条成功的 model-io 请求。
  198. expect(exported.trajectories[0]?.requestCount).toBe(18);
  199. });
  200. it("SHR15: terminal child 保留全部历史与工具配对,配置变化后轨迹仍连续单段", async () => {
  201. await assertChildTrajectory(terminalSession, [
  202. "scb-seed-child",
  203. "scb-seed-child-final",
  204. "scb-stable-child",
  205. "scb-next-child",
  206. ]);
  207. });
  208. it("SHR15: running child 在同一边界取出全部消息并在 resume 后保留完整历史", async () => {
  209. await assertChildTrajectory(runningSession, [
  210. "scb-running-child",
  211. "scb-running-message-next",
  212. "scb-running-resume-child",
  213. ]);
  214. await assertChildTrajectory(crossSession, ["scb-cross-child"]);
  215. });
  216. it("SHR15: 每个 child provider 请求保留完整对话前缀的缓存 breakpoint", async () => {
  217. const failures: string[] = [];
  218. const children = (await readSubagentCapture()).filter((r) =>
  219. JSON.stringify((r.requestJson as CapturedPrompt)?.system).includes("E2E_SCB_PROFILE_"),
  220. );
  221. expect(children).toHaveLength(8);
  222. for (const record of children) {
  223. try {
  224. assertRequestCacheBreakpoint(record.requestJson as CapturedPrompt);
  225. } catch (error) {
  226. failures.push(`${record.replay?.fixtureId}: ${String(error)}`);
  227. }
  228. }
  229. expect(failures).toEqual([]);
  230. });
  231. });
  232. async function send(stage: string, instruction: string) {
  233. const marker = `E2E_SCB_${stage}`;
  234. await sendV4PromptAndWaitAccepted(`${marker}: ${instruction}`, marker, `未接收 ${marker}`);
  235. }
  236. const idle = () => waitForSubagentIdle(120000);
  237. const finish = (stage: string) => finishSubagentTurn(`E2E_SCB_${stage}_DONE`, 120000);
  238. async function turn(stage: string, instruction: string) {
  239. await send(stage, instruction);
  240. await finish(stage);
  241. }
  242. async function started(marker: string, child = false) {
  243. await browser.waitUntil(
  244. async () =>
  245. (await readSubagentCapture()).some((r) => {
  246. const body = r.requestJson as CapturedPrompt | undefined;
  247. return (
  248. body &&
  249. JSON.stringify(body.messages).includes(marker) &&
  250. (child
  251. ? JSON.stringify(body.system).includes("E2E_SCB_PROFILE_")
  252. : !JSON.stringify(body.system).includes("E2E_SCB_PROFILE_")) &&
  253. !JSON.stringify(body).includes("Generate a concise title")
  254. );
  255. }),
  256. { timeout: 30000, timeoutMsg: `请求未开始 ${marker}` },
  257. );
  258. }