conversation-session-subagent-runtime-catalog-reasoning.test.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. import { readdir, readFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { parse as parseYaml } from "yaml";
  4. import { decodeCustomModelValue, encodeCustomModelValue } from "@zcode/shared";
  5. import {
  6. TID_CHAT_MODEL_SELECT_GROUP,
  7. TID_CHAT_MODEL_SELECT_ITEM,
  8. TID_CHAT_MODEL_SELECT_TRIGGER,
  9. TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM,
  10. TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER,
  11. TID_SETTINGS_BACK_BUTTON,
  12. TID_SETTINGS_PAGE,
  13. TID_SETTINGS_SECTION_NAV,
  14. TID_SUBAGENT_BUILT_IN_MODEL_TRIGGER,
  15. TID_SUBAGENT_ROW,
  16. TID_TASK_SETTINGS_BUTTON,
  17. TID_V4_MODEL_CONFIG,
  18. testId,
  19. } from "@zcode/shared/test-ids";
  20. import { selectCombinedComposerThoughtLevel } from "../helpers/composer-model-picker.js";
  21. import {
  22. DEFAULT_WORKSPACE,
  23. clearAppData,
  24. clickTestIdByDom,
  25. readAgentsState,
  26. waitForTestIdByDom,
  27. waitForWorkspaceApp,
  28. } from "../helpers/desktop-app.js";
  29. import type {
  30. E2ENetworkCaptureArtifact,
  31. E2ENetworkCaptureRecord,
  32. } from "../helpers/network-capture-proxy.js";
  33. import {
  34. UPSTREAM_MODEL,
  35. UPSTREAM_PROVIDER_ID,
  36. selectUpstreamProviderModelById,
  37. } from "../helpers/upstream-provider.js";
  38. import { resolveE2EStorageRoot } from "../helpers/e2e-runtime-paths.js";
  39. import {
  40. restartIntoWorkspacePreservingProfile,
  41. seedPersistedModelSelection,
  42. } from "../helpers/model-provider-restart.js";
  43. import { sel } from "../helpers/selectors.js";
  44. import { waitForToolCallBlockByToolName } from "../helpers/conversation-session-tool.js";
  45. import {
  46. getV4PaneSnapshot,
  47. prepareV4ConversationE2E,
  48. sendV4Prompt,
  49. waitForV4AssistantMessageContaining,
  50. waitForV4ComposerText,
  51. waitForV4ConversationState,
  52. waitForV4UserMessageContaining,
  53. } from "../helpers/v4-conversation.js";
  54. const PROVIDER_ID = "e2e-claude-runtime-catalog";
  55. const PROVIDER_NAME = "Claude Runtime Catalog E2E";
  56. const MODEL_ID = "claude-opus-4-8";
  57. const MODEL_VALUE = encodeCustomModelValue(PROVIDER_ID, MODEL_ID);
  58. const UPSTREAM_MODEL_VALUE = encodeCustomModelValue(UPSTREAM_PROVIDER_ID, UPSTREAM_MODEL);
  59. const CUSTOM_AGENT_NAME = "e2e-claude-catalog-reviewer";
  60. const CUSTOM_AGENT_PATH = join(resolveE2EStorageRoot(), "agents", `${CUSTOM_AGENT_NAME}.md`);
  61. const SUBAGENT_FORM_SELECTOR = `form:has(input[type="text"]):has(${sel(TID_CHAT_MODEL_SELECT_TRIGGER)})`;
  62. const THOUGHT_LEVELS = ["low", "medium", "high", "xhigh"] as const;
  63. const INVALID_EFFORT = "invalid-e2e";
  64. const PARENT_EFFORT = "low";
  65. const GENERAL_EFFORT = "high";
  66. const EXPLORE_EFFORT = "xhigh";
  67. const CUSTOM_EFFORT = "medium";
  68. const MODEL_OUTPUT_TOKEN_BUDGET = 32_000;
  69. const REASONING_BUDGETS: Record<string, number> = {
  70. low: 4000,
  71. medium: 8000,
  72. high: 16000,
  73. xhigh: 31999,
  74. };
  75. const GENERAL_PARENT_MARKER = "E2E_CLAUDE_CATALOG_GENERAL_PARENT";
  76. const GENERAL_CHILD_MARKER = "E2E_CLAUDE_CATALOG_GENERAL_CHILD";
  77. const GENERAL_CHILD_REPLY_TOKEN = "E2E_CLAUDE_CATALOG_GENERAL_CHILD_OK";
  78. const GENERAL_FINAL_TOKEN = "claude-catalog-general-done";
  79. const EXPLORE_PARENT_MARKER = "E2E_CLAUDE_CATALOG_EXPLORE_PARENT";
  80. const EXPLORE_CHILD_MARKER = "E2E_CLAUDE_CATALOG_EXPLORE_CHILD";
  81. const EXPLORE_CHILD_REPLY_TOKEN = "E2E_CLAUDE_CATALOG_EXPLORE_CHILD_OK";
  82. const EXPLORE_FINAL_TOKEN = "claude-catalog-explore-done";
  83. const CUSTOM_PARENT_MARKER = "E2E_CLAUDE_CATALOG_CUSTOM_PARENT";
  84. const CUSTOM_CHILD_MARKER = "E2E_CLAUDE_CATALOG_CUSTOM_CHILD";
  85. const CUSTOM_CHILD_REPLY_TOKEN = "E2E_CLAUDE_CATALOG_CUSTOM_CHILD_OK";
  86. const CUSTOM_FINAL_TOKEN = "claude-catalog-custom-done";
  87. interface ModelIoRecord {
  88. error?: unknown;
  89. querySource?: unknown;
  90. request?: { body?: unknown };
  91. response?: unknown;
  92. sessionId?: unknown;
  93. }
  94. interface ModelIoMatch {
  95. body: Record<string, unknown>;
  96. sessionId: string;
  97. }
  98. describe("Subagent runtime reasoning catalog E2E", () => {
  99. after(async () => {
  100. await browser.electron.restoreAllMocks();
  101. await clearAppData();
  102. });
  103. it("I68: Provider Registry 档位经 Settings 落盘并在三个 child 请求中生效", async function () {
  104. this.timeout(360000);
  105. await prepareV4ConversationE2E({ skipProvider: true });
  106. await selectUpstreamProviderModelById(MODEL_ID, {
  107. includePlainModelFallback: false,
  108. providerId: PROVIDER_ID,
  109. providerName: PROVIDER_NAME,
  110. });
  111. await assertThoughtOptionsAndSelectInScope("body", THOUGHT_LEVELS, PARENT_EFFORT);
  112. await configureSubagentReasoningOverrides();
  113. await seedPersistedModelSelection({
  114. modelId: MODEL_ID,
  115. providerId: PROVIDER_ID,
  116. reasoningLevel: PARENT_EFFORT,
  117. });
  118. await restartIntoWorkspacePreservingProfile();
  119. await prepareV4ConversationE2E({ skipProvider: true });
  120. await runSubagentScenario({
  121. childMarker: GENERAL_CHILD_MARKER,
  122. childReplyToken: GENERAL_CHILD_REPLY_TOKEN,
  123. childEffort: GENERAL_EFFORT,
  124. finalToken: GENERAL_FINAL_TOKEN,
  125. parentMarker: GENERAL_PARENT_MARKER,
  126. subagentType: "general-purpose",
  127. });
  128. const exploreChildRecord = await runSubagentScenario({
  129. childMarker: EXPLORE_CHILD_MARKER,
  130. childReplyToken: EXPLORE_CHILD_REPLY_TOKEN,
  131. childEffort: EXPLORE_EFFORT,
  132. finalToken: EXPLORE_FINAL_TOKEN,
  133. parentMarker: EXPLORE_PARENT_MARKER,
  134. subagentType: "Explore",
  135. });
  136. expect(readToolNamesFromCapture(exploreChildRecord.requestJson)).toEqual([
  137. "Bash",
  138. "Read",
  139. "TodoWrite",
  140. "WebFetch",
  141. "RespondToCoordinator",
  142. ]);
  143. await runSubagentScenario({
  144. childMarker: CUSTOM_CHILD_MARKER,
  145. childReplyToken: CUSTOM_CHILD_REPLY_TOKEN,
  146. childEffort: CUSTOM_EFFORT,
  147. finalToken: CUSTOM_FINAL_TOKEN,
  148. parentMarker: CUSTOM_PARENT_MARKER,
  149. subagentType: CUSTOM_AGENT_NAME,
  150. });
  151. });
  152. });
  153. async function configureSubagentReasoningOverrides() {
  154. expect(await readAgentsState()).toMatchObject({
  155. builtInModelSelectionOverrides: {
  156. Explore: {
  157. providerId: PROVIDER_ID,
  158. modelId: MODEL_ID,
  159. options: { reasoningLevel: INVALID_EFFORT },
  160. },
  161. "general-purpose": {
  162. providerId: PROVIDER_ID,
  163. modelId: MODEL_ID,
  164. options: { reasoningLevel: GENERAL_EFFORT },
  165. },
  166. },
  167. });
  168. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  169. timeout: 15000,
  170. timeoutMsg: "没有找到设置入口按钮",
  171. });
  172. await waitForTestIdByDom(TID_SETTINGS_PAGE, {
  173. timeout: 15000,
  174. timeoutMsg: "设置页没有渲染",
  175. });
  176. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "subagents"), {
  177. timeout: 15000,
  178. timeoutMsg: "设置页没有出现 subagents 分区入口",
  179. });
  180. const generalScope = sel(testId(TID_SUBAGENT_ROW, "general-purpose"));
  181. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, "general-purpose"));
  182. await assertThoughtOptionsAndSelectInScope(generalScope, THOUGHT_LEVELS, GENERAL_EFFORT);
  183. await assertNoGenericModelTooltip(generalScope);
  184. const exploreScope = sel(testId(TID_SUBAGENT_ROW, "Explore"));
  185. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, "Explore"));
  186. expect(await $(exploreScope).getText()).toMatch(
  187. /Select a reasoning effort supported by this model|请选择当前模型支持的推理档位/u,
  188. );
  189. await assertCurrentThoughtLabel(exploreScope, INVALID_EFFORT);
  190. await assertThoughtOptionsAndSelectInScope(exploreScope, THOUGHT_LEVELS, EXPLORE_EFFORT);
  191. await assertNoGenericModelTooltip(exploreScope);
  192. await waitForAgentsState(
  193. (state) => readBuiltInReasoningLevel(state, "Explore") === EXPLORE_EFFORT,
  194. "Explore xhigh effort 没有写入 agents-state.json",
  195. );
  196. await selectModelInScope(generalScope, UPSTREAM_MODEL_VALUE);
  197. await waitForAgentsState(
  198. (state) =>
  199. readBuiltInModelValue(state, "general-purpose") === UPSTREAM_MODEL_VALUE &&
  200. readBuiltInReasoningLevel(state, "general-purpose") === null,
  201. "general-purpose 切换到 上游 后没有清除旧 effort",
  202. );
  203. await selectModelInScope(generalScope, MODEL_VALUE);
  204. await waitForAgentsState(
  205. (state) =>
  206. readBuiltInModelValue(state, "general-purpose") === MODEL_VALUE &&
  207. readBuiltInReasoningLevel(state, "general-purpose") === null,
  208. "general-purpose 切回 Claude 后不应恢复旧 effort",
  209. );
  210. await selectThoughtLevelInScope(generalScope, GENERAL_EFFORT);
  211. await waitForAgentsState(
  212. (state) => readBuiltInReasoningLevel(state, "general-purpose") === GENERAL_EFFORT,
  213. "general-purpose high effort 没有写入 agents-state.json",
  214. );
  215. await configureCustomSubagentReasoningOverride();
  216. await assertBuiltInLayoutAcrossThemes();
  217. expect(await readAgentsState()).toMatchObject({
  218. builtInModelSelectionOverrides: {
  219. Explore: {
  220. providerId: PROVIDER_ID,
  221. modelId: MODEL_ID,
  222. options: { reasoningLevel: EXPLORE_EFFORT },
  223. },
  224. "general-purpose": {
  225. providerId: PROVIDER_ID,
  226. modelId: MODEL_ID,
  227. options: { reasoningLevel: GENERAL_EFFORT },
  228. },
  229. },
  230. });
  231. expect(parseCustomAgentFrontmatter(await readFile(CUSTOM_AGENT_PATH, "utf8"))).toMatchObject({
  232. model: MODEL_VALUE,
  233. thoughtLevel: CUSTOM_EFFORT,
  234. });
  235. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  236. timeout: 15000,
  237. timeoutMsg: "设置页返回按钮没有出现",
  238. });
  239. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 30000);
  240. }
  241. async function configureCustomSubagentReasoningOverride() {
  242. const initialMarkdown = await readFile(CUSTOM_AGENT_PATH, "utf8");
  243. expect(initialMarkdown).toContain(`model: ${MODEL_VALUE}`);
  244. expect(initialMarkdown).toContain(`thoughtLevel: ${INVALID_EFFORT}`);
  245. await openCustomAgentForm();
  246. await assertCurrentThoughtLabel(SUBAGENT_FORM_SELECTOR, INVALID_EFFORT);
  247. await assertNoGenericModelTooltip(SUBAGENT_FORM_SELECTOR);
  248. await assertCustomFormLayoutAcrossThemes();
  249. const form = $(SUBAGENT_FORM_SELECTOR);
  250. expect(await form.getText()).toMatch(
  251. /Select a reasoning effort supported by this model|请选择当前模型支持的推理档位/u,
  252. );
  253. // 非法历史档位会禁用保存按钮;强行点击只会触发 WebDriver 拦截,不能证明产品拒绝保存。
  254. expect(await form.$('button[type="submit"]').isEnabled()).toBe(false);
  255. expect(await form.isDisplayed()).toBe(true);
  256. expect(await readFile(CUSTOM_AGENT_PATH, "utf8")).toBe(initialMarkdown);
  257. await assertThoughtOptionsAndSelectInScope(SUBAGENT_FORM_SELECTOR, THOUGHT_LEVELS, CUSTOM_EFFORT);
  258. await saveCustomAgentForm();
  259. await waitForCustomMarkdown(
  260. (content) => parseCustomAgentFrontmatter(content).thoughtLevel === CUSTOM_EFFORT,
  261. "custom 合法 medium effort 没有写入 Markdown",
  262. );
  263. await openCustomAgentForm();
  264. await selectModelInScope(SUBAGENT_FORM_SELECTOR, UPSTREAM_MODEL_VALUE);
  265. await selectModelInScope(SUBAGENT_FORM_SELECTOR, MODEL_VALUE);
  266. await saveCustomAgentForm();
  267. const clearedMarkdown = await waitForCustomMarkdown((content) => {
  268. const frontmatter = parseCustomAgentFrontmatter(content);
  269. return frontmatter.model === MODEL_VALUE && frontmatter.thoughtLevel === undefined;
  270. }, "custom 切换模型后没有删除旧 effort");
  271. expect(clearedMarkdown).not.toMatch(/^thoughtLevel:/mu);
  272. await openCustomAgentForm();
  273. await selectThoughtLevelInScope(SUBAGENT_FORM_SELECTOR, GENERAL_EFFORT);
  274. await selectThoughtLevelInScope(SUBAGENT_FORM_SELECTOR, CUSTOM_EFFORT);
  275. await saveCustomAgentForm();
  276. await waitForCustomMarkdown((content) => {
  277. const frontmatter = parseCustomAgentFrontmatter(content);
  278. return frontmatter.model === MODEL_VALUE && frontmatter.thoughtLevel === CUSTOM_EFFORT;
  279. }, "custom 最终 Claude model + medium effort 没有写入 Markdown");
  280. }
  281. async function openCustomAgentForm() {
  282. const rowTestId = testId(TID_SUBAGENT_ROW, CUSTOM_AGENT_NAME);
  283. await waitForTestIdByDom(rowTestId);
  284. await browser.waitUntil(
  285. async () =>
  286. browser.execute((currentRowTestId) => {
  287. const row = document.querySelector<HTMLElement>(`[data-testid="${currentRowTestId}"]`);
  288. if (!row) return false;
  289. // 编辑入口由整行承载;行内带 title 的按钮是删除,不能按 button[title] 定位。
  290. row.click();
  291. return true;
  292. }, rowTestId),
  293. { timeout: 15000, timeoutMsg: "custom subagent 行不可编辑" },
  294. );
  295. await $(SUBAGENT_FORM_SELECTOR).waitForDisplayed({
  296. timeout: 15000,
  297. timeoutMsg: "custom subagent 编辑表单没有打开",
  298. });
  299. }
  300. async function saveCustomAgentForm() {
  301. await $(SUBAGENT_FORM_SELECTOR).$('button[type="submit"]').click();
  302. await browser.waitUntil(async () => !(await $(SUBAGENT_FORM_SELECTOR).isExisting()), {
  303. timeout: 15000,
  304. timeoutMsg: "custom subagent 保存后表单没有关闭",
  305. });
  306. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, CUSTOM_AGENT_NAME));
  307. }
  308. async function selectModelInScope(scope: string, model: string) {
  309. const decodedModel = decodeCustomModelValue(model);
  310. if (!decodedModel) throw new Error(`E2E 仅支持选择 custom provider 模型: ${model}`);
  311. const itemTestId = testId(TID_CHAT_MODEL_SELECT_ITEM, model);
  312. const groupTestId = testId(
  313. TID_CHAT_MODEL_SELECT_GROUP,
  314. `registry-provider:${decodedModel.providerId}`,
  315. );
  316. const trigger = $(scope).$(sel(TID_CHAT_MODEL_SELECT_TRIGGER));
  317. await trigger.waitForClickable({ timeout: 15000 });
  318. await trigger.click();
  319. await browser.waitUntil(
  320. () =>
  321. browser.execute(
  322. (currentItemTestId, currentGroupTestId) =>
  323. Boolean(
  324. document.querySelector(`[data-testid="${currentItemTestId}"]`) ||
  325. document.querySelector(`[data-testid="${currentGroupTestId}"]`),
  326. ),
  327. itemTestId,
  328. groupTestId,
  329. ),
  330. { timeout: 15000, timeoutMsg: `模型菜单没有出现 ${model}` },
  331. );
  332. const itemVisible = await browser.execute(
  333. (currentItemTestId) => Boolean(document.querySelector(`[data-testid="${currentItemTestId}"]`)),
  334. itemTestId,
  335. );
  336. if (!itemVisible) {
  337. await browser.execute((currentGroupTestId) => {
  338. const group = document.querySelector<HTMLElement>(`[data-testid="${currentGroupTestId}"]`);
  339. if (!group) return;
  340. group.focus();
  341. for (const eventName of ["pointerenter", "mouseenter", "mousemove"] as const) {
  342. group.dispatchEvent(
  343. new MouseEvent(eventName, { bubbles: true, cancelable: true, view: window }),
  344. );
  345. }
  346. group.click();
  347. }, groupTestId);
  348. }
  349. await browser.waitUntil(
  350. () =>
  351. browser.execute(
  352. (currentItemTestId) =>
  353. Boolean(document.querySelector(`[data-testid="${currentItemTestId}"]`)),
  354. itemTestId,
  355. ),
  356. { timeout: 15000, timeoutMsg: `模型菜单没有出现 ${model}` },
  357. );
  358. await browser.execute((currentItemTestId) => {
  359. document.querySelector<HTMLElement>(`[data-testid="${currentItemTestId}"]`)?.click();
  360. }, itemTestId);
  361. await browser.waitUntil(
  362. async () =>
  363. (await $(scope)
  364. .$(sel(TID_CHAT_MODEL_SELECT_TRIGGER))
  365. .getAttribute("data-model-current-value")) === model,
  366. { timeout: 15000, timeoutMsg: `模型控件没有切换到 ${model}` },
  367. );
  368. }
  369. async function assertThoughtOptionsAndSelectInScope(
  370. scope: string,
  371. levels: readonly string[],
  372. thoughtLevel: string,
  373. ) {
  374. if (scope === "body") {
  375. // 主输入框已合并模型和思考入口;Subagent 设置仍使用独立下拉框。
  376. await $(sel(TID_CHAT_MODEL_SELECT_TRIGGER)).click();
  377. const slider = $('[data-testid="composer-thought-slider"]');
  378. await slider.waitForDisplayed({ timeout: 15000 });
  379. expect(JSON.parse((await slider.getAttribute("data-levels")) ?? "[]")).toEqual(levels);
  380. expect(await selectCombinedComposerThoughtLevel(thoughtLevel)).toBe(true);
  381. await expect($(sel(TID_V4_MODEL_CONFIG))).toHaveAttribute("data-thought", thoughtLevel);
  382. return;
  383. }
  384. const trigger = $(scope).$(sel(TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER));
  385. await trigger.waitForClickable({
  386. timeout: 15000,
  387. timeoutMsg: `reasoning effort 控件没有出现: ${scope}`,
  388. });
  389. await trigger.click();
  390. for (const level of levels) {
  391. await $(sel(testId(TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM, level))).waitForDisplayed({
  392. timeout: 15000,
  393. timeoutMsg: `reasoning effort 菜单没有出现 ${level}`,
  394. });
  395. }
  396. const item = $(sel(testId(TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM, thoughtLevel)));
  397. await item.waitForClickable({ timeout: 15000 });
  398. await item.click();
  399. await assertCurrentThoughtLabel(scope, thoughtLevel);
  400. }
  401. async function selectThoughtLevelInScope(scope: string, thoughtLevel: string) {
  402. const trigger = $(scope).$(sel(TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER));
  403. await trigger.waitForClickable({ timeout: 15000 });
  404. await trigger.click();
  405. const item = $(sel(testId(TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM, thoughtLevel)));
  406. await item.waitForClickable({
  407. timeout: 15000,
  408. timeoutMsg: `reasoning effort 菜单没有出现 ${thoughtLevel}`,
  409. });
  410. await item.click();
  411. await assertCurrentThoughtLabel(scope, thoughtLevel);
  412. }
  413. async function assertCurrentThoughtLabel(scope: string, thoughtLevel: string) {
  414. const acceptedLabels: Record<string, string[]> = {
  415. low: ["low", "低"],
  416. medium: ["medium", "中"],
  417. high: ["high", "高"],
  418. xhigh: ["extra high", "极高"],
  419. };
  420. await browser.waitUntil(
  421. async () => {
  422. const label = await $(scope)
  423. .$(sel(TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER))
  424. .getAttribute("aria-label");
  425. return (acceptedLabels[thoughtLevel] ?? [thoughtLevel]).includes(
  426. (label ?? "").trim().toLowerCase(),
  427. );
  428. },
  429. { timeout: 15000, timeoutMsg: `reasoning effort 控件没有显示 ${thoughtLevel}` },
  430. );
  431. }
  432. async function assertNoGenericModelTooltip(scope: string) {
  433. const trigger = $(scope).$(sel(TID_CHAT_MODEL_SELECT_TRIGGER));
  434. await trigger.waitForDisplayed({ timeout: 15000 });
  435. expect((await trigger.getAttribute("aria-label"))?.trim().toLowerCase()).not.toBe("model");
  436. await trigger.moveTo();
  437. await browser.pause(700);
  438. const tooltipTexts = await browser.execute(() =>
  439. Array.from(document.querySelectorAll<HTMLElement>('[role="tooltip"]')).map((element) =>
  440. (element.innerText ?? "").trim(),
  441. ),
  442. );
  443. expect(tooltipTexts).not.toContain("Model");
  444. expect(tooltipTexts).not.toContain("模型");
  445. }
  446. async function waitForAgentsState(
  447. predicate: (state: Record<string, unknown>) => boolean,
  448. timeoutMsg: string,
  449. ) {
  450. await browser.waitUntil(async () => predicate(await readAgentsState()), {
  451. timeout: 15000,
  452. timeoutMsg,
  453. });
  454. }
  455. function readBuiltInSelection(state: Record<string, unknown>, agentName: string) {
  456. const map = state.builtInModelSelectionOverrides;
  457. if (!map || typeof map !== "object" || Array.isArray(map)) return null;
  458. const value = (map as Record<string, unknown>)[agentName];
  459. return value && typeof value === "object" && !Array.isArray(value)
  460. ? (value as Record<string, unknown>)
  461. : null;
  462. }
  463. function readBuiltInModelValue(state: Record<string, unknown>, agentName: string) {
  464. const selection = readBuiltInSelection(state, agentName);
  465. return typeof selection?.providerId === "string" && typeof selection.modelId === "string"
  466. ? encodeCustomModelValue(selection.providerId, selection.modelId)
  467. : null;
  468. }
  469. function readBuiltInReasoningLevel(state: Record<string, unknown>, agentName: string) {
  470. const options = readBuiltInSelection(state, agentName)?.options;
  471. if (!options || typeof options !== "object" || Array.isArray(options)) return null;
  472. const reasoningLevel = (options as Record<string, unknown>).reasoningLevel;
  473. return typeof reasoningLevel === "string" ? reasoningLevel : null;
  474. }
  475. async function waitForCustomMarkdown(predicate: (content: string) => boolean, timeoutMsg: string) {
  476. let latest = "";
  477. try {
  478. await browser.waitUntil(
  479. async () => {
  480. latest = await readFile(CUSTOM_AGENT_PATH, "utf8");
  481. return predicate(latest);
  482. },
  483. { timeout: 15000, timeoutMsg },
  484. );
  485. } catch (error) {
  486. throw new Error(`${timeoutMsg}\n最后读取到的 Markdown:\n${latest}`, { cause: error });
  487. }
  488. return latest;
  489. }
  490. function parseCustomAgentFrontmatter(content: string): Record<string, unknown> {
  491. const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u);
  492. if (!match?.[1]) return {};
  493. const parsed = parseYaml(match[1]) as unknown;
  494. return parsed && typeof parsed === "object" && !Array.isArray(parsed)
  495. ? (parsed as Record<string, unknown>)
  496. : {};
  497. }
  498. async function assertBuiltInLayoutAcrossThemes() {
  499. await assertBuiltInRowsFit();
  500. try {
  501. await setRendererViewport(390, 844);
  502. for (const theme of ["zai-light", "zai-dark"] as const) {
  503. await setSettingsTheme(theme);
  504. await assertBuiltInRowsFit();
  505. }
  506. } finally {
  507. await clearRendererViewport();
  508. }
  509. }
  510. async function assertBuiltInRowsFit() {
  511. const result = await browser.execute(
  512. (rowPrefix, modelPrefix, thoughtTrigger, names) =>
  513. names.map((name) => {
  514. const row = document.querySelector<HTMLElement>(`[data-testid="${rowPrefix}-${name}"]`);
  515. const model = row?.querySelector<HTMLElement>(`[data-testid="${modelPrefix}-${name}"]`);
  516. const thought = row?.querySelector<HTMLElement>(`[data-testid="${thoughtTrigger}"]`);
  517. const modelRect = model?.getBoundingClientRect();
  518. const thoughtRect = thought?.getBoundingClientRect();
  519. return {
  520. hasModel: Boolean(modelRect),
  521. hasThought: Boolean(thoughtRect),
  522. horizontalOverflow: Boolean(row && row.scrollWidth > row.clientWidth + 1),
  523. name,
  524. overlaps: Boolean(
  525. modelRect &&
  526. thoughtRect &&
  527. modelRect.left < thoughtRect.right &&
  528. modelRect.right > thoughtRect.left &&
  529. modelRect.top < thoughtRect.bottom &&
  530. modelRect.bottom > thoughtRect.top,
  531. ),
  532. };
  533. }),
  534. TID_SUBAGENT_ROW,
  535. TID_SUBAGENT_BUILT_IN_MODEL_TRIGGER,
  536. TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER,
  537. ["general-purpose", "Explore"],
  538. );
  539. expect(result).toEqual([
  540. {
  541. hasModel: true,
  542. hasThought: true,
  543. horizontalOverflow: false,
  544. name: "general-purpose",
  545. overlaps: false,
  546. },
  547. {
  548. hasModel: true,
  549. hasThought: true,
  550. horizontalOverflow: false,
  551. name: "Explore",
  552. overlaps: false,
  553. },
  554. ]);
  555. }
  556. async function assertCustomFormLayoutAcrossThemes() {
  557. await assertCustomFormControlsFit();
  558. try {
  559. await setRendererViewport(390, 844);
  560. for (const theme of ["zai-light", "zai-dark"] as const) {
  561. await setSettingsTheme(theme);
  562. await assertCustomFormControlsFit();
  563. }
  564. } finally {
  565. await clearRendererViewport();
  566. }
  567. }
  568. async function assertCustomFormControlsFit() {
  569. const result = await browser.execute(
  570. (formSelector, modelTrigger, thoughtTrigger) => {
  571. const form = document.querySelector<HTMLElement>(formSelector);
  572. const model = form?.querySelector<HTMLElement>(`[data-testid="${modelTrigger}"]`);
  573. const thought = form?.querySelector<HTMLElement>(`[data-testid="${thoughtTrigger}"]`);
  574. const modelRect = model?.getBoundingClientRect();
  575. const thoughtRect = thought?.getBoundingClientRect();
  576. return {
  577. hasModel: Boolean(modelRect),
  578. hasThought: Boolean(thoughtRect),
  579. horizontalOverflow: Boolean(form && form.scrollWidth > form.clientWidth + 1),
  580. overlaps: Boolean(
  581. modelRect &&
  582. thoughtRect &&
  583. modelRect.left < thoughtRect.right &&
  584. modelRect.right > thoughtRect.left &&
  585. modelRect.top < thoughtRect.bottom &&
  586. modelRect.bottom > thoughtRect.top,
  587. ),
  588. };
  589. },
  590. SUBAGENT_FORM_SELECTOR,
  591. TID_CHAT_MODEL_SELECT_TRIGGER,
  592. TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER,
  593. );
  594. expect(result).toEqual({
  595. hasModel: true,
  596. hasThought: true,
  597. horizontalOverflow: false,
  598. overlaps: false,
  599. });
  600. }
  601. async function setSettingsTheme(theme: "zai-light" | "zai-dark") {
  602. const changed = await browser.execute((nextTheme) => {
  603. const actions = (window as typeof window & { __testActions?: Record<string, unknown> })
  604. .__testActions;
  605. const setTheme = actions?.setTheme;
  606. if (typeof setTheme !== "function") return false;
  607. (setTheme as (value: string) => void)(nextTheme);
  608. return true;
  609. }, theme);
  610. expect(changed).toBe(true);
  611. await browser.pause(100);
  612. }
  613. async function setRendererViewport(width: number, height: number) {
  614. await sendRendererEmulationCommand("Emulation.setDeviceMetricsOverride", {
  615. deviceScaleFactor: 1,
  616. height,
  617. mobile: false,
  618. width,
  619. });
  620. await browser.waitUntil(
  621. async () => browser.execute((expectedWidth) => window.innerWidth === expectedWidth, width),
  622. { timeout: 10000, timeoutMsg: `renderer viewport 没有收敛到 ${width}px` },
  623. );
  624. }
  625. async function clearRendererViewport() {
  626. await sendRendererEmulationCommand("Emulation.clearDeviceMetricsOverride");
  627. }
  628. async function sendRendererEmulationCommand(method: string, params: Record<string, unknown> = {}) {
  629. const sent = await browser.electron.execute(
  630. async (electron, command, commandParams) => {
  631. const window = electron.BrowserWindow.getAllWindows().find(
  632. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  633. );
  634. if (!window) return false;
  635. const devtools = window.webContents.debugger;
  636. if (!devtools.isAttached()) devtools.attach("1.3");
  637. await devtools.sendCommand(command, commandParams);
  638. return true;
  639. },
  640. method,
  641. params,
  642. );
  643. expect(sent).toBe(true);
  644. }
  645. async function runSubagentScenario(input: {
  646. childMarker: string;
  647. childReplyToken: string;
  648. childEffort: string;
  649. finalToken: string;
  650. parentMarker: string;
  651. subagentType: string;
  652. }) {
  653. const parentMarker = `${input.parentMarker}_${Date.now()}`;
  654. const prompt =
  655. `${parentMarker}: Use the Agent tool with subagent_type "${input.subagentType}". ` +
  656. `Ask it to reply with exactly "${input.childReplyToken}". ` +
  657. `After the subagent returns, reply with exactly "${input.finalToken}" and no other text.`;
  658. await sendV4Prompt(prompt);
  659. await waitForV4ComposerText("", `${input.subagentType} 首发后输入框没有清空`);
  660. await waitForV4UserMessageContaining(parentMarker);
  661. const mainSessionId = (await getV4PaneSnapshot()).sessionId;
  662. if (!mainSessionId || mainSessionId === "draft") {
  663. throw new Error(`${input.subagentType} 没有真实 parent sessionId`);
  664. }
  665. const parentInitialRecord = await waitForParentInitialRequestCapture(parentMarker);
  666. assertClaudeReasoningRecord(parentInitialRecord, PARENT_EFFORT);
  667. const parentModelIo = await waitForSuccessfulModelIo({
  668. marker: parentMarker,
  669. sessionId: mainSessionId,
  670. });
  671. assertClaudeReasoningBody(parentModelIo.body, PARENT_EFFORT);
  672. expect(parentModelIo.sessionId).toBe(mainSessionId);
  673. const childRecord = await waitForChildSubagentRequestCapture(input.childMarker);
  674. assertClaudeReasoningRecord(childRecord, input.childEffort);
  675. const childModelIo = await waitForSuccessfulModelIo({
  676. marker: `${input.childMarker}:`,
  677. querySource: "subagent",
  678. sessionIdPrefix: "sess_subagent_",
  679. });
  680. assertClaudeReasoningBody(childModelIo.body, input.childEffort);
  681. expect(childModelIo.sessionId).toMatch(/^sess_subagent_/u);
  682. expect(childModelIo.sessionId).not.toBe(mainSessionId);
  683. const parentContinuationRecord = await waitForParentContinuationRequestCapture(
  684. input.childReplyToken,
  685. );
  686. assertClaudeReasoningRecord(parentContinuationRecord, PARENT_EFFORT);
  687. await waitForV4AssistantMessageContaining(input.finalToken);
  688. await waitForV4ConversationState(
  689. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  690. `${input.subagentType} runtime catalog case 完成后没有回到 idle`,
  691. 90000,
  692. );
  693. const agentBlock = await waitForToolCallBlockByToolName("Agent");
  694. expect(agentBlock.status).toBe("completed");
  695. return childRecord;
  696. }
  697. function assertClaudeReasoningRecord(record: E2ENetworkCaptureRecord, effort: string) {
  698. expect(record.path).toContain("/messages");
  699. assertClaudeReasoningBody(asRecord(record.requestJson), effort);
  700. }
  701. function assertClaudeReasoningBody(body: Record<string, unknown>, effort: string) {
  702. expect(body.model).toBe(MODEL_ID);
  703. expect(body.max_tokens).toBe(expectedAnthropicMaxTokens(effort));
  704. expect(readNestedValue(body, ["thinking", "type"])).toBe("enabled");
  705. expect(readNestedValue(body, ["thinking", "budget_tokens"])).toBe(
  706. expectedAnthropicThinkingBudget(effort),
  707. );
  708. expect(readNestedValue(body, ["output_config", "effort"])).toBe(effort);
  709. expect(body.reasoning_effort).toBeUndefined();
  710. }
  711. function expectedAnthropicMaxTokens(effort: string): number {
  712. if (REASONING_BUDGETS[effort] === undefined) {
  713. throw new Error(`未知 Claude reasoning effort: ${effort}`);
  714. }
  715. // Bug 根因:失败日志里的 31,999 属于 thinking.budget_tokens,而不是
  716. // max_tokens。Anthropic 总输出上限仍保持 32K,只收敛内部思考预算来预留可见输出。
  717. return MODEL_OUTPUT_TOKEN_BUDGET;
  718. }
  719. function expectedAnthropicThinkingBudget(effort: string): number {
  720. const catalogBudget = REASONING_BUDGETS[effort];
  721. if (catalogBudget === undefined) {
  722. throw new Error(`未知 Claude reasoning effort: ${effort}`);
  723. }
  724. // Registry 只执行 Option Spec;夹具显式为可见输出保留 1 token,不依赖旧 catalog 补全。
  725. return catalogBudget;
  726. }
  727. async function waitForParentInitialRequestCapture(parentMarker: string) {
  728. return waitForCaptureRecord(
  729. (artifact) =>
  730. artifact?.records.find(
  731. (record) =>
  732. isMessageRequest(record) &&
  733. record.status === "complete" &&
  734. captureContainsText(record.requestJson, parentMarker) &&
  735. readModelFromCapture(record.requestJson) === MODEL_ID &&
  736. !captureContainsText(record.requestJson, "Generate a concise title") &&
  737. !latestUserMessageHasToolResult(record.requestJson),
  738. ) ?? null,
  739. `没有捕获到 parent 首轮请求: ${parentMarker}`,
  740. );
  741. }
  742. async function waitForChildSubagentRequestCapture(childMarker: string) {
  743. return waitForCaptureRecord(
  744. (artifact) =>
  745. artifact?.records.find(
  746. (record) =>
  747. isMessageRequest(record) &&
  748. record.status === "complete" &&
  749. captureContainsText(record.requestJson, `${childMarker}:`) &&
  750. readModelFromCapture(record.requestJson) === MODEL_ID,
  751. ) ?? null,
  752. `没有捕获到 child 请求: ${childMarker}`,
  753. );
  754. }
  755. async function waitForParentContinuationRequestCapture(childReplyToken: string) {
  756. return waitForCaptureRecord(
  757. (artifact) =>
  758. artifact?.records.findLast(
  759. (record) =>
  760. isMessageRequest(record) &&
  761. record.status === "complete" &&
  762. latestUserToolResultContainsText(record.requestJson, childReplyToken) &&
  763. readModelFromCapture(record.requestJson) === MODEL_ID,
  764. ) ?? null,
  765. `没有捕获到 parent continuation 请求: ${childReplyToken}`,
  766. );
  767. }
  768. async function waitForCaptureRecord(
  769. findRecord: (artifact: E2ENetworkCaptureArtifact | null) => E2ENetworkCaptureRecord | null,
  770. timeoutMsg: string,
  771. ): Promise<E2ENetworkCaptureRecord> {
  772. let matched: E2ENetworkCaptureRecord | null = null;
  773. await browser.waitUntil(
  774. async () => {
  775. matched = findRecord(await readCaptureArtifact());
  776. return Boolean(matched);
  777. },
  778. { timeout: 45000, timeoutMsg },
  779. );
  780. if (!matched) throw new Error(`${timeoutMsg},等待完成后记录仍为空`);
  781. return matched as E2ENetworkCaptureRecord;
  782. }
  783. async function readCaptureArtifact(): Promise<E2ENetworkCaptureArtifact | null> {
  784. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH?.trim();
  785. if (!capturePath) return null;
  786. try {
  787. return JSON.parse(await readFile(capturePath, "utf8")) as E2ENetworkCaptureArtifact;
  788. } catch (error) {
  789. if (error instanceof Error && "code" in error && error.code === "ENOENT") return null;
  790. throw error;
  791. }
  792. }
  793. async function waitForSuccessfulModelIo(input: {
  794. marker: string;
  795. querySource?: "main_turn" | "subagent";
  796. sessionId?: string;
  797. sessionIdPrefix?: string;
  798. }): Promise<ModelIoMatch> {
  799. let matched: ModelIoMatch | null = null;
  800. await browser.waitUntil(
  801. async () => {
  802. for (const { line, record } of await readModelIoRecords()) {
  803. if (!line.includes(input.marker)) continue;
  804. if (
  805. record.error !== undefined ||
  806. record.response === undefined ||
  807. record.querySource !== (input.querySource ?? "main_turn") ||
  808. (input.sessionId !== undefined && record.sessionId !== input.sessionId) ||
  809. (input.sessionIdPrefix !== undefined &&
  810. (typeof record.sessionId !== "string" ||
  811. !record.sessionId.startsWith(input.sessionIdPrefix)))
  812. ) {
  813. continue;
  814. }
  815. const body = parseJsonObject(record.request?.body);
  816. if (!body || body.bodySource === "ai_sdk_options" || typeof record.sessionId !== "string") {
  817. continue;
  818. }
  819. matched = { body, sessionId: record.sessionId };
  820. return true;
  821. }
  822. return false;
  823. },
  824. { timeout: 45000, timeoutMsg: `没有找到成功的 model-io: ${input.marker}` },
  825. );
  826. if (!matched) throw new Error(`model-io 等待完成后仍为空: ${input.marker}`);
  827. return matched;
  828. }
  829. async function readModelIoRecords(): Promise<Array<{ line: string; record: ModelIoRecord }>> {
  830. const debugDir = join(resolveE2EStorageRoot(), "cli", "debug");
  831. const files = await readdir(debugDir).catch(() => []);
  832. const records: Array<{ line: string; record: ModelIoRecord }> = [];
  833. for (const file of files.filter(
  834. (name) => name.startsWith("model-io-") && name.endsWith(".jsonl"),
  835. )) {
  836. const content = await readFile(join(debugDir, file), "utf8").catch(() => "");
  837. for (const line of content.split("\n")) {
  838. const record = parseJsonObject(line) as ModelIoRecord | null;
  839. if (record) records.push({ line, record });
  840. }
  841. }
  842. return records;
  843. }
  844. function parseJsonObject(value: unknown): Record<string, unknown> | null {
  845. if (typeof value === "string") {
  846. try {
  847. return parseJsonObject(JSON.parse(value));
  848. } catch {
  849. return null;
  850. }
  851. }
  852. return value && typeof value === "object" && !Array.isArray(value)
  853. ? (value as Record<string, unknown>)
  854. : null;
  855. }
  856. function asRecord(value: unknown): Record<string, unknown> {
  857. const record = parseJsonObject(value);
  858. if (!record) throw new Error("provider capture requestJson 不是对象");
  859. return record;
  860. }
  861. function isMessageRequest(record: E2ENetworkCaptureRecord) {
  862. return record.method === "POST" && record.path.includes("/messages");
  863. }
  864. function readModelFromCapture(value: unknown) {
  865. const model = parseJsonObject(value)?.model;
  866. return typeof model === "string" ? model : null;
  867. }
  868. function latestUserMessageHasToolResult(requestJson: unknown) {
  869. const messages = parseJsonObject(requestJson)?.messages;
  870. if (!Array.isArray(messages)) return false;
  871. for (let index = messages.length - 1; index >= 0; index -= 1) {
  872. const message = parseJsonObject(messages[index]);
  873. if (message?.role !== "user") continue;
  874. return (
  875. Array.isArray(message.content) &&
  876. message.content.some((part) => parseJsonObject(part)?.type === "tool_result")
  877. );
  878. }
  879. return false;
  880. }
  881. function latestUserToolResultContainsText(requestJson: unknown, expectedText: string) {
  882. const messages = parseJsonObject(requestJson)?.messages;
  883. if (!Array.isArray(messages)) return false;
  884. for (let index = messages.length - 1; index >= 0; index -= 1) {
  885. const message = parseJsonObject(messages[index]);
  886. if (message?.role !== "user") continue;
  887. return (
  888. Array.isArray(message.content) &&
  889. message.content.some(
  890. (part) =>
  891. parseJsonObject(part)?.type === "tool_result" && captureContainsText(part, expectedText),
  892. )
  893. );
  894. }
  895. return false;
  896. }
  897. function readNestedValue(value: unknown, path: string[]) {
  898. let current: unknown = value;
  899. for (const key of path) {
  900. const record = parseJsonObject(current);
  901. if (!record) return undefined;
  902. current = record[key];
  903. }
  904. return current;
  905. }
  906. function readToolNamesFromCapture(value: unknown): string[] {
  907. const tools = parseJsonObject(value)?.tools;
  908. if (!Array.isArray(tools)) return [];
  909. return tools.flatMap((tool) => {
  910. const name = parseJsonObject(tool)?.name;
  911. return typeof name === "string" ? [name] : [];
  912. });
  913. }
  914. function captureContainsText(value: unknown, expected: string): boolean {
  915. if (typeof value === "string") return value.includes(expected);
  916. if (Array.isArray(value)) return value.some((item) => captureContainsText(item, expected));
  917. const record = parseJsonObject(value);
  918. return record
  919. ? Object.values(record).some((child) => captureContainsText(child, expected))
  920. : false;
  921. }