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

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