conversation-session-offpeak-subagent-model-inheritance.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. import { readFile, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { fileURLToPath } from "node:url";
  4. import {
  5. TID_AUTOMATIONS_OPEN,
  6. TID_CHAT_MODEL_SELECT_ITEM,
  7. TID_CHAT_MODEL_SELECT_TRIGGER,
  8. TID_OFFPEAK_CARD,
  9. TID_OFFPEAK_CREATE_BUTTON,
  10. TID_OFFPEAK_EDIT_SUBMIT,
  11. TID_OFFPEAK_FORM_INSTRUCTIONS,
  12. TID_OFFPEAK_FORM_TITLE,
  13. TID_OFFPEAK_TAB,
  14. testId,
  15. } from "@zcode/shared/test-ids";
  16. import {
  17. clearAppData,
  18. clickTestIdByDom,
  19. setInputValueByTestIdDom,
  20. waitForTestIdByDom,
  21. } from "#e2e/helpers/desktop-app";
  22. import {
  23. assertUpstreamRequestCapture,
  24. waitForUpstreamNetworkCapture,
  25. } from "#e2e/helpers/upstream-capture";
  26. import {
  27. selectUpstreamModel,
  28. selectUpstreamThoughtLevel,
  29. UPSTREAM_MODEL,
  30. } from "#e2e/helpers/upstream-provider";
  31. import {
  32. prepareV4ConversationE2E,
  33. sendV4Prompt,
  34. waitForV4AssistantMessageContaining,
  35. waitForV4ConversationState,
  36. waitForV4ComposerText,
  37. waitForV4UserMessageContaining,
  38. switchV4Mode,
  39. } from "#e2e/helpers/v4-conversation";
  40. import { sel } from "#e2e/helpers/selectors";
  41. import { openFaultInjectedHostWindow, readHostBoundary } from "#e2e/helpers/subagent-host-window";
  42. const OFFPEAK_PARENT_MARKER = "E2E_OFFPEAK_SUBAGENTS_PARENT";
  43. const ORDINARY_PROMPT_MARKER = "E2E_OFFPEAK_SUBAGENTS_ORDINARY_PROMPT";
  44. const ORDINARY_REPLY_TOKEN = "E2E_OFFPEAK_SUBAGENTS_ORDINARY_OK";
  45. const EXPECTED_FOREGROUND_STAGES = [
  46. "child-explore",
  47. "child-general-purpose",
  48. "child-code-search",
  49. "child-custom-inherit",
  50. ] as const;
  51. const EXPECTED_BACKGROUND_STAGES = ["background-explicit", "background-profile"] as const;
  52. interface OffPeakMockRequestRecord {
  53. hasApiKey: boolean;
  54. hasAuthorization: boolean;
  55. hasCodingPlanApiKey: boolean;
  56. maxTokens?: number;
  57. model?: string;
  58. requestJson: unknown;
  59. stage: string;
  60. ticketId: string;
  61. }
  62. describe("闲时后台 subagent 模型继承与唤起 E2E", () => {
  63. after(async () => {
  64. await browser.electron.restoreAllMocks();
  65. await clearAppData();
  66. });
  67. it("OP10/IL01/IL02: foreground 与 background 继承闲时模型,主轮结束等待后台唤起,发送普通消息才切回用户模型", async function () {
  68. this.timeout(300000);
  69. const handoffFault = process.env.ZCODE_E2E_OFFPEAK_HANDOFF_FAULT === "1";
  70. if (handoffFault) {
  71. const { windowId } = await openFaultInjectedHostWindow(
  72. fileURLToPath(new URL("../../helpers/offpeak-host-faults.cjs", import.meta.url)),
  73. );
  74. // 只保留注入窗口,避免另一个 Host 先抢到闲时任务,使故障边界没有被执行。
  75. await browser.electron.execute((electron, retainedId) => {
  76. for (const window of electron.BrowserWindow.getAllWindows())
  77. if (window.id !== retainedId) window.close();
  78. }, windowId);
  79. }
  80. await prepareV4ConversationE2E();
  81. const takeover = process.env.ZCODE_E2E_OFFPEAK_TAKEOVER === "1";
  82. const title = `E2E_OFFPEAK_SUBAGENTS_${Date.now()}`;
  83. await createOffPeakTask({
  84. instructions: `${OFFPEAK_PARENT_MARKER}: verify the foreground subagent provider matrix.`,
  85. title,
  86. });
  87. let records = await waitForOffPeakScenarioCompletion();
  88. await clickTestIdByDom(TID_AUTOMATIONS_OPEN, {
  89. timeoutMsg: "闲时任务完成后无法重新打开 Automations",
  90. });
  91. await openOffPeakTab();
  92. await browser.waitUntil(
  93. async () => /Running|进行中|运行中/u.test((await readOffPeakCardText(title)) ?? ""),
  94. { timeout: 15000, timeoutMsg: "后台工作未结束时闲时卡应保持进行中" },
  95. );
  96. await openOffPeakTaskSession(title);
  97. await waitForV4ConversationState(
  98. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  99. "后台屏障关闭时主轮应已自然结束",
  100. 60000,
  101. );
  102. // 工具栏草稿选择用户模型但尚未发送,不得改变随后后台唤起使用的闲时 Selection。
  103. await selectUpstreamModel();
  104. await selectUpstreamThoughtLevel();
  105. await recordComposerSelection("before-background-wakeup");
  106. if (takeover) {
  107. await sendV4Prompt(ORDINARY_PROMPT_MARKER);
  108. await waitForV4ComposerText("", "用户接管消息没有提交");
  109. await waitForV4AssistantMessageContaining(ORDINARY_REPLY_TOKEN);
  110. }
  111. // 主轮已结束但后台仍在等待。显式放行真实子请求,证明通知能另起续跑轮。
  112. const port = Number(process.env.ZCODE_OFFPEAK_MOCK_PORT ?? "45197");
  113. const expireOnWake = handoffFault || process.env.ZCODE_E2E_OFFPEAK_EXPIRE_WAKE === "1";
  114. const release = await fetch(`http://127.0.0.1:${port}/__e2e/off-peak/release-background`, {
  115. method: "POST",
  116. headers: { "content-type": "application/json" },
  117. body: JSON.stringify({ expireOnWake }),
  118. });
  119. expect(release.ok).toBe(true);
  120. const bashNotification = "<tool-use-id>toolu_e2e_offpeak_bash</tool-use-id>";
  121. let userWakeBody: string | undefined;
  122. if (takeover) {
  123. const userWake = await waitForUpstreamNetworkCapture(bashNotification);
  124. assertUpstreamRequestCapture(userWake, {
  125. expectedText: bashNotification,
  126. model: UPSTREAM_MODEL,
  127. });
  128. userWakeBody = JSON.stringify(userWake.requestJson);
  129. } else {
  130. await browser.waitUntil(
  131. async () => {
  132. records = await readOffPeakMockRequests();
  133. return records.some((record) => record.stage === "parent-wakeup");
  134. },
  135. { timeout: 60000, timeoutMsg: "后台完成未唤起主 agent" },
  136. );
  137. }
  138. await clickTestIdByDom(TID_AUTOMATIONS_OPEN);
  139. await openOffPeakTab();
  140. await waitForOffPeakCardCompleted(title);
  141. if (handoffFault) {
  142. const boundary = await readHostBoundary();
  143. const failed = boundary.filter((event) => event.kind === "ticket-ack-failed");
  144. const confirmed = boundary.filter((event) => event.kind === "ticket-ack-confirmed");
  145. expect(failed).toHaveLength(1);
  146. expect(confirmed).toHaveLength(1);
  147. expect(confirmed[0]!.id).toBe(failed[0]!.id);
  148. expect(boundary.filter((event) => event.kind === "ticket-control")).toHaveLength(2);
  149. }
  150. records = await readOffPeakMockRequests();
  151. expect(records.filter((record) => record.stage === "bash-started")).toHaveLength(1);
  152. expect(records.filter((record) => record.stage === "parent-initial")).toHaveLength(1);
  153. const parentInitial = requireStage(records, "parent-initial");
  154. // 默认标题也属于本次闲时执行,不能只继承模型却漏掉请求票据。
  155. const sessionTitle = requireStage(records, "session-title");
  156. expect(sessionTitle.ticketId).toBe(parentInitial.ticketId);
  157. expect(sessionTitle.model).toBe(parentInitial.model);
  158. expect(sessionTitle.hasApiKey).toBe(true);
  159. const foregroundRecords = EXPECTED_FOREGROUND_STAGES.map((stage) =>
  160. requireStage(records, stage),
  161. );
  162. const parentContinuation = requireStage(records, "parent-continuation");
  163. const ticketIds = new Set(
  164. [parentInitial, ...foregroundRecords, parentContinuation].map((record) => record.ticketId),
  165. );
  166. expect(ticketIds.size).toBe(1);
  167. for (const record of foregroundRecords) {
  168. expect(record.model).toBe("GLM-5.3");
  169. expect(record.maxTokens).toBe(parentInitial.maxTokens);
  170. expect(record.hasApiKey).toBe(true);
  171. expect(record.hasAuthorization).toBe(true);
  172. expect(record.hasCodingPlanApiKey).toBe(true);
  173. }
  174. for (const stage of EXPECTED_BACKGROUND_STAGES) {
  175. const record = requireStage(records, stage);
  176. expect(record.model).toBe("GLM-5.3");
  177. expect(record.ticketId).toBe(parentInitial.ticketId);
  178. expect(record.hasCodingPlanApiKey).toBe(true);
  179. }
  180. const continuationBody = JSON.stringify(parentContinuation.requestJson);
  181. expect(continuationBody).not.toContain("Idle-time tasks do not support background agents.");
  182. let wakeBody = userWakeBody ?? "";
  183. if (takeover) {
  184. expect(records.some((record) => record.stage === "parent-wakeup")).toBe(false);
  185. } else {
  186. const wakeup = requireStage(records, "parent-wakeup");
  187. expect(wakeup.model).toBe("GLM-5.3");
  188. if (expireOnWake) {
  189. const expired = requireStage(records, "parent-wakeup-expired");
  190. expect(expired.ticketId).toBe(parentInitial.ticketId);
  191. expect(wakeup.ticketId).not.toBe(expired.ticketId);
  192. expect(
  193. records.some(
  194. (record) =>
  195. record.stage === "parent-wakeup" &&
  196. record.ticketId !== expired.ticketId &&
  197. JSON.stringify(record.requestJson) === JSON.stringify(expired.requestJson),
  198. ),
  199. ).toBe(true);
  200. } else {
  201. expect(wakeup.ticketId).toBe(parentInitial.ticketId);
  202. }
  203. wakeBody = JSON.stringify(wakeup.requestJson);
  204. }
  205. expect(wakeBody.includes("<tool-use-id>toolu_e2e_offpeak_bash</tool-use-id>")).toBe(true);
  206. const outputPath =
  207. /<output-file>([^<]*toolu_e2e_offpeak_bash-stdout\.log)<\/output-file>/u.exec(wakeBody)?.[1];
  208. expect(outputPath).toBeTruthy();
  209. expect(await readFile(JSON.parse(`"${outputPath!}"`) as string, "utf8")).toContain(
  210. "E2E_OFFPEAK_BACKGROUND_BASH_OK",
  211. );
  212. await openOffPeakTaskSession(title);
  213. await waitForV4ConversationState(
  214. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  215. "闲时任务完成后打开 session 没有回到 idle",
  216. 60000,
  217. );
  218. if (!takeover) {
  219. await recordComposerSelection("after-reopening-completed-task");
  220. await sendV4Prompt(ORDINARY_PROMPT_MARKER);
  221. await waitForV4ComposerText("", "闲时任务后的普通 prompt 没有提交");
  222. await waitForV4UserMessageContaining(ORDINARY_PROMPT_MARKER);
  223. }
  224. const ordinaryRecord = await waitForUpstreamNetworkCapture(ORDINARY_PROMPT_MARKER);
  225. assertUpstreamRequestCapture(ordinaryRecord, {
  226. expectedText: ORDINARY_PROMPT_MARKER,
  227. model: UPSTREAM_MODEL,
  228. });
  229. await waitForV4AssistantMessageContaining(ORDINARY_REPLY_TOKEN);
  230. const afterOrdinaryPrompt = await readOffPeakMockRequests();
  231. expect(
  232. afterOrdinaryPrompt.some((record) =>
  233. JSON.stringify(record.requestJson).includes(ORDINARY_PROMPT_MARKER),
  234. ),
  235. ).toBe(false);
  236. // F-OFFPEAK-001/F-OFFPEAK-003/F-OFFPEAK-005:闲时表单只展示隐藏
  237. // idle-plan 的扁平模型,不把当前 Chat 的 Start/Coding 连接泄漏进来。
  238. await clickTestIdByDom(TID_AUTOMATIONS_OPEN, {
  239. timeoutMsg: "普通 prompt 完成后无法打开 Automations",
  240. });
  241. await openOffPeakTab();
  242. await clickTestIdByDom(TID_OFFPEAK_CREATE_BUTTON, {
  243. timeoutMsg: "闲时任务创建入口没有出现",
  244. });
  245. await waitForTestIdByDom(TID_OFFPEAK_FORM_TITLE, {
  246. timeout: 15000,
  247. timeoutMsg: "闲时任务创建页没有打开",
  248. });
  249. const modelTrigger = $(sel(TID_CHAT_MODEL_SELECT_TRIGGER));
  250. await modelTrigger.waitForDisplayed({ timeout: 15000 });
  251. expect(await modelTrigger.getAttribute("data-model-current-value")).toBe("GLM-5.3");
  252. await modelTrigger.click();
  253. const visibleModelItems = await browser.execute(
  254. (itemPrefix) =>
  255. Array.from(document.querySelectorAll<HTMLElement>("[data-testid]"))
  256. .map((element) => element.dataset.testid ?? "")
  257. .filter((value) => value.startsWith(itemPrefix)),
  258. `${TID_CHAT_MODEL_SELECT_ITEM}-`,
  259. );
  260. expect(visibleModelItems).toEqual([testId(TID_CHAT_MODEL_SELECT_ITEM, "GLM-5.3")]);
  261. await browser.keys("Escape");
  262. });
  263. });
  264. /** 只读采集草稿与当前选择,区分空草稿不持久化和闲时执行覆盖普通模型。 */
  265. async function recordComposerSelection(stage: string): Promise<void> {
  266. const diagnostic = await browser.execute(() => ({
  267. text: document.body.innerText,
  268. config: document.querySelector('[data-testid="v4-model-config"]')?.outerHTML,
  269. pane: document.querySelector('[data-testid="v4-session-pane"]')?.outerHTML.slice(0, 700),
  270. drafts: Object.fromEntries(
  271. Object.entries(localStorage).filter(([key]) => key.startsWith("zcode-v4-composer")),
  272. ),
  273. }));
  274. await writeFile(
  275. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `offpeak-selection-${stage}.json`),
  276. JSON.stringify(diagnostic, null, 2),
  277. );
  278. }
  279. async function createOffPeakTask(input: { instructions: string; title: string }): Promise<void> {
  280. await clickTestIdByDom(TID_AUTOMATIONS_OPEN, {
  281. timeoutMsg: "侧栏没有出现 Automations 入口",
  282. });
  283. await openOffPeakTab();
  284. await clickTestIdByDom(TID_OFFPEAK_CREATE_BUTTON, {
  285. timeoutMsg: "闲时任务创建按钮没有出现",
  286. });
  287. await setInputValueByTestIdDom(TID_OFFPEAK_FORM_TITLE, input.title, {
  288. timeoutMsg: "闲时任务标题输入没有出现",
  289. });
  290. await setInputValueByTestIdDom(TID_OFFPEAK_FORM_INSTRUCTIONS, input.instructions, {
  291. timeoutMsg: "闲时任务 instructions 输入没有出现",
  292. });
  293. // 后台 Bash 是本用例的受测行为,任务显式使用全权限,避免停在交互审批。
  294. await switchV4Mode("yolo");
  295. await clickTestIdByDom(TID_OFFPEAK_EDIT_SUBMIT, {
  296. timeoutMsg: "闲时任务创建提交按钮不可点击",
  297. });
  298. }
  299. async function waitForOffPeakScenarioCompletion(): Promise<OffPeakMockRequestRecord[]> {
  300. let latest: OffPeakMockRequestRecord[] = [];
  301. await browser.waitUntil(
  302. async () => {
  303. latest = await readOffPeakMockRequests();
  304. return [
  305. "parent-continuation",
  306. "background-explicit",
  307. "background-profile",
  308. "bash-started",
  309. ].every((stage) => latest.some((record) => record.stage === stage));
  310. },
  311. {
  312. interval: 1000,
  313. timeout: 180000,
  314. timeoutMsg: "闲时 mock 没有完成 foreground subagent 场景",
  315. },
  316. );
  317. return latest;
  318. }
  319. async function readOffPeakMockRequests(): Promise<OffPeakMockRequestRecord[]> {
  320. const port = Number(process.env.ZCODE_OFFPEAK_MOCK_PORT ?? "45197");
  321. try {
  322. const response = await fetch(`http://127.0.0.1:${port}/__e2e/off-peak/requests`);
  323. if (!response.ok) return [];
  324. const body = (await response.json()) as {
  325. requests?: OffPeakMockRequestRecord[];
  326. };
  327. return Array.isArray(body.requests) ? body.requests : [];
  328. } catch {
  329. return [];
  330. }
  331. }
  332. function requireStage(
  333. records: readonly OffPeakMockRequestRecord[],
  334. stage: string,
  335. ): OffPeakMockRequestRecord {
  336. const record = records.findLast((candidate) => candidate.stage === stage);
  337. if (!record) {
  338. throw new Error(
  339. `闲时 mock 缺少请求阶段 ${stage}: ${JSON.stringify(
  340. records.map((candidate) => ({
  341. model: candidate.model,
  342. stage: candidate.stage,
  343. })),
  344. )}`,
  345. );
  346. }
  347. return record;
  348. }
  349. async function waitForOffPeakCardCompleted(title: string): Promise<void> {
  350. await browser.waitUntil(
  351. async () => {
  352. const text = await readOffPeakCardText(title);
  353. // Bug 原因:卡片成功终态的英文产品文案是 Succeeded,旧断言只接受 Completed。
  354. return /Completed|Succeeded|已完成/u.test(text ?? "");
  355. },
  356. {
  357. interval: 1000,
  358. timeout: 180000,
  359. timeoutMsg: `闲时任务没有进入 completed: ${title}`,
  360. },
  361. );
  362. }
  363. async function openOffPeakTab(): Promise<void> {
  364. await browser.waitUntil(
  365. () =>
  366. browser.execute((tabTestId) => {
  367. const tabGroup = document.querySelector<HTMLElement>(`[data-testid="${tabTestId}"]`);
  368. if (!tabGroup && document.querySelector('[data-testid="offpeak-create-button"]'))
  369. return true;
  370. const offPeakButton = Array.from(
  371. tabGroup?.querySelectorAll<HTMLButtonElement>("button") ?? [],
  372. ).find((button) => /闲时任务|Idle/u.test(button.textContent ?? ""));
  373. if (!offPeakButton) return false;
  374. offPeakButton.click();
  375. return true;
  376. }, TID_OFFPEAK_TAB),
  377. {
  378. interval: 500,
  379. timeout: 30000,
  380. timeoutMsg: "Automations 没有出现闲时任务标签",
  381. },
  382. );
  383. }
  384. async function readOffPeakCardText(title: string): Promise<string | null> {
  385. return browser.execute(
  386. (cardTestId, expectedTitle) =>
  387. Array.from(document.querySelectorAll<HTMLElement>(`[data-testid="${cardTestId}"]`))
  388. .find((card) => card.textContent?.includes(expectedTitle))
  389. ?.textContent?.trim() ?? null,
  390. TID_OFFPEAK_CARD,
  391. title,
  392. );
  393. }
  394. async function openOffPeakTaskSession(title: string): Promise<void> {
  395. await browser.waitUntil(
  396. async () =>
  397. browser.execute(
  398. (cardTestId, expectedTitle) => {
  399. const card = Array.from(
  400. document.querySelectorAll<HTMLElement>(`[data-testid="${cardTestId}"]`),
  401. ).find((candidate) => candidate.textContent?.includes(expectedTitle));
  402. const sessionButton = Array.from(
  403. card?.querySelectorAll<HTMLButtonElement>("button") ?? [],
  404. ).find((button) => !button.dataset.testid);
  405. if (!sessionButton) return false;
  406. sessionButton.click();
  407. return true;
  408. },
  409. TID_OFFPEAK_CARD,
  410. title,
  411. ),
  412. {
  413. interval: 500,
  414. timeout: 30000,
  415. timeoutMsg: `闲时任务卡片没有出现 session 跳转入口: ${title}`,
  416. },
  417. );
  418. }