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

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