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

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