settings-subagent-create-edit-persistence.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. import { access, readdir, readFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { decodeCustomModelValue, encodeCustomModelValue } from "@zcode/shared";
  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_MODEL_PROVIDER_MODEL_DELETE_BUTTON,
  11. TID_MODEL_PROVIDER_MODEL_INPUT,
  12. TID_MODEL_PROVIDER_NAV_ITEM,
  13. TID_SETTINGS_PAGE,
  14. TID_SETTINGS_SECTION_NAV,
  15. TID_SUBAGENT_ROW,
  16. TID_TASK_SETTINGS_BUTTON,
  17. testId,
  18. } from "@zcode/shared/test-ids";
  19. import {
  20. DEFAULT_WORKSPACE,
  21. clearAppData,
  22. clickTestIdByDom,
  23. readAgentsState,
  24. readModelProvider,
  25. waitForTestIdByDom,
  26. } from "#e2e/helpers/desktop-app";
  27. import {
  28. UPSTREAM_ALTERNATE_MODEL,
  29. UPSTREAM_ALTERNATE_PROVIDER_ID,
  30. UPSTREAM_MODEL,
  31. UPSTREAM_PROVIDER_ID,
  32. } from "#e2e/helpers/upstream-provider";
  33. import { resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  34. import { sel } from "#e2e/helpers/selectors";
  35. import { clickOpenScopeMenuOption } from "#e2e/helpers/settings-scope-menu";
  36. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  37. const CASE_TIMEOUT_MS = 240_000;
  38. const PRIMARY_MODEL = encodeCustomModelValue(UPSTREAM_PROVIDER_ID, UPSTREAM_MODEL);
  39. const ALTERNATE_MODEL = encodeCustomModelValue(
  40. UPSTREAM_ALTERNATE_PROVIDER_ID,
  41. UPSTREAM_ALTERNATE_MODEL,
  42. );
  43. const USER_CREATED = {
  44. description: "User create reasoning persistence",
  45. model: PRIMARY_MODEL,
  46. name: "e2e-user-reasoning",
  47. systemPrompt: "Review user changes with the selected effort.",
  48. thoughtLevel: "high",
  49. };
  50. const USER_UPDATED = {
  51. description: "User edit reasoning persistence",
  52. model: ALTERNATE_MODEL,
  53. name: "e2e-user-reasoning-v2",
  54. systemPrompt: "Review updated user changes with the selected effort.",
  55. thoughtLevel: "high",
  56. };
  57. const WORKSPACE_CREATED = {
  58. description: "Workspace create reasoning persistence",
  59. model: ALTERNATE_MODEL,
  60. name: "e2e-workspace-reasoning",
  61. systemPrompt: "Review workspace changes with the selected effort.",
  62. thoughtLevel: "max",
  63. };
  64. const WORKSPACE_UPDATED = {
  65. description: "Workspace edit reasoning persistence",
  66. model: PRIMARY_MODEL,
  67. name: "e2e-workspace-reasoning-v2",
  68. systemPrompt: "Review updated workspace changes with the selected effort.",
  69. thoughtLevel: "high",
  70. };
  71. const USER_DEFAULT_UNTOUCHED = {
  72. description: "User catalog default remains implicit",
  73. model: PRIMARY_MODEL,
  74. name: "e2e-user-default-materialized",
  75. systemPrompt: "Materialize the catalog default reasoning level.",
  76. };
  77. const USER_REMOVED_MODEL = {
  78. description: "User removed model requires re-selection",
  79. model: PRIMARY_MODEL,
  80. name: "e2e-user-removed-model",
  81. systemPrompt: "Require selecting a model again without restoring its unavailable option.",
  82. thoughtLevel: "high",
  83. };
  84. const USER_AGENT_ROOT = join(resolveE2EStorageRoot(), "agents");
  85. const PLUGIN_JUDGE_AGENT_NAME = "documents:visual-judge";
  86. const PLUGIN_JUDGE_AGENT_ID = "plugin:documents@zcode-plugins-official:visual-judge";
  87. const WORKSPACE_AGENT_ROOT = join(DEFAULT_WORKSPACE, ".zcode", "agents");
  88. const SUBAGENT_FORM_SELECTOR = `form:has(input[type="text"]):has(${sel(
  89. TID_CHAT_MODEL_SELECT_TRIGGER,
  90. )})`;
  91. interface CustomAgentFixture {
  92. description: string;
  93. model: string;
  94. name: string;
  95. systemPrompt: string;
  96. thoughtLevel?: string;
  97. }
  98. describe("Settings subagent 创建/编辑文件持久化 E2E", () => {
  99. before(async function () {
  100. this.timeout(CASE_TIMEOUT_MS);
  101. // 模型选择控件和 Subagent 的 model overlay 都依赖已初始化的 Provider/Registry。
  102. await prepareV4ConversationE2E();
  103. await setRendererLocale("en-US");
  104. await openSubagentSettings();
  105. });
  106. after(async () => {
  107. await browser.electron.restoreAllMocks();
  108. await clearAppData();
  109. });
  110. it("SE-01: builtin、user 与 workspace 保存后写入精确 model/reasoning 配置", async function () {
  111. this.timeout(CASE_TIMEOUT_MS);
  112. await persistBuiltInOverrides();
  113. await createCustomAgent(USER_CREATED, USER_AGENT_ROOT);
  114. await editCustomAgent(USER_CREATED, USER_UPDATED, USER_AGENT_ROOT);
  115. await selectSubagentScope(DEFAULT_WORKSPACE);
  116. await createCustomAgent(WORKSPACE_CREATED, WORKSPACE_AGENT_ROOT);
  117. await editCustomAgent(WORKSPACE_CREATED, WORKSPACE_UPDATED, WORKSPACE_AGENT_ROOT);
  118. });
  119. it("SE-02: 切换模型时物化 catalog 默认档位", async function () {
  120. this.timeout(CASE_TIMEOUT_MS);
  121. await selectSubagentScope("user");
  122. const generalScope = sel(testId(TID_SUBAGENT_ROW, "general-purpose"));
  123. // 从已有显式覆盖切换到另一模型后,只观察默认档位,不触发 effort 控件。
  124. await selectModelInScope(generalScope, ALTERNATE_MODEL);
  125. await assertDisplayedThoughtLevel(generalScope, "Max");
  126. await waitForAgentsState(
  127. (state) =>
  128. readBuiltInModelValue(state, "general-purpose") === ALTERNATE_MODEL &&
  129. readBuiltInReasoningLevel(state, "general-purpose") === "max",
  130. "general-purpose 切换模型时没有物化 catalog 默认 effort",
  131. );
  132. await createCustomAgent(USER_DEFAULT_UNTOUCHED, USER_AGENT_ROOT);
  133. });
  134. it("SE-04: 内置官方插件 subagent 可见并按 agent id 持久化 model/effort 覆盖", async function () {
  135. this.timeout(CASE_TIMEOUT_MS);
  136. await selectSubagentScope("user");
  137. // 官方插件没有安装记录;真实 CLI seed 后,Settings 也必须发现相同的只读 profile。
  138. const judgeRowTestId = testId(TID_SUBAGENT_ROW, PLUGIN_JUDGE_AGENT_NAME);
  139. await waitForTestIdByDom(judgeRowTestId, {
  140. timeout: 30_000,
  141. timeoutMsg: "Settings 未列出 documents:visual-judge",
  142. });
  143. const cacheRoot = join(
  144. resolveE2EStorageRoot(),
  145. "cli",
  146. "plugins",
  147. "cache",
  148. "zcode-plugins-official",
  149. "documents",
  150. );
  151. const artifacts = await Promise.all(
  152. (await readdir(cacheRoot, { withFileTypes: true }))
  153. .filter((entry) => entry.isDirectory())
  154. .map(async (entry) => {
  155. const path = join(cacheRoot, entry.name, "agents", "visual-judge.md");
  156. return (await fileExists(path)) ? { path, content: await readFile(path, "utf8") } : null;
  157. }),
  158. );
  159. expect(artifacts.some(Boolean)).toBe(true);
  160. const scope = sel(judgeRowTestId);
  161. await selectModelInScope(scope, ALTERNATE_MODEL);
  162. const expectedSelection = {
  163. providerId: UPSTREAM_ALTERNATE_PROVIDER_ID,
  164. modelId: UPSTREAM_ALTERNATE_MODEL,
  165. options: { reasoningLevel: "max" },
  166. };
  167. await waitForAgentsState(
  168. (state) =>
  169. JSON.stringify(
  170. (state.pluginAgentModelSelectionOverrides as Record<string, unknown>)?.[
  171. PLUGIN_JUDGE_AGENT_ID
  172. ],
  173. ) === JSON.stringify(expectedSelection),
  174. "插件覆盖未完整保存或未使用新模型最高档",
  175. );
  176. // 改到非默认 high,避免只重复点击自动保存的 max 而冒充 effort 修改覆盖。
  177. await selectThoughtLevelInScope(scope, "high");
  178. expectedSelection.options.reasoningLevel = "high";
  179. await waitForAgentsState(
  180. (state) =>
  181. JSON.stringify(
  182. (state.pluginAgentModelSelectionOverrides as Record<string, unknown>)?.[
  183. PLUGIN_JUDGE_AGENT_ID
  184. ],
  185. ) === JSON.stringify(expectedSelection),
  186. "插件 effort 修改未保存",
  187. );
  188. const state = await readAgentsState();
  189. expect(state.pluginAgentModelOverrides).toBeUndefined();
  190. expect(state.pluginAgentThoughtLevelOverrides).toBeUndefined();
  191. await browser.execute(
  192. (id) => document.querySelector<HTMLElement>(`[data-testid="${id}"]`)?.click(),
  193. judgeRowTestId,
  194. );
  195. expect(await $(SUBAGENT_FORM_SELECTOR).isExisting()).toBe(false);
  196. for (const artifact of artifacts) {
  197. if (artifact) expect(await readFile(artifact.path, "utf8")).toBe(artifact.content);
  198. }
  199. });
  200. it("SE-03: 删除已选模型后显示选择模型且不恢复候选", async function () {
  201. this.timeout(CASE_TIMEOUT_MS);
  202. await createCustomAgent(USER_REMOVED_MODEL, USER_AGENT_ROOT);
  203. const artifactPath = customAgentPath(USER_AGENT_ROOT, USER_REMOVED_MODEL.name);
  204. const artifactBeforeDelete = await readFile(artifactPath, "utf8");
  205. await deleteProviderModel(UPSTREAM_PROVIDER_ID, UPSTREAM_MODEL);
  206. await openSubagentSettingsSection();
  207. await openCustomAgentForm(USER_REMOVED_MODEL.name);
  208. const form = $(SUBAGENT_FORM_SELECTOR);
  209. const modelTrigger = form.$(sel(TID_CHAT_MODEL_SELECT_TRIGGER));
  210. const reasoningUnavailable = form.$('[data-subagent-thought-level-unavailable="true"]');
  211. const reasoningLoading = form.$('[data-subagent-thought-level-loading="true"]');
  212. await browser.waitUntil(
  213. async () =>
  214. (await modelTrigger.getAttribute("aria-label")) === "Select model" &&
  215. !(await form.$(sel(TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER)).isExisting()) &&
  216. !(await reasoningUnavailable.isExisting()) &&
  217. !(await reasoningLoading.isExisting()),
  218. {
  219. timeout: 15_000,
  220. timeoutMsg: "已删除模型重新编辑时没有显示选择模型,或 reasoning effort 仍然可见",
  221. },
  222. );
  223. expect(await modelTrigger.getAttribute("data-model-current-value")).toBe(PRIMARY_MODEL);
  224. await modelTrigger.click();
  225. await $(
  226. sel(
  227. testId(TID_CHAT_MODEL_SELECT_GROUP, `registry-provider:${UPSTREAM_ALTERNATE_PROVIDER_ID}`),
  228. ),
  229. ).waitForDisplayed({ timeout: 15_000 });
  230. expect(await $(sel(testId(TID_CHAT_MODEL_SELECT_ITEM, PRIMARY_MODEL))).isExisting()).toBe(
  231. false,
  232. );
  233. expect(await form.$('button[type="submit"]').isEnabled()).toBe(false);
  234. expect(await readFile(artifactPath, "utf8")).toBe(artifactBeforeDelete);
  235. });
  236. });
  237. async function openSubagentSettings() {
  238. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  239. timeout: 15_000,
  240. timeoutMsg: "没有找到设置入口按钮",
  241. });
  242. await waitForTestIdByDom(TID_SETTINGS_PAGE, {
  243. timeout: 15_000,
  244. timeoutMsg: "设置页没有渲染",
  245. });
  246. await openSubagentSettingsSection();
  247. }
  248. async function openSubagentSettingsSection() {
  249. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "subagents"), {
  250. timeout: 15_000,
  251. timeoutMsg: "设置页没有出现 subagents 分区入口",
  252. });
  253. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, "general-purpose"));
  254. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, "Explore"));
  255. }
  256. async function deleteProviderModel(providerId: string, modelId: string) {
  257. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "modelProvider"), {
  258. timeout: 15_000,
  259. timeoutMsg: "设置页没有出现模型供应商分区入口",
  260. });
  261. await clickTestIdByDom(testId(TID_MODEL_PROVIDER_NAV_ITEM, `custom:${providerId}`), {
  262. timeout: 15_000,
  263. timeoutMsg: `模型供应商导航没有出现 ${providerId}`,
  264. });
  265. const deleted = await browser.execute(
  266. (modelInputPrefix, deleteButtonPrefix, targetModelId) => {
  267. const input = Array.from(
  268. document.querySelectorAll<HTMLElement>(`[data-testid^="${modelInputPrefix}-"]`),
  269. ).find((candidate) => {
  270. const value =
  271. candidate instanceof HTMLInputElement ? candidate.value : candidate.textContent;
  272. return value?.trim() === targetModelId;
  273. });
  274. const inputTestId = input?.dataset.testid;
  275. const index = inputTestId?.slice(`${modelInputPrefix}-`.length);
  276. if (!index) return false;
  277. const deleteButton = document.querySelector<HTMLElement>(
  278. `[data-testid="${deleteButtonPrefix}-${index}"]`,
  279. );
  280. if (!deleteButton) return false;
  281. deleteButton.click();
  282. return true;
  283. },
  284. TID_MODEL_PROVIDER_MODEL_INPUT,
  285. TID_MODEL_PROVIDER_MODEL_DELETE_BUTTON,
  286. modelId,
  287. );
  288. if (!deleted) {
  289. throw new Error(`没有找到待删除模型 ${providerId}/${modelId}`);
  290. }
  291. await browser.waitUntil(
  292. async () => {
  293. const provider = await readModelProvider(providerId);
  294. return Boolean(
  295. provider &&
  296. !provider.models.some((model) => {
  297. if (typeof model === "string") return model === modelId;
  298. return model.id === modelId && model.deleted !== true;
  299. }),
  300. );
  301. },
  302. {
  303. timeout: 15_000,
  304. timeoutMsg: `模型没有从供应商配置中删除 ${providerId}/${modelId}`,
  305. },
  306. );
  307. }
  308. async function persistBuiltInOverrides() {
  309. const generalScope = sel(testId(TID_SUBAGENT_ROW, "general-purpose"));
  310. const exploreScope = sel(testId(TID_SUBAGENT_ROW, "Explore"));
  311. await selectModelInScope(generalScope, PRIMARY_MODEL);
  312. await waitForAgentsState(
  313. (state) => readBuiltInModelValue(state, "general-purpose") === PRIMARY_MODEL,
  314. "general-purpose model 没有写入 agents-state.json",
  315. );
  316. // high 是非默认档;显式点击必须覆盖自动补全的 max,并形成持久化选择。
  317. await selectThoughtLevelInScope(generalScope, "high");
  318. await waitForAgentsState(
  319. (state) => readBuiltInReasoningLevel(state, "general-purpose") === "high",
  320. "general-purpose 显式默认 effort 没有写入 agents-state.json",
  321. );
  322. await selectModelInScope(exploreScope, ALTERNATE_MODEL);
  323. await waitForAgentsState(
  324. (state) => readBuiltInModelValue(state, "Explore") === ALTERNATE_MODEL,
  325. "Explore model 没有写入 agents-state.json",
  326. );
  327. // max 是另一个模型的 catalog 默认档,用不同模型覆盖同一回归边界。
  328. await selectThoughtLevelInScope(exploreScope, "max");
  329. await waitForAgentsState(
  330. (state) => readBuiltInReasoningLevel(state, "Explore") === "max",
  331. "Explore 显式默认 effort 没有写入 agents-state.json",
  332. );
  333. const finalState = await readAgentsState();
  334. expect(finalState.builtInModelSelectionOverrides).toEqual({
  335. Explore: {
  336. providerId: UPSTREAM_ALTERNATE_PROVIDER_ID,
  337. modelId: UPSTREAM_ALTERNATE_MODEL,
  338. options: { reasoningLevel: "max" },
  339. },
  340. "general-purpose": {
  341. providerId: UPSTREAM_PROVIDER_ID,
  342. modelId: UPSTREAM_MODEL,
  343. options: { reasoningLevel: "high" },
  344. },
  345. });
  346. }
  347. async function createCustomAgent(
  348. fixture: CustomAgentFixture,
  349. root: string,
  350. displayedThoughtLevel?: string,
  351. ) {
  352. const newButton = $('button[aria-label="New"]');
  353. await newButton.waitForClickable({
  354. timeout: 15_000,
  355. timeoutMsg: "Subagent New 按钮不可用",
  356. });
  357. await newButton.click();
  358. await $(SUBAGENT_FORM_SELECTOR).waitForDisplayed({
  359. timeout: 15_000,
  360. timeoutMsg: "Subagent 新建表单没有打开",
  361. });
  362. await fillCustomAgentForm(fixture);
  363. if (displayedThoughtLevel) {
  364. await assertDisplayedThoughtLevel(SUBAGENT_FORM_SELECTOR, displayedThoughtLevel);
  365. }
  366. await saveCustomAgentForm(fixture.name);
  367. await assertCustomAgentArtifact(root, fixture);
  368. }
  369. async function editCustomAgent(
  370. previous: CustomAgentFixture,
  371. next: CustomAgentFixture,
  372. root: string,
  373. ) {
  374. await openCustomAgentForm(previous.name);
  375. await fillCustomAgentForm(next);
  376. await saveCustomAgentForm(next.name);
  377. const previousPath = customAgentPath(root, previous.name);
  378. await browser.waitUntil(async () => !(await fileExists(previousPath)), {
  379. timeout: 15_000,
  380. timeoutMsg: `Subagent 重命名后旧文件仍存在: ${previousPath}`,
  381. });
  382. await assertCustomAgentArtifact(root, next);
  383. }
  384. async function openCustomAgentForm(name: string) {
  385. const rowTestId = testId(TID_SUBAGENT_ROW, name);
  386. await browser.waitUntil(
  387. () =>
  388. browser.execute((currentRowTestId) => {
  389. const row = document.querySelector<HTMLElement>(`[data-testid="${currentRowTestId}"]`);
  390. if (!row) return false;
  391. row.click();
  392. return true;
  393. }, rowTestId),
  394. {
  395. timeout: 15_000,
  396. timeoutMsg: `Subagent 行不可编辑: ${name}`,
  397. },
  398. );
  399. await $(SUBAGENT_FORM_SELECTOR).waitForDisplayed({
  400. timeout: 15_000,
  401. timeoutMsg: `Subagent 编辑表单没有打开: ${name}`,
  402. });
  403. }
  404. async function fillCustomAgentForm(fixture: CustomAgentFixture) {
  405. const form = $(SUBAGENT_FORM_SELECTOR);
  406. const textInputs = await form.$$('input[type="text"]');
  407. const nameInput = textInputs[0];
  408. const descriptionInput = textInputs[1];
  409. if (!nameInput || !descriptionInput) {
  410. throw new Error("Subagent 表单缺少名称或描述输入框");
  411. }
  412. await nameInput.setValue(fixture.name);
  413. await descriptionInput.setValue(fixture.description);
  414. await form.$("textarea").setValue(fixture.systemPrompt);
  415. await selectModelInScope(SUBAGENT_FORM_SELECTOR, fixture.model);
  416. if (fixture.thoughtLevel !== undefined) {
  417. await selectThoughtLevelInScope(SUBAGENT_FORM_SELECTOR, fixture.thoughtLevel);
  418. }
  419. }
  420. async function saveCustomAgentForm(name: string) {
  421. await $(SUBAGENT_FORM_SELECTOR).$('button[type="submit"]').click();
  422. await browser.waitUntil(async () => !(await $(SUBAGENT_FORM_SELECTOR).isExisting()), {
  423. timeout: 15_000,
  424. timeoutMsg: `Subagent 保存后表单没有关闭: ${name}`,
  425. });
  426. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, name));
  427. }
  428. async function selectSubagentScope(scopeKey: string) {
  429. // 作用域标签包含设备名;使用稳定 key,避免显示文案变化导致菜单保持打开并污染后续用例。
  430. const trigger = $('[data-plugin-scope-trigger="true"]');
  431. await trigger.waitForClickable({ timeout: 15_000 });
  432. await trigger.click();
  433. await clickOpenScopeMenuOption(scopeKey, {
  434. timeoutMsg: `Subagent scope 菜单没有出现 ${scopeKey}`,
  435. });
  436. await browser.waitUntil(
  437. async () =>
  438. (await $('[data-plugin-scope-trigger="true"]').getAttribute("data-plugin-scope-key")) ===
  439. scopeKey,
  440. { timeout: 15_000, timeoutMsg: `Subagent scope 没有切换到 ${scopeKey}` },
  441. );
  442. }
  443. async function selectModelInScope(scope: string, model: string) {
  444. const decodedModel = decodeCustomModelValue(model);
  445. if (!decodedModel) {
  446. throw new Error(`E2E 仅支持选择 custom provider 模型: ${model}`);
  447. }
  448. const itemTestId = testId(TID_CHAT_MODEL_SELECT_ITEM, model);
  449. const groupTestId = testId(
  450. TID_CHAT_MODEL_SELECT_GROUP,
  451. `registry-provider:${decodedModel.providerId}`,
  452. );
  453. const trigger = $(scope).$(sel(TID_CHAT_MODEL_SELECT_TRIGGER));
  454. await trigger.waitForClickable({ timeout: 15_000 });
  455. await trigger.click();
  456. await browser.waitUntil(
  457. () =>
  458. browser.execute(
  459. (currentItemTestId, currentGroupTestId) =>
  460. Boolean(
  461. document.querySelector(`[data-testid="${currentItemTestId}"]`) ||
  462. document.querySelector(`[data-testid="${currentGroupTestId}"]`),
  463. ),
  464. itemTestId,
  465. groupTestId,
  466. ),
  467. { timeout: 15_000, timeoutMsg: `模型菜单没有出现 ${model}` },
  468. );
  469. const itemVisible = await browser.execute(
  470. (currentItemTestId) => Boolean(document.querySelector(`[data-testid="${currentItemTestId}"]`)),
  471. itemTestId,
  472. );
  473. if (!itemVisible) {
  474. await browser.execute((currentGroupTestId) => {
  475. const group = document.querySelector<HTMLElement>(`[data-testid="${currentGroupTestId}"]`);
  476. if (!group) return;
  477. group.focus();
  478. for (const eventName of ["pointerenter", "mouseenter", "mousemove"] as const) {
  479. group.dispatchEvent(
  480. new MouseEvent(eventName, {
  481. bubbles: true,
  482. cancelable: true,
  483. view: window,
  484. }),
  485. );
  486. }
  487. group.click();
  488. }, groupTestId);
  489. }
  490. await browser.waitUntil(
  491. () =>
  492. browser.execute(
  493. (currentItemTestId) =>
  494. Boolean(document.querySelector(`[data-testid="${currentItemTestId}"]`)),
  495. itemTestId,
  496. ),
  497. { timeout: 15_000, timeoutMsg: `模型菜单没有出现 ${model}` },
  498. );
  499. await browser.execute((currentItemTestId) => {
  500. document.querySelector<HTMLElement>(`[data-testid="${currentItemTestId}"]`)?.click();
  501. }, itemTestId);
  502. await browser.waitUntil(
  503. async () => (await trigger.getAttribute("data-model-current-value")) === model,
  504. { timeout: 15_000, timeoutMsg: `模型控件没有切换到 ${model}` },
  505. );
  506. }
  507. async function selectThoughtLevelInScope(scope: string, thoughtLevel: string) {
  508. let selected = false;
  509. for (let attempt = 0; attempt < 3; attempt += 1) {
  510. const trigger = $(scope).$(sel(TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER));
  511. await trigger.waitForClickable({
  512. timeout: 15_000,
  513. timeoutMsg: `reasoning effort 控件没有出现: ${scope}`,
  514. });
  515. await trigger.click();
  516. try {
  517. const item = $(sel(testId(TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM, thoughtLevel)));
  518. await item.waitForClickable({ timeout: 3_000 });
  519. await item.click();
  520. selected = true;
  521. break;
  522. } catch {
  523. await browser.keys("Escape");
  524. }
  525. }
  526. if (!selected) {
  527. throw new Error(`reasoning effort 菜单没有出现 ${thoughtLevel}`);
  528. }
  529. }
  530. async function assertDisplayedThoughtLevel(scope: string, expectedLabel: string) {
  531. const trigger = $(scope).$(sel(TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER));
  532. await trigger.waitForDisplayed({
  533. timeout: 15_000,
  534. timeoutMsg: `reasoning effort 默认档位没有出现: ${scope}`,
  535. });
  536. await browser.waitUntil(
  537. async () => (await trigger.getAttribute("aria-label")) === expectedLabel,
  538. {
  539. timeout: 15_000,
  540. timeoutMsg: `reasoning effort 没有展示 catalog 默认档位 ${expectedLabel}`,
  541. },
  542. );
  543. }
  544. async function assertCustomAgentArtifact(root: string, fixture: CustomAgentFixture) {
  545. const path = customAgentPath(root, fixture.name);
  546. const expected = expectedCustomAgentMarkdown(fixture);
  547. let latest = "";
  548. await browser.waitUntil(
  549. async () => {
  550. try {
  551. latest = await readFile(path, "utf8");
  552. return latest === expected;
  553. } catch {
  554. return false;
  555. }
  556. },
  557. {
  558. timeout: 15_000,
  559. timeoutMsg: `Subagent Markdown 与表单不一致: ${path}\n${latest}`,
  560. },
  561. );
  562. expect(latest).toBe(expected);
  563. }
  564. function expectedCustomAgentMarkdown(fixture: CustomAgentFixture) {
  565. const decoded = decodeCustomModelValue(fixture.model)!;
  566. return `---
  567. name: "${fixture.name}"
  568. description: "${fixture.description}"
  569. color: yellow
  570. model: ${decoded.providerId}/${decoded.modelName}
  571. thoughtLevel: ${fixture.thoughtLevel ?? "max"}
  572. injectAgentsMd: true
  573. ---
  574. ${fixture.systemPrompt}
  575. `;
  576. }
  577. function customAgentPath(root: string, name: string) {
  578. return join(root, `${name.toLowerCase()}.md`);
  579. }
  580. async function fileExists(path: string) {
  581. try {
  582. await access(path);
  583. return true;
  584. } catch {
  585. return false;
  586. }
  587. }
  588. async function waitForAgentsState(
  589. predicate: (state: Record<string, unknown>) => boolean,
  590. timeoutMsg: string,
  591. ) {
  592. await browser.waitUntil(async () => predicate(await readAgentsState()), {
  593. timeout: 15_000,
  594. timeoutMsg,
  595. });
  596. }
  597. function readBuiltInSelection(state: Record<string, unknown>, agentName: string) {
  598. const map = state.builtInModelSelectionOverrides;
  599. if (!map || typeof map !== "object" || Array.isArray(map)) return null;
  600. const value = (map as Record<string, unknown>)[agentName];
  601. return value && typeof value === "object" && !Array.isArray(value)
  602. ? (value as Record<string, unknown>)
  603. : null;
  604. }
  605. function readBuiltInModelValue(state: Record<string, unknown>, agentName: string) {
  606. const selection = readBuiltInSelection(state, agentName);
  607. return typeof selection?.providerId === "string" && typeof selection.modelId === "string"
  608. ? encodeCustomModelValue(selection.providerId, selection.modelId)
  609. : null;
  610. }
  611. function readBuiltInReasoningLevel(state: Record<string, unknown>, agentName: string) {
  612. const options = readBuiltInSelection(state, agentName)?.options;
  613. if (!options || typeof options !== "object" || Array.isArray(options)) return null;
  614. const reasoningLevel = (options as Record<string, unknown>).reasoningLevel;
  615. return typeof reasoningLevel === "string" ? reasoningLevel : null;
  616. }
  617. async function setRendererLocale(locale: "en-US") {
  618. const changed = await browser.execute((nextLocale) => {
  619. const actions = (window as typeof window & { __testActions?: Record<string, unknown> })
  620. .__testActions;
  621. const setLocale = actions?.setLocale;
  622. if (typeof setLocale !== "function") return false;
  623. (setLocale as (value: string) => void)(nextLocale);
  624. return true;
  625. }, locale);
  626. if (!changed) {
  627. throw new Error(`缺少 renderer locale test action: ${locale}`);
  628. }
  629. }