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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. import { readdir, readFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { parse as parseYaml } from "yaml";
  4. import {
  5. TID_CHAT_MODEL_SELECT_GROUP,
  6. TID_CHAT_MODEL_SELECT_ITEM,
  7. TID_CHAT_MODEL_SELECT_TRIGGER,
  8. TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM,
  9. TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER,
  10. TID_SETTINGS_BACK_BUTTON,
  11. TID_SETTINGS_PAGE,
  12. TID_SETTINGS_SECTION_NAV,
  13. TID_SUBAGENT_BUILT_IN_MODEL_TRIGGER,
  14. TID_SUBAGENT_ROW,
  15. TID_TASK_SETTINGS_BUTTON,
  16. decodeCustomModelValue,
  17. encodeCustomModelValue,
  18. testId,
  19. } from "@zcode/shared";
  20. import {
  21. DEFAULT_WORKSPACE,
  22. clearAppData,
  23. clickTestIdByDom,
  24. readAgentsState,
  25. readModelProviders,
  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: 32000,
  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: Claude runtime 档位经 Settings 落盘并在三个 child 请求中生效", async function () {
  104. this.timeout(360000);
  105. await prepareV4ConversationE2E({ skipProvider: true });
  106. await assertAppMetadataOmitsReasoning();
  107. await selectUpstreamProviderModelById(MODEL_ID, {
  108. includePlainModelFallback: false,
  109. providerId: PROVIDER_ID,
  110. providerName: PROVIDER_NAME,
  111. });
  112. await assertThoughtOptionsAndSelectInScope("body", THOUGHT_LEVELS, PARENT_EFFORT);
  113. await configureSubagentReasoningOverrides();
  114. await seedPersistedModelSelection({
  115. modelId: MODEL_ID,
  116. providerId: PROVIDER_ID,
  117. reasoningLevel: PARENT_EFFORT,
  118. });
  119. await restartIntoWorkspacePreservingProfile();
  120. await prepareV4ConversationE2E({ skipProvider: true });
  121. await runSubagentScenario({
  122. childMarker: GENERAL_CHILD_MARKER,
  123. childReplyToken: GENERAL_CHILD_REPLY_TOKEN,
  124. childEffort: GENERAL_EFFORT,
  125. finalToken: GENERAL_FINAL_TOKEN,
  126. parentMarker: GENERAL_PARENT_MARKER,
  127. subagentType: "general-purpose",
  128. });
  129. const exploreChildRecord = await runSubagentScenario({
  130. childMarker: EXPLORE_CHILD_MARKER,
  131. childReplyToken: EXPLORE_CHILD_REPLY_TOKEN,
  132. childEffort: EXPLORE_EFFORT,
  133. finalToken: EXPLORE_FINAL_TOKEN,
  134. parentMarker: EXPLORE_PARENT_MARKER,
  135. subagentType: "Explore",
  136. });
  137. expect(readToolNamesFromCapture(exploreChildRecord.requestJson)).toEqual([
  138. "Bash",
  139. "Read",
  140. "TodoWrite",
  141. "WebFetch",
  142. "RespondToCoordinator",
  143. ]);
  144. await runSubagentScenario({
  145. childMarker: CUSTOM_CHILD_MARKER,
  146. childReplyToken: CUSTOM_CHILD_REPLY_TOKEN,
  147. childEffort: CUSTOM_EFFORT,
  148. finalToken: CUSTOM_FINAL_TOKEN,
  149. parentMarker: CUSTOM_PARENT_MARKER,
  150. subagentType: CUSTOM_AGENT_NAME,
  151. });
  152. });
  153. });
  154. async function assertAppMetadataOmitsReasoning() {
  155. const provider = (await readModelProviders()).find((item) => item.id === PROVIDER_ID);
  156. const model = provider?.models.find((item) =>
  157. typeof item === "string" ? item === MODEL_ID : item.id === MODEL_ID,
  158. );
  159. expect(provider).toBeDefined();
  160. expect(typeof model === "string" ? undefined : model?.reasoning).toBeUndefined();
  161. }
  162. async function configureSubagentReasoningOverrides() {
  163. expect(await readAgentsState()).toMatchObject({
  164. builtInModelSelectionOverrides: {
  165. Explore: {
  166. providerId: PROVIDER_ID,
  167. modelId: MODEL_ID,
  168. options: { reasoningLevel: INVALID_EFFORT },
  169. },
  170. "general-purpose": {
  171. providerId: PROVIDER_ID,
  172. modelId: MODEL_ID,
  173. options: { reasoningLevel: GENERAL_EFFORT },
  174. },
  175. },
  176. });
  177. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  178. timeout: 15000,
  179. timeoutMsg: "没有找到设置入口按钮",
  180. });
  181. await waitForTestIdByDom(TID_SETTINGS_PAGE, {
  182. timeout: 15000,
  183. timeoutMsg: "设置页没有渲染",
  184. });
  185. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "subagents"), {
  186. timeout: 15000,
  187. timeoutMsg: "设置页没有出现 subagents 分区入口",
  188. });
  189. const generalScope = sel(testId(TID_SUBAGENT_ROW, "general-purpose"));
  190. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, "general-purpose"));
  191. await assertThoughtOptionsAndSelectInScope(generalScope, THOUGHT_LEVELS, GENERAL_EFFORT);
  192. await assertNoGenericModelTooltip(generalScope);
  193. const exploreScope = sel(testId(TID_SUBAGENT_ROW, "Explore"));
  194. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, "Explore"));
  195. expect(await $(exploreScope).getText()).toMatch(
  196. /Select a reasoning effort supported by this model|请选择当前模型支持的推理档位/u,
  197. );
  198. await assertCurrentThoughtLabel(exploreScope, INVALID_EFFORT);
  199. await assertThoughtOptionsAndSelectInScope(exploreScope, THOUGHT_LEVELS, EXPLORE_EFFORT);
  200. await assertNoGenericModelTooltip(exploreScope);
  201. await waitForAgentsState(
  202. (state) => readBuiltInReasoningLevel(state, "Explore") === EXPLORE_EFFORT,
  203. "Explore xhigh effort 没有写入 agents-state.json",
  204. );
  205. await selectModelInScope(generalScope, UPSTREAM_MODEL_VALUE);
  206. await waitForAgentsState(
  207. (state) =>
  208. readBuiltInModelValue(state, "general-purpose") === UPSTREAM_MODEL_VALUE &&
  209. readBuiltInReasoningLevel(state, "general-purpose") === null,
  210. "general-purpose 切换到 上游 后没有清除旧 effort",
  211. );
  212. await selectModelInScope(generalScope, MODEL_VALUE);
  213. await waitForAgentsState(
  214. (state) =>
  215. readBuiltInModelValue(state, "general-purpose") === MODEL_VALUE &&
  216. readBuiltInReasoningLevel(state, "general-purpose") === null,
  217. "general-purpose 切回 Claude 后不应恢复旧 effort",
  218. );
  219. await selectThoughtLevelInScope(generalScope, GENERAL_EFFORT);
  220. await waitForAgentsState(
  221. (state) => readBuiltInReasoningLevel(state, "general-purpose") === GENERAL_EFFORT,
  222. "general-purpose high effort 没有写入 agents-state.json",
  223. );
  224. await configureCustomSubagentReasoningOverride();
  225. await assertBuiltInLayoutAcrossThemes();
  226. expect(await readAgentsState()).toMatchObject({
  227. builtInModelSelectionOverrides: {
  228. Explore: {
  229. providerId: PROVIDER_ID,
  230. modelId: MODEL_ID,
  231. options: { reasoningLevel: EXPLORE_EFFORT },
  232. },
  233. "general-purpose": {
  234. providerId: PROVIDER_ID,
  235. modelId: MODEL_ID,
  236. options: { reasoningLevel: GENERAL_EFFORT },
  237. },
  238. },
  239. });
  240. expect(parseCustomAgentFrontmatter(await readFile(CUSTOM_AGENT_PATH, "utf8"))).toMatchObject({
  241. model: MODEL_VALUE,
  242. thoughtLevel: CUSTOM_EFFORT,
  243. });
  244. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  245. timeout: 15000,
  246. timeoutMsg: "设置页返回按钮没有出现",
  247. });
  248. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 30000);
  249. }
  250. async function configureCustomSubagentReasoningOverride() {
  251. const initialMarkdown = await readFile(CUSTOM_AGENT_PATH, "utf8");
  252. expect(initialMarkdown).toContain(`model: ${MODEL_VALUE}`);
  253. expect(initialMarkdown).toContain(`thoughtLevel: ${INVALID_EFFORT}`);
  254. await openCustomAgentForm();
  255. await assertCurrentThoughtLabel(SUBAGENT_FORM_SELECTOR, INVALID_EFFORT);
  256. await assertNoGenericModelTooltip(SUBAGENT_FORM_SELECTOR);
  257. await assertCustomFormLayoutAcrossThemes();
  258. const form = $(SUBAGENT_FORM_SELECTOR);
  259. expect(await form.getText()).toMatch(
  260. /Select a reasoning effort supported by this model|请选择当前模型支持的推理档位/u,
  261. );
  262. // 非法历史档位会禁用保存按钮;强行点击只会触发 WebDriver 拦截,不能证明产品拒绝保存。
  263. expect(await form.$('button[type="submit"]').isEnabled()).toBe(false);
  264. expect(await form.isDisplayed()).toBe(true);
  265. expect(await readFile(CUSTOM_AGENT_PATH, "utf8")).toBe(initialMarkdown);
  266. await assertThoughtOptionsAndSelectInScope(SUBAGENT_FORM_SELECTOR, THOUGHT_LEVELS, CUSTOM_EFFORT);
  267. await saveCustomAgentForm();
  268. await waitForCustomMarkdown(
  269. (content) => parseCustomAgentFrontmatter(content).thoughtLevel === CUSTOM_EFFORT,
  270. "custom 合法 medium effort 没有写入 Markdown",
  271. );
  272. await openCustomAgentForm();
  273. await selectModelInScope(SUBAGENT_FORM_SELECTOR, UPSTREAM_MODEL_VALUE);
  274. await selectModelInScope(SUBAGENT_FORM_SELECTOR, MODEL_VALUE);
  275. await saveCustomAgentForm();
  276. const clearedMarkdown = await waitForCustomMarkdown((content) => {
  277. const frontmatter = parseCustomAgentFrontmatter(content);
  278. return frontmatter.model === MODEL_VALUE && frontmatter.thoughtLevel === undefined;
  279. }, "custom 切换模型后没有删除旧 effort");
  280. expect(clearedMarkdown).not.toMatch(/^thoughtLevel:/mu);
  281. await openCustomAgentForm();
  282. await selectThoughtLevelInScope(SUBAGENT_FORM_SELECTOR, GENERAL_EFFORT);
  283. await selectThoughtLevelInScope(SUBAGENT_FORM_SELECTOR, CUSTOM_EFFORT);
  284. await saveCustomAgentForm();
  285. await waitForCustomMarkdown((content) => {
  286. const frontmatter = parseCustomAgentFrontmatter(content);
  287. return frontmatter.model === MODEL_VALUE && frontmatter.thoughtLevel === CUSTOM_EFFORT;
  288. }, "custom 最终 Claude model + medium effort 没有写入 Markdown");
  289. }
  290. async function openCustomAgentForm() {
  291. const rowTestId = testId(TID_SUBAGENT_ROW, CUSTOM_AGENT_NAME);
  292. await waitForTestIdByDom(rowTestId);
  293. await browser.waitUntil(
  294. async () =>
  295. browser.execute((currentRowTestId) => {
  296. const row = document.querySelector<HTMLElement>(`[data-testid="${currentRowTestId}"]`);
  297. if (!row) return false;
  298. // 编辑入口由整行承载;行内带 title 的按钮是删除,不能按 button[title] 定位。
  299. row.click();
  300. return true;
  301. }, rowTestId),
  302. { timeout: 15000, timeoutMsg: "custom subagent 行不可编辑" },
  303. );
  304. await $(SUBAGENT_FORM_SELECTOR).waitForDisplayed({
  305. timeout: 15000,
  306. timeoutMsg: "custom subagent 编辑表单没有打开",
  307. });
  308. }
  309. async function saveCustomAgentForm() {
  310. await $(SUBAGENT_FORM_SELECTOR).$('button[type="submit"]').click();
  311. await browser.waitUntil(async () => !(await $(SUBAGENT_FORM_SELECTOR).isExisting()), {
  312. timeout: 15000,
  313. timeoutMsg: "custom subagent 保存后表单没有关闭",
  314. });
  315. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, CUSTOM_AGENT_NAME));
  316. }
  317. async function selectModelInScope(scope: string, model: string) {
  318. const decodedModel = decodeCustomModelValue(model);
  319. if (!decodedModel) throw new Error(`E2E 仅支持选择 custom provider 模型: ${model}`);
  320. const itemTestId = testId(TID_CHAT_MODEL_SELECT_ITEM, model);
  321. const groupTestId = testId(
  322. TID_CHAT_MODEL_SELECT_GROUP,
  323. `registry-provider:${decodedModel.providerId}`,
  324. );
  325. const trigger = $(scope).$(sel(TID_CHAT_MODEL_SELECT_TRIGGER));
  326. await trigger.waitForClickable({ timeout: 15000 });
  327. await trigger.click();
  328. await browser.waitUntil(
  329. () =>
  330. browser.execute(
  331. (currentItemTestId, currentGroupTestId) =>
  332. Boolean(
  333. document.querySelector(`[data-testid="${currentItemTestId}"]`) ||
  334. document.querySelector(`[data-testid="${currentGroupTestId}"]`),
  335. ),
  336. itemTestId,
  337. groupTestId,
  338. ),
  339. { timeout: 15000, timeoutMsg: `模型菜单没有出现 ${model}` },
  340. );
  341. const itemVisible = await browser.execute(
  342. (currentItemTestId) => Boolean(document.querySelector(`[data-testid="${currentItemTestId}"]`)),
  343. itemTestId,
  344. );
  345. if (!itemVisible) {
  346. await browser.execute((currentGroupTestId) => {
  347. const group = document.querySelector<HTMLElement>(`[data-testid="${currentGroupTestId}"]`);
  348. if (!group) return;
  349. group.focus();
  350. for (const eventName of ["pointerenter", "mouseenter", "mousemove"] as const) {
  351. group.dispatchEvent(
  352. new MouseEvent(eventName, { bubbles: true, cancelable: true, view: window }),
  353. );
  354. }
  355. group.click();
  356. }, groupTestId);
  357. }
  358. await browser.waitUntil(
  359. () =>
  360. browser.execute(
  361. (currentItemTestId) =>
  362. Boolean(document.querySelector(`[data-testid="${currentItemTestId}"]`)),
  363. itemTestId,
  364. ),
  365. { timeout: 15000, timeoutMsg: `模型菜单没有出现 ${model}` },
  366. );
  367. await browser.execute((currentItemTestId) => {
  368. document.querySelector<HTMLElement>(`[data-testid="${currentItemTestId}"]`)?.click();
  369. }, itemTestId);
  370. await browser.waitUntil(
  371. async () =>
  372. (await $(scope)
  373. .$(sel(TID_CHAT_MODEL_SELECT_TRIGGER))
  374. .getAttribute("data-model-current-value")) === model,
  375. { timeout: 15000, timeoutMsg: `模型控件没有切换到 ${model}` },
  376. );
  377. }
  378. async function assertThoughtOptionsAndSelectInScope(
  379. scope: string,
  380. levels: readonly string[],
  381. thoughtLevel: string,
  382. ) {
  383. const trigger = $(scope).$(sel(TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER));
  384. await trigger.waitForClickable({
  385. timeout: 15000,
  386. timeoutMsg: `reasoning effort 控件没有出现: ${scope}`,
  387. });
  388. await trigger.click();
  389. for (const level of levels) {
  390. await $(sel(testId(TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM, level))).waitForDisplayed({
  391. timeout: 15000,
  392. timeoutMsg: `reasoning effort 菜单没有出现 ${level}`,
  393. });
  394. }
  395. const item = $(sel(testId(TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM, thoughtLevel)));
  396. await item.waitForClickable({ timeout: 15000 });
  397. await item.click();
  398. await assertCurrentThoughtLabel(scope, thoughtLevel);
  399. }
  400. async function selectThoughtLevelInScope(scope: string, thoughtLevel: string) {
  401. const trigger = $(scope).$(sel(TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER));
  402. await trigger.waitForClickable({ timeout: 15000 });
  403. await trigger.click();
  404. const item = $(sel(testId(TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM, thoughtLevel)));
  405. await item.waitForClickable({
  406. timeout: 15000,
  407. timeoutMsg: `reasoning effort 菜单没有出现 ${thoughtLevel}`,
  408. });
  409. await item.click();
  410. await assertCurrentThoughtLabel(scope, thoughtLevel);
  411. }
  412. async function assertCurrentThoughtLabel(scope: string, thoughtLevel: string) {
  413. const acceptedLabels: Record<string, string[]> = {
  414. low: ["low", "低"],
  415. medium: ["medium", "中"],
  416. high: ["high", "高"],
  417. xhigh: ["extra high", "极高"],
  418. };
  419. await browser.waitUntil(
  420. async () => {
  421. const label = await $(scope)
  422. .$(sel(TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER))
  423. .getAttribute("aria-label");
  424. return (acceptedLabels[thoughtLevel] ?? [thoughtLevel]).includes(
  425. (label ?? "").trim().toLowerCase(),
  426. );
  427. },
  428. { timeout: 15000, timeoutMsg: `reasoning effort 控件没有显示 ${thoughtLevel}` },
  429. );
  430. }
  431. async function assertNoGenericModelTooltip(scope: string) {
  432. const trigger = $(scope).$(sel(TID_CHAT_MODEL_SELECT_TRIGGER));
  433. await trigger.waitForDisplayed({ timeout: 15000 });
  434. expect((await trigger.getAttribute("aria-label"))?.trim().toLowerCase()).not.toBe("model");
  435. await trigger.moveTo();
  436. await browser.pause(700);
  437. const tooltipTexts = await browser.execute(() =>
  438. Array.from(document.querySelectorAll<HTMLElement>('[role="tooltip"]')).map((element) =>
  439. (element.innerText ?? "").trim(),
  440. ),
  441. );
  442. expect(tooltipTexts).not.toContain("Model");
  443. expect(tooltipTexts).not.toContain("模型");
  444. }
  445. async function waitForAgentsState(
  446. predicate: (state: Record<string, unknown>) => boolean,
  447. timeoutMsg: string,
  448. ) {
  449. await browser.waitUntil(async () => predicate(await readAgentsState()), {
  450. timeout: 15000,
  451. timeoutMsg,
  452. });
  453. }
  454. function readBuiltInSelection(state: Record<string, unknown>, agentName: string) {
  455. const map = state.builtInModelSelectionOverrides;
  456. if (!map || typeof map !== "object" || Array.isArray(map)) return null;
  457. const value = (map as Record<string, unknown>)[agentName];
  458. return value && typeof value === "object" && !Array.isArray(value)
  459. ? (value as Record<string, unknown>)
  460. : null;
  461. }
  462. function readBuiltInModelValue(state: Record<string, unknown>, agentName: string) {
  463. const selection = readBuiltInSelection(state, agentName);
  464. return typeof selection?.providerId === "string" && typeof selection.modelId === "string"
  465. ? encodeCustomModelValue(selection.providerId, selection.modelId)
  466. : null;
  467. }
  468. function readBuiltInReasoningLevel(state: Record<string, unknown>, agentName: string) {
  469. const options = readBuiltInSelection(state, agentName)?.options;
  470. if (!options || typeof options !== "object" || Array.isArray(options)) return null;
  471. const reasoningLevel = (options as Record<string, unknown>).reasoningLevel;
  472. return typeof reasoningLevel === "string" ? reasoningLevel : null;
  473. }
  474. async function waitForCustomMarkdown(predicate: (content: string) => boolean, timeoutMsg: string) {
  475. let latest = "";
  476. try {
  477. await browser.waitUntil(
  478. async () => {
  479. latest = await readFile(CUSTOM_AGENT_PATH, "utf8");
  480. return predicate(latest);
  481. },
  482. { timeout: 15000, timeoutMsg },
  483. );
  484. } catch (error) {
  485. throw new Error(`${timeoutMsg}\n最后读取到的 Markdown:\n${latest}`, { cause: error });
  486. }
  487. return latest;
  488. }
  489. function parseCustomAgentFrontmatter(content: string): Record<string, unknown> {
  490. const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u);
  491. if (!match?.[1]) return {};
  492. const parsed = parseYaml(match[1]) as unknown;
  493. return parsed && typeof parsed === "object" && !Array.isArray(parsed)
  494. ? (parsed as Record<string, unknown>)
  495. : {};
  496. }
  497. async function assertBuiltInLayoutAcrossThemes() {
  498. await assertBuiltInRowsFit();
  499. try {
  500. await setRendererViewport(390, 844);
  501. for (const theme of ["zai-light", "zai-dark"] as const) {
  502. await setSettingsTheme(theme);
  503. await assertBuiltInRowsFit();
  504. }
  505. } finally {
  506. await clearRendererViewport();
  507. }
  508. }
  509. async function assertBuiltInRowsFit() {
  510. const result = await browser.execute(
  511. (rowPrefix, modelPrefix, thoughtTrigger, names) =>
  512. names.map((name) => {
  513. const row = document.querySelector<HTMLElement>(`[data-testid="${rowPrefix}-${name}"]`);
  514. const model = row?.querySelector<HTMLElement>(`[data-testid="${modelPrefix}-${name}"]`);
  515. const thought = row?.querySelector<HTMLElement>(`[data-testid="${thoughtTrigger}"]`);
  516. const modelRect = model?.getBoundingClientRect();
  517. const thoughtRect = thought?.getBoundingClientRect();
  518. return {
  519. hasModel: Boolean(modelRect),
  520. hasThought: Boolean(thoughtRect),
  521. horizontalOverflow: Boolean(row && row.scrollWidth > row.clientWidth + 1),
  522. name,
  523. overlaps: Boolean(
  524. modelRect &&
  525. thoughtRect &&
  526. modelRect.left < thoughtRect.right &&
  527. modelRect.right > thoughtRect.left &&
  528. modelRect.top < thoughtRect.bottom &&
  529. modelRect.bottom > thoughtRect.top,
  530. ),
  531. };
  532. }),
  533. TID_SUBAGENT_ROW,
  534. TID_SUBAGENT_BUILT_IN_MODEL_TRIGGER,
  535. TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER,
  536. ["general-purpose", "Explore"],
  537. );
  538. expect(result).toEqual([
  539. {
  540. hasModel: true,
  541. hasThought: true,
  542. horizontalOverflow: false,
  543. name: "general-purpose",
  544. overlaps: false,
  545. },
  546. {
  547. hasModel: true,
  548. hasThought: true,
  549. horizontalOverflow: false,
  550. name: "Explore",
  551. overlaps: false,
  552. },
  553. ]);
  554. }
  555. async function assertCustomFormLayoutAcrossThemes() {
  556. await assertCustomFormControlsFit();
  557. try {
  558. await setRendererViewport(390, 844);
  559. for (const theme of ["zai-light", "zai-dark"] as const) {
  560. await setSettingsTheme(theme);
  561. await assertCustomFormControlsFit();
  562. }
  563. } finally {
  564. await clearRendererViewport();
  565. }
  566. }
  567. async function assertCustomFormControlsFit() {
  568. const result = await browser.execute(
  569. (formSelector, modelTrigger, thoughtTrigger) => {
  570. const form = document.querySelector<HTMLElement>(formSelector);
  571. const model = form?.querySelector<HTMLElement>(`[data-testid="${modelTrigger}"]`);
  572. const thought = form?.querySelector<HTMLElement>(`[data-testid="${thoughtTrigger}"]`);
  573. const modelRect = model?.getBoundingClientRect();
  574. const thoughtRect = thought?.getBoundingClientRect();
  575. return {
  576. hasModel: Boolean(modelRect),
  577. hasThought: Boolean(thoughtRect),
  578. horizontalOverflow: Boolean(form && form.scrollWidth > form.clientWidth + 1),
  579. overlaps: Boolean(
  580. modelRect &&
  581. thoughtRect &&
  582. modelRect.left < thoughtRect.right &&
  583. modelRect.right > thoughtRect.left &&
  584. modelRect.top < thoughtRect.bottom &&
  585. modelRect.bottom > thoughtRect.top,
  586. ),
  587. };
  588. },
  589. SUBAGENT_FORM_SELECTOR,
  590. TID_CHAT_MODEL_SELECT_TRIGGER,
  591. TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER,
  592. );
  593. expect(result).toEqual({
  594. hasModel: true,
  595. hasThought: true,
  596. horizontalOverflow: false,
  597. overlaps: false,
  598. });
  599. }
  600. async function setSettingsTheme(theme: "zai-light" | "zai-dark") {
  601. const changed = await browser.execute((nextTheme) => {
  602. const actions = (window as typeof window & { __testActions?: Record<string, unknown> })
  603. .__testActions;
  604. const setTheme = actions?.setTheme;
  605. if (typeof setTheme !== "function") return false;
  606. (setTheme as (value: string) => void)(nextTheme);
  607. return true;
  608. }, theme);
  609. expect(changed).toBe(true);
  610. await browser.pause(100);
  611. }
  612. async function setRendererViewport(width: number, height: number) {
  613. await sendRendererEmulationCommand("Emulation.setDeviceMetricsOverride", {
  614. deviceScaleFactor: 1,
  615. height,
  616. mobile: false,
  617. width,
  618. });
  619. await browser.waitUntil(
  620. async () => browser.execute((expectedWidth) => window.innerWidth === expectedWidth, width),
  621. { timeout: 10000, timeoutMsg: `renderer viewport 没有收敛到 ${width}px` },
  622. );
  623. }
  624. async function clearRendererViewport() {
  625. await sendRendererEmulationCommand("Emulation.clearDeviceMetricsOverride");
  626. }
  627. async function sendRendererEmulationCommand(method: string, params: Record<string, unknown> = {}) {
  628. const sent = await browser.electron.execute(
  629. async (electron, command, commandParams) => {
  630. const window = electron.BrowserWindow.getAllWindows().find(
  631. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  632. );
  633. if (!window) return false;
  634. const devtools = window.webContents.debugger;
  635. if (!devtools.isAttached()) devtools.attach("1.3");
  636. await devtools.sendCommand(command, commandParams);
  637. return true;
  638. },
  639. method,
  640. params,
  641. );
  642. expect(sent).toBe(true);
  643. }
  644. async function runSubagentScenario(input: {
  645. childMarker: string;
  646. childReplyToken: string;
  647. childEffort: string;
  648. finalToken: string;
  649. parentMarker: string;
  650. subagentType: string;
  651. }) {
  652. const parentMarker = `${input.parentMarker}_${Date.now()}`;
  653. const prompt =
  654. `${parentMarker}: Use the Agent tool with subagent_type "${input.subagentType}". ` +
  655. `Ask it to reply with exactly "${input.childReplyToken}". ` +
  656. `After the subagent returns, reply with exactly "${input.finalToken}" and no other text.`;
  657. await sendV4Prompt(prompt);
  658. await waitForV4ComposerText("", `${input.subagentType} 首发后输入框没有清空`);
  659. await waitForV4UserMessageContaining(parentMarker);
  660. const mainSessionId = (await getV4PaneSnapshot()).sessionId;
  661. if (!mainSessionId || mainSessionId === "draft") {
  662. throw new Error(`${input.subagentType} 没有真实 parent sessionId`);
  663. }
  664. const parentInitialRecord = await waitForParentInitialRequestCapture(parentMarker);
  665. assertClaudeReasoningRecord(parentInitialRecord, PARENT_EFFORT);
  666. const parentModelIo = await waitForSuccessfulModelIo({
  667. marker: parentMarker,
  668. sessionId: mainSessionId,
  669. });
  670. assertClaudeReasoningBody(parentModelIo.body, PARENT_EFFORT);
  671. expect(parentModelIo.sessionId).toBe(mainSessionId);
  672. const childRecord = await waitForChildSubagentRequestCapture(input.childMarker);
  673. assertClaudeReasoningRecord(childRecord, input.childEffort);
  674. const childModelIo = await waitForSuccessfulModelIo({
  675. marker: `${input.childMarker}:`,
  676. querySource: "subagent",
  677. sessionIdPrefix: "sess_subagent_",
  678. });
  679. assertClaudeReasoningBody(childModelIo.body, input.childEffort);
  680. expect(childModelIo.sessionId).toMatch(/^sess_subagent_/u);
  681. expect(childModelIo.sessionId).not.toBe(mainSessionId);
  682. const parentContinuationRecord = await waitForParentContinuationRequestCapture(
  683. input.childReplyToken,
  684. );
  685. assertClaudeReasoningRecord(parentContinuationRecord, PARENT_EFFORT);
  686. await waitForV4AssistantMessageContaining(input.finalToken);
  687. await waitForV4ConversationState(
  688. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  689. `${input.subagentType} runtime catalog case 完成后没有回到 idle`,
  690. 90000,
  691. );
  692. const agentBlock = await waitForToolCallBlockByToolName("Agent");
  693. expect(agentBlock.status).toBe("completed");
  694. return childRecord;
  695. }
  696. function assertClaudeReasoningRecord(record: E2ENetworkCaptureRecord, effort: string) {
  697. expect(record.path).toContain("/messages");
  698. assertClaudeReasoningBody(asRecord(record.requestJson), effort);
  699. }
  700. function assertClaudeReasoningBody(body: Record<string, unknown>, effort: string) {
  701. expect(body.model).toBe(MODEL_ID);
  702. expect(body.max_tokens).toBe(expectedAnthropicMaxTokens(effort));
  703. expect(readNestedValue(body, ["thinking", "type"])).toBe("enabled");
  704. expect(readNestedValue(body, ["thinking", "budget_tokens"])).toBe(
  705. expectedAnthropicThinkingBudget(effort),
  706. );
  707. expect(readNestedValue(body, ["output_config", "effort"])).toBe(effort);
  708. expect(body.reasoning_effort).toBeUndefined();
  709. }
  710. function expectedAnthropicMaxTokens(effort: string): number {
  711. if (REASONING_BUDGETS[effort] === undefined) {
  712. throw new Error(`未知 Claude reasoning effort: ${effort}`);
  713. }
  714. // Bug 根因:失败日志里的 31,999 属于 thinking.budget_tokens,而不是
  715. // max_tokens。Anthropic 总输出上限仍保持 32K,只收敛内部思考预算来预留可见输出。
  716. return MODEL_OUTPUT_TOKEN_BUDGET;
  717. }
  718. function expectedAnthropicThinkingBudget(effort: string): number {
  719. const catalogBudget = REASONING_BUDGETS[effort];
  720. if (catalogBudget === undefined) {
  721. throw new Error(`未知 Claude reasoning effort: ${effort}`);
  722. }
  723. // 回归原因:Anthropic fixed thinking 与可见输出共享请求总预算;即使 catalog 的
  724. // xhigh 是 32K,也必须为可见输出保留至少 1 token,provider body 因此使用 31,999。
  725. return Math.min(catalogBudget, MODEL_OUTPUT_TOKEN_BUDGET - 1);
  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. }