subagentsSection.test.ts 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911
  1. // @vitest-environment jsdom
  2. import { readFileSync } from "node:fs";
  3. import { createElement, type ChangeEvent } from "react";
  4. import { renderToStaticMarkup } from "react-dom/server";
  5. import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
  6. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  7. import { TID_SUBAGENT_BUILT_IN_MODEL_TRIGGER, TID_SUBAGENT_ROW, testId } from "@zcode/shared";
  8. import { encodeCustomModelValue } from "../src/lib/zcodeCustomModelValue.js";
  9. const capturedButtons: Array<Record<string, unknown>> = [];
  10. const capturedModelConfigSelects: Array<Record<string, unknown>> = [];
  11. const capturedThoughtLevelControls: Array<Record<string, unknown>> = [];
  12. let useStateCallCount = 0;
  13. let stateOverrides = new Map<number, unknown>();
  14. let onManageModels = vi.fn();
  15. let useRealReactHooks = false;
  16. const mockTabs = vi.hoisted(() => ({ tabs: [] as unknown[] }));
  17. const mockInitializePlugins = vi.hoisted(() => vi.fn(async () => {}));
  18. const mockSubagentsService = vi.hoisted(() => ({
  19. list: vi.fn(async () => ({
  20. agents: [],
  21. userAgents: [],
  22. pluginAgents: [],
  23. capability: { userScopeAvailable: false, userScopeReason: "desktop_only" },
  24. })),
  25. getPrimaryUserAgentsDirectory: vi.fn(async () => ({ path: "/tmp/agents" })),
  26. createAgent: vi.fn(),
  27. updateAgent: vi.fn(),
  28. deleteAgent: vi.fn(),
  29. setEnabled: vi.fn(),
  30. setBuiltInModelOverride: vi.fn(),
  31. setPluginAgentModelOverride: vi.fn(),
  32. }));
  33. const mockRefreshLoadedSubagentsStoreForWorkspace = vi.hoisted(() => vi.fn(async () => {}));
  34. const mockUseModelProviders = vi.hoisted(() =>
  35. vi.fn(() => ({
  36. displayOrder: { providerIds: [] },
  37. loading: false,
  38. modelProviders: [],
  39. })),
  40. );
  41. const mockToolbarConfigState = vi.hoisted(() => ({
  42. configOptions: [
  43. {
  44. id: "model",
  45. name: "Model",
  46. category: "model",
  47. type: "select" as const,
  48. currentValue: "custom-openai/gpt-5.4",
  49. options: [
  50. {
  51. value: "custom-openai/gpt-5.4",
  52. name: "gpt-5.4",
  53. modelProviderId: "custom-openai",
  54. modelProviderName: "Custom OpenAI",
  55. modelThoughtLevels: ["low", "high"],
  56. modelDefaultThoughtLevel: "high",
  57. },
  58. {
  59. value: "custom-openai/glm-5.2",
  60. name: "glm-5.2",
  61. modelProviderId: "custom-openai",
  62. modelProviderName: "Custom OpenAI",
  63. modelThoughtLevels: ["high", "max"],
  64. modelDefaultThoughtLevel: "max",
  65. },
  66. {
  67. value: "custom-openai/plain-chat",
  68. name: "plain-chat",
  69. modelProviderId: "custom-openai",
  70. modelProviderName: "Custom OpenAI",
  71. modelThoughtLevels: [],
  72. },
  73. ],
  74. },
  75. ],
  76. status: "ready" as "idle" | "loading" | "ready" | "error",
  77. }));
  78. const mockModelSelectionView = vi.hoisted(() => ({
  79. revision: 1,
  80. providers: [
  81. {
  82. providerId: "custom-openai",
  83. config: {
  84. label: "Custom OpenAI",
  85. access: { type: "api-key" as const, apiKey: "token" },
  86. api: {
  87. type: "openai-chat-completions" as const,
  88. baseUrl: "https://example.test/v1",
  89. },
  90. models: ["gpt-5.4", "glm-5.2", "plain-chat"],
  91. },
  92. models: [
  93. {
  94. modelId: "gpt-5.4",
  95. config: {
  96. optionSpecs: {
  97. reasoningLevel: {
  98. values: ["low", "high"],
  99. map: "{}",
  100. },
  101. maxOutputTokens: { max: 32_000, map: "{}" },
  102. },
  103. },
  104. },
  105. {
  106. modelId: "glm-5.2",
  107. config: {
  108. optionSpecs: {
  109. reasoningLevel: {
  110. values: ["high", "max"],
  111. map: "{}",
  112. },
  113. maxOutputTokens: { max: 32_000, map: "{}" },
  114. },
  115. },
  116. },
  117. {
  118. modelId: "plain-chat",
  119. config: {
  120. optionSpecs: {
  121. reasoningLevel: { values: ["disabled"], map: "{}" },
  122. maxOutputTokens: { max: 32_000, map: "{}" },
  123. },
  124. },
  125. },
  126. ],
  127. },
  128. ],
  129. }));
  130. vi.mock("react", async () => {
  131. const actual = await vi.importActual<typeof import("react")>("react");
  132. return {
  133. ...actual,
  134. useEffect: (effect: () => void | (() => void), dependencies?: readonly unknown[]) =>
  135. useRealReactHooks ? actual.useEffect(effect, dependencies) : undefined,
  136. useState: (initialValue: unknown) => {
  137. if (useRealReactHooks) {
  138. return actual.useState(initialValue);
  139. }
  140. useStateCallCount += 1;
  141. if (stateOverrides.has(useStateCallCount)) {
  142. return [stateOverrides.get(useStateCallCount), vi.fn()] as const;
  143. }
  144. if (useStateCallCount === 1) {
  145. return [[], vi.fn()] as const;
  146. }
  147. if (useStateCallCount === 2) {
  148. return [{ userScopeAvailable: false, userScopeReason: "desktop_only" }, vi.fn()] as const;
  149. }
  150. if (useStateCallCount === 3) {
  151. return [false, vi.fn()] as const;
  152. }
  153. if (useStateCallCount === 4) {
  154. return [false, vi.fn()] as const;
  155. }
  156. return [typeof initialValue === "function" ? initialValue() : initialValue, vi.fn()] as const;
  157. },
  158. };
  159. });
  160. vi.mock("lucide-react", () => ({
  161. ArrowLeft: (props: Record<string, unknown>) => createElement("svg", props),
  162. Bot: (props: Record<string, unknown>) => createElement("svg", props),
  163. Check: (props: Record<string, unknown>) => createElement("svg", props),
  164. ChevronDown: (props: Record<string, unknown>) => createElement("svg", props),
  165. CircleHelp: (props: Record<string, unknown>) =>
  166. createElement("svg", { ...props, "data-icon": "reasoning-unavailable" }),
  167. FolderOpen: (props: Record<string, unknown>) => createElement("svg", props),
  168. InfoIcon: (props: Record<string, unknown>) => createElement("svg", props, "info"),
  169. Download: (props: Record<string, unknown>) => createElement("svg", props),
  170. Import: (props: Record<string, unknown>) => createElement("svg", props),
  171. SquareArrowRightEnter: (props: Record<string, unknown>) => createElement("svg", props),
  172. Loader2: (props: Record<string, unknown>) => createElement("svg", props),
  173. MoreHorizontal: (props: Record<string, unknown>) => createElement("svg", props),
  174. Pencil: (props: Record<string, unknown>) => createElement("svg", props),
  175. Plus: (props: Record<string, unknown>) => createElement("svg", props),
  176. RefreshCw: (props: Record<string, unknown>) => createElement("svg", props),
  177. RefreshCcw: (props: Record<string, unknown>) => createElement("svg", props),
  178. Search: (props: Record<string, unknown>) => createElement("svg", props),
  179. Trash2: (props: Record<string, unknown>) => createElement("svg", props),
  180. X: (props: Record<string, unknown>) => createElement("svg", props),
  181. }));
  182. vi.mock("@/components/ui/button.js", () => ({
  183. Button: ({ children, ...props }: { children: unknown; [key: string]: unknown }) => {
  184. capturedButtons.push({ children, ...props });
  185. return createElement("button", props, children);
  186. },
  187. }));
  188. vi.mock("@/ModelConfigSelect.js", () => ({
  189. ModelConfigSelect: ({ triggerLabel, normalizedValue, ...props }: Record<string, unknown>) => {
  190. capturedModelConfigSelects.push({
  191. triggerLabel,
  192. normalizedValue,
  193. ...props,
  194. });
  195. return createElement(
  196. "button",
  197. {
  198. type: "button",
  199. "data-model-current-value": normalizedValue,
  200. },
  201. triggerLabel,
  202. );
  203. },
  204. }));
  205. vi.mock("@/ControlHintTooltip.js", () => ({
  206. ControlHintTooltip: ({ children }: { children: unknown }) => children,
  207. }));
  208. vi.mock("@/store/TabStoreProvider.js", () => ({
  209. useTabStore: (selector: (state: { tabs: unknown[] }) => unknown) => selector(mockTabs),
  210. }));
  211. vi.mock("@/store/pluginManagementStore.js", () => ({
  212. usePluginManagementStore: (selector: (state: Record<string, unknown>) => unknown) =>
  213. selector({ plugins: [], availablePlugins: [], initialize: mockInitializePlugins }),
  214. }));
  215. vi.mock("@/settings/PluginScopeMenu.js", () => ({
  216. PluginScopeMenu: () => createElement("button", null, "scope"),
  217. getPluginWorkspaceKey: () => "workspace",
  218. isPluginScopeWorkspaceConnected: () => true,
  219. }));
  220. vi.mock("@/chat-input-toolbar/ThoughtLevelCycleControl.js", () => ({
  221. ThoughtLevelCycleControl: (props: Record<string, unknown>) => {
  222. capturedThoughtLevelControls.push(props);
  223. return createElement("button", {
  224. type: "button",
  225. "data-testid": "subagent-thought-level",
  226. });
  227. },
  228. }));
  229. vi.mock("@/components/ui/input.js", () => ({
  230. Input: (props: Record<string, unknown>) => createElement("input", props),
  231. }));
  232. vi.mock("@/components/ui/select.js", () => ({
  233. Select: ({ children }: { children: unknown }) => createElement("div", null, children),
  234. SelectContent: ({ children }: { children: unknown }) => createElement("div", null, children),
  235. SelectItem: ({ children }: { children: unknown }) => createElement("div", null, children),
  236. SelectTrigger: ({ children }: { children: unknown }) => createElement("button", null, children),
  237. SelectValue: () => createElement("span"),
  238. }));
  239. vi.mock("@/components/ui/tabs.js", () => ({
  240. Tabs: ({ children }: { children: unknown }) => createElement("div", null, children),
  241. TabsList: ({ children }: { children: unknown }) => createElement("div", null, children),
  242. TabsTrigger: ({ children, value }: { children: unknown; value: string }) =>
  243. createElement("button", { type: "button", "data-value": value }, children),
  244. }));
  245. vi.mock("@/components/ui/switch.js", () => ({
  246. Switch: ({ onCheckedChange, ...props }: Record<string, unknown>) =>
  247. createElement("input", {
  248. type: "checkbox",
  249. role: "switch",
  250. ...props,
  251. onChange: (event: ChangeEvent<HTMLInputElement>) => {
  252. if (typeof onCheckedChange === "function") {
  253. (onCheckedChange as (checked: boolean) => void)(event.target.checked);
  254. }
  255. },
  256. }),
  257. }));
  258. vi.mock("@/components/ui/textarea.js", () => ({
  259. Textarea: (props: Record<string, unknown>) => createElement("textarea", props),
  260. }));
  261. vi.mock("@/components/ui/toast.js", () => ({
  262. toast: vi.fn(),
  263. }));
  264. vi.mock("@/hooks/useConfirmDialog.js", () => ({
  265. useConfirmDialog: () => vi.fn(async () => true),
  266. }));
  267. vi.mock("@/hooks/usePlatform.js", () => ({
  268. usePlatform: () => ({
  269. openInFileManager: vi.fn(async () => ({ success: true })),
  270. }),
  271. }));
  272. vi.mock("@/hooks/useServices.js", () => ({
  273. useOptionalServices: () => null,
  274. useServices: () => ({
  275. subagentsService: mockSubagentsService,
  276. }),
  277. }));
  278. vi.mock("@/store/subagentsStore.js", () => ({
  279. refreshLoadedSubagentsStoreForWorkspace: mockRefreshLoadedSubagentsStoreForWorkspace,
  280. }));
  281. vi.mock("@/hooks/useModelProviders.js", () => ({
  282. useModelProviders: mockUseModelProviders,
  283. }));
  284. vi.mock("@/hooks/useModelSelectionView.js", () => {
  285. return {
  286. useModelSelectionView: () => ({
  287. state: { status: "ready", view: mockModelSelectionView },
  288. reload: vi.fn(),
  289. }),
  290. useModelSelectionServiceView: () => ({
  291. state: { status: "ready", view: mockModelSelectionView },
  292. reload: vi.fn(),
  293. }),
  294. };
  295. });
  296. vi.mock("@/hooks/useZCodeConfig.js", () => ({
  297. useToolbarConfigOptions: () => ({
  298. configOptions: mockToolbarConfigState.configOptions,
  299. loading: mockToolbarConfigState.status === "loading",
  300. error: mockToolbarConfigState.status === "error",
  301. status: mockToolbarConfigState.status,
  302. }),
  303. }));
  304. vi.mock("@/settings/model-provider-section/useEnterpriseCodingPlanProducts.js", () => ({
  305. useEnterpriseCodingPlanProducts: () => ({
  306. snapshot: null,
  307. loading: false,
  308. error: null,
  309. refresh: vi.fn(async () => {}),
  310. }),
  311. }));
  312. vi.mock("@/i18n/IntlProvider.js", () => ({
  313. useZCodeIntl: () => ({
  314. intl: {
  315. formatMessage: ({ id }: { id: string }, values?: Record<string, string | number>) => {
  316. const messages: Record<string, string> = {
  317. "settings.subagents.description": "Manage subagents.",
  318. "settings.subagents.workspaceScopeUnsupported":
  319. "Workspace-level creation or editing is unsupported",
  320. "settings.subagents.addNew": "New subagent",
  321. "settings.create.action": "New",
  322. "settings.resourceActions.import": "Import",
  323. "settings.resourceActions.export": "Export",
  324. "settings.resourceActions.more": "More actions",
  325. "common.loading": "Loading...",
  326. "common.refresh": "Refresh",
  327. "settings.subagents.openUserAgentsFolder": "Open user subagents folder",
  328. "settings.subagents.noDescription": "No description",
  329. "settings.skills.refresh": "Refresh",
  330. "settings.skills.refreshing": "Refreshing...",
  331. "settings.subagents.searchPlaceholder": "Search subagents",
  332. "settings.subagents.userScopeDesktopOnly": "Subagents are desktop only.",
  333. "settings.subagents.empty": "No subagents found",
  334. "settings.subagents.group.user": "Installed",
  335. "settings.subagents.group.plugin": "Plugin subagents",
  336. "settings.subagents.group.plugin.hint": "Plugin agents are read-only.",
  337. "settings.subagents.group.builtIn": "Built-in subagents",
  338. "settings.subagents.group.builtIn.hint": "Built-in agents are read-only.",
  339. "settings.modelProvider.connectionMode.apiKeyBadge": "API",
  340. "settings.modelProvider.connectionMode.codingPlanBadge": "Individual",
  341. "settings.modelProvider.connectionMode.startPlan": "Start Plan",
  342. "settings.modelProvider.connectionMode.startPlanBadge": "Start",
  343. "settings.modelProvider.connectionMode.teamPlan": "Team Plan",
  344. "settings.modelProvider.connectionMode.teamPlanBadge": "Team",
  345. "settings.subagents.scope.builtIn": "Built-in",
  346. "settings.subagents.scope.plugin": "Plugin",
  347. "settings.scope.user": "User",
  348. "settings.subagents.model.select": "Select model",
  349. "settings.subagents.model.inherit": "Inherit default",
  350. "settings.subagents.model.defaultMain": "Inherit default",
  351. "settings.subagents.model.main": "Main model",
  352. "settings.subagents.reasoningUnavailable": "Reasoning effort unavailable",
  353. "settings.subagents.toolsCount": `${values?.count ?? 0} tools`,
  354. "settings.subagents.tools.all": "All tools",
  355. "settings.subagents.tools.inherit": "Inherit tools",
  356. "settings.subagents.toggleAria": `Toggle ${values?.name ?? ""}`,
  357. "settings.subagents.form.injectAgentsMd.label": "Inject AGENTS.md",
  358. "settings.modelProvider.apiKey": "API key",
  359. "settings.modelProvider.connectionMode.codingPlan": "Individual Plan",
  360. "chat.toolbar.model.manageModels": "Manage models",
  361. "settings.subagents.form.validation.thoughtLevelUnavailable": "Select a supported effort",
  362. };
  363. return messages[id] ?? id;
  364. },
  365. },
  366. }),
  367. }));
  368. vi.mock("@/settings/SettingsResourceGroupHeader.js", () => ({
  369. SettingsResourceGroupHeader: ({ title }: { title: string }) => createElement("h3", null, title),
  370. }));
  371. async function renderSubagentsSection() {
  372. useStateCallCount = 0;
  373. const { SubagentsSection } = await import("../src/settings/SubagentsSection.js");
  374. return renderToStaticMarkup(
  375. createElement(SubagentsSection, {
  376. onManageModels,
  377. workspacePath: "/repo",
  378. }),
  379. );
  380. }
  381. async function renderInteractiveSubagentsSection() {
  382. useRealReactHooks = true;
  383. const { SubagentsSection } = await import("../src/settings/SubagentsSection.js");
  384. return render(
  385. createElement(SubagentsSection, {
  386. onManageModels,
  387. workspacePath: "/repo",
  388. }),
  389. );
  390. }
  391. function findButton(label: string) {
  392. return capturedButtons.find((button) => button["aria-label"] === label);
  393. }
  394. describe("SubagentsSection", () => {
  395. afterEach(() => {
  396. cleanup();
  397. });
  398. beforeEach(() => {
  399. capturedButtons.length = 0;
  400. capturedModelConfigSelects.length = 0;
  401. capturedThoughtLevelControls.length = 0;
  402. useStateCallCount = 0;
  403. stateOverrides = new Map<number, unknown>();
  404. onManageModels = vi.fn();
  405. useRealReactHooks = false;
  406. mockTabs.tabs = [];
  407. mockInitializePlugins.mockReset().mockResolvedValue(undefined);
  408. mockToolbarConfigState.status = "ready";
  409. vi.clearAllMocks();
  410. mockSubagentsService.list.mockResolvedValue({
  411. agents: [],
  412. userAgents: [],
  413. pluginAgents: [],
  414. capability: {
  415. userScopeAvailable: false,
  416. userScopeReason: "desktop_only",
  417. },
  418. });
  419. mockRefreshLoadedSubagentsStoreForWorkspace.mockResolvedValue(undefined);
  420. });
  421. it.each([false, true])(
  422. "插件初始化晚于首读时刷新用户页资源;卸载=%s 不消费迟到结果",
  423. async (unmounted) => {
  424. mockTabs.tabs = [{ kind: "workspace", id: "local", workspacePath: "/repo" }];
  425. let resolveInventory!: () => void;
  426. mockInitializePlugins.mockImplementationOnce(
  427. () =>
  428. new Promise<void>((resolve) => {
  429. resolveInventory = resolve;
  430. }),
  431. );
  432. await renderInteractiveSubagentsSection();
  433. await waitFor(() => expect(mockSubagentsService.list).toHaveBeenCalledTimes(1));
  434. expect(mockInitializePlugins).toHaveBeenCalledWith(
  435. expect.objectContaining({ workspacePath: "/repo", configScope: "user" }),
  436. );
  437. if (unmounted) cleanup();
  438. await act(async () => {
  439. resolveInventory();
  440. await Promise.resolve();
  441. });
  442. expect(mockSubagentsService.list).toHaveBeenCalledTimes(unmounted ? 1 : 2);
  443. expect(mockSubagentsService.list).toHaveBeenLastCalledWith(
  444. expect.objectContaining({ workspacePath: "", mode: "settingsUserOnly" }),
  445. );
  446. },
  447. );
  448. it("keeps same-name plugin subagents in separate marketplace groups", async () => {
  449. const { groupPluginAgentsById } = await import("../src/settings/SubagentsSection.js");
  450. const groups = groupPluginAgentsById([
  451. {
  452. id: "official-agent",
  453. name: "official-agent",
  454. description: "",
  455. systemPrompt: "",
  456. path: "/official",
  457. scope: "workspace",
  458. source: "plugin",
  459. enabled: true,
  460. pluginId: "computer-use@zcode-plugins-official",
  461. pluginName: "computer-use",
  462. },
  463. {
  464. id: "custom-agent",
  465. name: "custom-agent",
  466. description: "",
  467. systemPrompt: "",
  468. path: "/custom",
  469. scope: "workspace",
  470. source: "plugin",
  471. enabled: true,
  472. pluginId: "zcode-cua@custom-marketplace",
  473. pluginName: "zcode-cua",
  474. },
  475. ]);
  476. expect(groups.map(([key, items]) => [key, items[0]?.id])).toEqual([
  477. ["computer-use@zcode-plugins-official", "official-agent"],
  478. ["zcode-cua@custom-marketplace", "custom-agent"],
  479. ]);
  480. });
  481. it("hides user-level write actions when user subagents are unavailable", async () => {
  482. const html = await renderSubagentsSection();
  483. expect(findButton("New")).toBeUndefined();
  484. expect(findButton("Open user subagents folder")).toBeUndefined();
  485. expect(html).not.toContain("Workspace-level creation or editing is unsupported");
  486. expect(html).toContain("Subagents are desktop only.");
  487. });
  488. it("renders plugin subagents in their own read-only group", async () => {
  489. stateOverrides = new Map<number, unknown>([
  490. [
  491. 1,
  492. [
  493. {
  494. id: "plugin:feature-dev@claude-plugins-official:code-architect",
  495. name: "feature-dev:code-architect",
  496. description: "Designs feature architectures",
  497. systemPrompt: "Architect.",
  498. path: "/cache/feature-dev/agents/code-architect.md",
  499. scope: "user",
  500. source: "plugin",
  501. enabled: true,
  502. readOnly: true,
  503. },
  504. ],
  505. ],
  506. ]);
  507. const html = await renderSubagentsSection();
  508. expect(html).toContain("Feature Dev");
  509. expect(html).toContain("feature-dev:code-architect");
  510. });
  511. it("gates the enabled toggle on user scope instead of general editability", async () => {
  512. // Bugfix 回归:workspace profile 可编辑之后仍不能展示启用开关——runtime 只对 user scope
  513. // 应用 disabledAgentIds(CLI isDisabledUserProfile 对 source !== "user" 直接 false,
  514. // workspace profile 的 source 是 "project"),开关点了会静默回弹。
  515. const source = readFileSync("packages/ui/src/settings/SubagentsSection.tsx", "utf8");
  516. expect(source).toMatch(/function supportsEnabledToggle\([\s\S]*?agent\.scope === "user"/);
  517. expect(source).toMatch(/\{showEnabledToggle \? \(\s*<Switch/);
  518. expect(source).toContain("const showEnabledToggle = supportsEnabledToggle(agent);");
  519. expect(source).toContain("if (!supportsEnabledToggle(agent)) {");
  520. });
  521. it("projects one settings row per plugin agent file while keeping runtime aliases separate", async () => {
  522. const { projectSettingsSubagents } = await import("../src/settings/SubagentsSection.js");
  523. const canonical = {
  524. id: "plugin:feature-dev@claude-plugins-official:code-architect",
  525. name: "feature-dev:code-architect",
  526. description: "Designs feature architectures",
  527. systemPrompt: "Architect.",
  528. path: "/cache/feature-dev/agents/code-architect.md",
  529. scope: "user" as const,
  530. source: "plugin" as const,
  531. enabled: true,
  532. readOnly: true,
  533. };
  534. const alias = {
  535. ...canonical,
  536. id: "plugin:feature-dev@claude-plugins-official:code-architect:alias",
  537. name: "code-architect",
  538. };
  539. const builtIn = {
  540. id: "built-in:explore",
  541. name: "Explore",
  542. description: "Search broadly",
  543. systemPrompt: "Search.",
  544. path: "built-in:Explore",
  545. scope: "built-in" as const,
  546. source: "built-in" as const,
  547. enabled: true,
  548. readOnly: true,
  549. };
  550. expect(
  551. projectSettingsSubagents({
  552. agents: [builtIn, alias, canonical],
  553. userAgents: [],
  554. pluginAgents: [canonical],
  555. capability: { userScopeAvailable: true },
  556. }).map((agent) => agent.name),
  557. ).toEqual(["Explore", "feature-dev:code-architect"]);
  558. });
  559. it("renders wildcard tools as all tools instead of a single tool", async () => {
  560. stateOverrides = new Map<number, unknown>([
  561. [
  562. 1,
  563. [
  564. {
  565. id: "built-in:explore",
  566. name: "Explore",
  567. description: "Search broadly",
  568. systemPrompt: "Search.",
  569. path: "built-in:Explore",
  570. scope: "built-in",
  571. source: "built-in",
  572. enabled: true,
  573. readOnly: true,
  574. tools: ["*"],
  575. },
  576. ],
  577. ],
  578. [2, { userScopeAvailable: true }],
  579. ]);
  580. const html = await renderSubagentsSection();
  581. expect(html).toContain("Explore");
  582. expect(html).toContain("All tools");
  583. expect(html).not.toContain("1 tools");
  584. });
  585. it("renders model controls for built-in subagents while keeping user model badges", async () => {
  586. stateOverrides = new Map<number, unknown>([
  587. [
  588. 1,
  589. [
  590. {
  591. id: "built-in:explore",
  592. name: "Explore",
  593. description: "Search broadly",
  594. systemPrompt: "Search.",
  595. path: "built-in:Explore",
  596. scope: "built-in",
  597. source: "built-in",
  598. enabled: true,
  599. readOnly: true,
  600. tools: ["Read"],
  601. },
  602. {
  603. id: "user:code-reviewer",
  604. name: "code-reviewer",
  605. description: "Review code",
  606. systemPrompt: "Review.",
  607. color: "blue",
  608. modelSelection: { providerId: "custom-openai", modelId: "gpt-5.4" },
  609. tools: ["Read", "Grep"],
  610. path: "/tmp/agents/code-reviewer.md",
  611. scope: "user",
  612. source: "user",
  613. enabled: true,
  614. readOnly: false,
  615. },
  616. ],
  617. ],
  618. [2, { userScopeAvailable: true }],
  619. ]);
  620. const html = await renderSubagentsSection();
  621. expect(html).toContain("Explore");
  622. expect(html).toContain("code-reviewer");
  623. expect(html).toContain("Inherit default");
  624. expect(html).toContain("gpt-5.4");
  625. const container = document.createElement("div");
  626. container.innerHTML = html;
  627. const builtInRow = container.querySelector(
  628. `[data-testid="${testId(TID_SUBAGENT_ROW, "Explore")}"]`,
  629. );
  630. const userRow = container.querySelector(
  631. `[data-testid="${testId(TID_SUBAGENT_ROW, "code-reviewer")}"]`,
  632. );
  633. expect(builtInRow?.classList.contains("grid-cols-[auto_minmax(0,1fr)]")).toBe(true);
  634. expect(builtInRow?.classList.contains("sm:grid-cols-[auto_minmax(0,1fr)_auto]")).toBe(true);
  635. expect(builtInRow?.lastElementChild?.classList.contains("col-span-2")).toBe(true);
  636. expect(builtInRow?.lastElementChild?.classList.contains("sm:col-span-1")).toBe(true);
  637. expect(userRow?.classList.contains("grid-cols-[auto_minmax(0,1fr)_auto]")).toBe(true);
  638. expect(userRow?.classList.contains("sm:grid-cols-[auto_minmax(0,1fr)_auto]")).toBe(false);
  639. expect(userRow?.lastElementChild?.classList.contains("shrink-0")).toBe(true);
  640. expect(userRow?.lastElementChild?.classList.contains("col-span-2")).toBe(false);
  641. expect(capturedModelConfigSelects).toEqual([
  642. expect.objectContaining({
  643. normalizedValue: "inherit",
  644. showManageModelsAction: false,
  645. triggerLabel: "Inherit default",
  646. contentSide: "top",
  647. contentAlign: "end",
  648. }),
  649. ]);
  650. });
  651. it("offers disabled without implicitly selecting it when reasoning is missing", async () => {
  652. const plainModel = "custom:custom-openai:plain-chat";
  653. const customAgent = {
  654. id: "user:plain-reviewer",
  655. name: "plain-reviewer",
  656. description: "Review without reasoning",
  657. systemPrompt: "Review.",
  658. path: "/tmp/agents/plain-reviewer.md",
  659. scope: "user",
  660. source: "user",
  661. enabled: true,
  662. readOnly: false,
  663. modelSelection: { providerId: "custom-openai", modelId: "plain-chat" },
  664. tools: ["Read"],
  665. };
  666. stateOverrides = new Map<number, unknown>([
  667. [
  668. 1,
  669. [
  670. {
  671. id: "built-in:explore",
  672. name: "Explore",
  673. description: "Search broadly",
  674. systemPrompt: "Search.",
  675. path: "built-in:Explore",
  676. scope: "built-in",
  677. source: "built-in",
  678. enabled: true,
  679. readOnly: true,
  680. modelSelection: { providerId: "custom-openai", modelId: "plain-chat" },
  681. modelSelectionOverride: { providerId: "custom-openai", modelId: "plain-chat" },
  682. tools: ["Read"],
  683. },
  684. ],
  685. ],
  686. [2, { userScopeAvailable: true }],
  687. ]);
  688. await renderSubagentsSection();
  689. expect(capturedModelConfigSelects).toEqual([
  690. expect.objectContaining({ normalizedValue: plainModel }),
  691. ]);
  692. expect(capturedThoughtLevelControls).toEqual([
  693. expect.objectContaining({
  694. option: expect.objectContaining({
  695. currentValue: "",
  696. options: [{ value: "disabled", name: "disabled" }],
  697. }),
  698. }),
  699. ]);
  700. capturedModelConfigSelects.length = 0;
  701. capturedThoughtLevelControls.length = 0;
  702. stateOverrides = new Map<number, unknown>([
  703. [1, []],
  704. [2, { userScopeAvailable: true }],
  705. [7, true],
  706. [8, customAgent],
  707. ]);
  708. await renderSubagentsSection();
  709. expect(capturedModelConfigSelects).toEqual([
  710. expect.objectContaining({ normalizedValue: plainModel }),
  711. ]);
  712. expect(capturedThoughtLevelControls).toEqual([
  713. expect.objectContaining({
  714. option: expect.objectContaining({ currentValue: "" }),
  715. }),
  716. ]);
  717. });
  718. it("shows built-in overrides and persists model changes through the subagents service", async () => {
  719. stateOverrides = new Map<number, unknown>([
  720. [
  721. 1,
  722. [
  723. {
  724. id: "built-in:general-purpose",
  725. name: "general-purpose",
  726. description: "General-purpose agent",
  727. systemPrompt: "",
  728. path: "built-in:general-purpose",
  729. scope: "built-in",
  730. source: "built-in",
  731. enabled: true,
  732. readOnly: true,
  733. tools: ["*"],
  734. },
  735. {
  736. id: "built-in:explore",
  737. name: "Explore",
  738. description: "Search broadly",
  739. systemPrompt: "",
  740. path: "built-in:Explore",
  741. scope: "built-in",
  742. source: "built-in",
  743. enabled: true,
  744. readOnly: true,
  745. modelSelection: {
  746. providerId: "custom-openai",
  747. modelId: "glm-5.2",
  748. options: { reasoningLevel: "high" },
  749. },
  750. modelSelectionOverride: {
  751. providerId: "custom-openai",
  752. modelId: "glm-5.2",
  753. options: { reasoningLevel: "high" },
  754. },
  755. tools: ["Read"],
  756. },
  757. ],
  758. ],
  759. [2, { userScopeAvailable: true }],
  760. ]);
  761. const html = await renderSubagentsSection();
  762. const generalPurposePicker = capturedModelConfigSelects.find(
  763. (picker) => picker.triggerLabel === "Inherit default",
  764. );
  765. const explorePicker = capturedModelConfigSelects.find(
  766. (picker) => picker.normalizedValue === "custom:custom-openai:glm-5.2",
  767. );
  768. expect(html).toContain("Inherit default");
  769. expect(explorePicker).toMatchObject({
  770. normalizedValue: "custom:custom-openai:glm-5.2",
  771. triggerLabel: "glm-5.2",
  772. showManageModelsAction: false,
  773. });
  774. expect(explorePicker?.tooltipTitle).toBeUndefined();
  775. expect(explorePicker?.footerActions).toContainEqual(
  776. expect.objectContaining({
  777. key: "subagent-model:built-in-default",
  778. label: "Inherit default",
  779. selected: false,
  780. }),
  781. );
  782. expect(generalPurposePicker?.onValueChange).toBeTypeOf("function");
  783. await (generalPurposePicker!.onValueChange as (value: string) => Promise<void>)(
  784. "custom:custom-openai:gpt-5.4",
  785. );
  786. expect(mockSubagentsService.setBuiltInModelOverride).toHaveBeenCalledWith({
  787. agentName: "general-purpose",
  788. modelSelection: {
  789. providerId: "custom-openai",
  790. modelId: "gpt-5.4",
  791. options: { reasoningLevel: "high" },
  792. },
  793. });
  794. await waitFor(() =>
  795. expect(mockSubagentsService.list).toHaveBeenCalledWith({
  796. workspacePath: "",
  797. workspaceIdentity: undefined,
  798. provider: "glm",
  799. mode: "settingsUserOnly",
  800. }),
  801. );
  802. });
  803. it("persists changed and explicitly selected built-in reasoning efforts", async () => {
  804. stateOverrides = new Map<number, unknown>([
  805. [
  806. 1,
  807. [
  808. {
  809. id: "built-in:explore",
  810. name: "Explore",
  811. description: "Search broadly",
  812. systemPrompt: "",
  813. path: "built-in:Explore",
  814. scope: "built-in",
  815. source: "built-in",
  816. enabled: true,
  817. readOnly: true,
  818. modelSelection: { providerId: "custom-openai", modelId: "gpt-5.4" },
  819. modelSelectionOverride: { providerId: "custom-openai", modelId: "gpt-5.4" },
  820. tools: ["Read"],
  821. },
  822. ],
  823. ],
  824. [2, { userScopeAvailable: true }],
  825. ]);
  826. await renderSubagentsSection();
  827. const effortControl = capturedThoughtLevelControls[0];
  828. if (!effortControl) {
  829. throw new Error("Expected the built-in reasoning effort control to render");
  830. }
  831. expect(effortControl.option).toMatchObject({
  832. // 原选择未保存档位时保持空;下面显式选择 high/low 才写入。
  833. currentValue: "",
  834. options: [{ value: "low" }, { value: "high" }],
  835. });
  836. expect(effortControl.onCurrentValueCommit).toBeTypeOf("function");
  837. (effortControl.onCurrentValueCommit as (value: string) => void)("high");
  838. await waitFor(() => {
  839. expect(mockSubagentsService.setBuiltInModelOverride).toHaveBeenCalledWith({
  840. agentName: "Explore",
  841. modelSelection: {
  842. providerId: "custom-openai",
  843. modelId: "gpt-5.4",
  844. options: { reasoningLevel: "high" },
  845. },
  846. });
  847. });
  848. mockSubagentsService.setBuiltInModelOverride.mockClear();
  849. (effortControl.onValueChange as (value: string) => void)("low");
  850. await waitFor(() => {
  851. expect(mockSubagentsService.setBuiltInModelOverride).toHaveBeenCalledWith({
  852. agentName: "Explore",
  853. modelSelection: {
  854. providerId: "custom-openai",
  855. modelId: "gpt-5.4",
  856. options: { reasoningLevel: "low" },
  857. },
  858. });
  859. });
  860. });
  861. it("renders the shared model override control for plugin subagents and persists by agent id", async () => {
  862. // 插件文件只读;保存用户覆盖时沿用完整 Selection 和主动选模最高档,而非上游的旧双字段。
  863. const selection = {
  864. providerId: "custom-openai",
  865. modelId: "glm-5.2",
  866. options: { reasoningLevel: "high" },
  867. };
  868. const pluginAgent = {
  869. id: "plugin:document-skills@zcode-plugins-official:judge",
  870. name: "document-skills:judge",
  871. description: "Visual acceptance reviewer",
  872. systemPrompt: "Judge.",
  873. path: "/cache/document-skills/0.1.4/agents/judge.md",
  874. scope: "user",
  875. source: "plugin",
  876. pluginId: "document-skills@zcode-plugins-official",
  877. pluginName: "document-skills",
  878. enabled: true,
  879. readOnly: true,
  880. tools: ["Read", "Bash"],
  881. defaultModelSelection: { providerId: "custom-openai", modelId: "gpt-5.4" },
  882. modelSelection: selection,
  883. modelSelectionOverride: selection,
  884. };
  885. stateOverrides = new Map<number, unknown>([
  886. [1, [pluginAgent]],
  887. [2, { userScopeAvailable: true }],
  888. ]);
  889. const container = document.createElement("div");
  890. container.innerHTML = await renderSubagentsSection();
  891. const row = container.querySelector(
  892. `[data-testid="${testId(TID_SUBAGENT_ROW, pluginAgent.name)}"]`,
  893. );
  894. expect(row?.getAttribute("role")).toBeNull();
  895. expect(row?.classList.contains("sm:grid-cols-[auto_minmax(0,1fr)_auto]")).toBe(true);
  896. expect(
  897. container.querySelector(
  898. `[data-testid="${testId(TID_SUBAGENT_BUILT_IN_MODEL_TRIGGER, pluginAgent.name)}"]`,
  899. ),
  900. ).not.toBeNull();
  901. const picker = capturedModelConfigSelects.find(
  902. (candidate) => candidate.normalizedValue === "custom:custom-openai:glm-5.2",
  903. );
  904. expect(picker).toMatchObject({ triggerLabel: "glm-5.2", showManageModelsAction: false });
  905. (picker!.onValueChange as (value: string) => void)("custom:custom-openai:gpt-5.4");
  906. await waitFor(() =>
  907. expect(mockSubagentsService.setPluginAgentModelOverride).toHaveBeenCalledWith({
  908. agentId: pluginAgent.id,
  909. modelSelection: {
  910. providerId: "custom-openai",
  911. modelId: "gpt-5.4",
  912. options: { reasoningLevel: "high" },
  913. },
  914. }),
  915. );
  916. expect(mockSubagentsService.setBuiltInModelOverride).not.toHaveBeenCalled();
  917. expect(mockSubagentsService.list).toHaveBeenCalled();
  918. });
  919. it("uses the new model's highest effort when the built-in model changes", async () => {
  920. stateOverrides = new Map<number, unknown>([
  921. [
  922. 1,
  923. [
  924. {
  925. id: "built-in:explore",
  926. name: "Explore",
  927. description: "Search broadly",
  928. systemPrompt: "",
  929. path: "built-in:Explore",
  930. scope: "built-in",
  931. source: "built-in",
  932. enabled: true,
  933. readOnly: true,
  934. modelSelection: {
  935. providerId: "custom-openai",
  936. modelId: "glm-5.2",
  937. options: { reasoningLevel: "low" },
  938. },
  939. modelSelectionOverride: {
  940. providerId: "custom-openai",
  941. modelId: "glm-5.2",
  942. options: { reasoningLevel: "low" },
  943. },
  944. tools: ["Read"],
  945. },
  946. ],
  947. ],
  948. [2, { userScopeAvailable: true }],
  949. ]);
  950. await renderSubagentsSection();
  951. const picker = capturedModelConfigSelects.find(
  952. (candidate) => candidate.normalizedValue === "custom:custom-openai:glm-5.2",
  953. );
  954. const onValueChange = picker?.onValueChange as (value: string) => void;
  955. onValueChange("custom:custom-openai:glm-5.2");
  956. expect(mockSubagentsService.setBuiltInModelOverride).not.toHaveBeenCalled();
  957. onValueChange("custom:custom-openai:gpt-5.4");
  958. await waitFor(() => {
  959. expect(mockSubagentsService.setBuiltInModelOverride).toHaveBeenCalledWith({
  960. agentName: "Explore",
  961. modelSelection: {
  962. providerId: "custom-openai",
  963. modelId: "gpt-5.4",
  964. options: { reasoningLevel: "high" },
  965. },
  966. });
  967. });
  968. });
  969. it("restores the previous built-in model config when persistence fails", async () => {
  970. const agent = {
  971. id: "built-in:explore",
  972. name: "Explore",
  973. description: "Search broadly",
  974. systemPrompt: "",
  975. path: "built-in:Explore",
  976. scope: "built-in" as const,
  977. source: "built-in" as const,
  978. enabled: true,
  979. readOnly: true,
  980. modelSelection: {
  981. providerId: "custom-openai",
  982. modelId: "glm-5.2",
  983. options: { reasoningLevel: "high" },
  984. },
  985. modelSelectionOverride: {
  986. providerId: "custom-openai",
  987. modelId: "glm-5.2",
  988. options: { reasoningLevel: "high" },
  989. },
  990. tools: ["Read"],
  991. };
  992. mockSubagentsService.list.mockResolvedValue({
  993. agents: [agent],
  994. userAgents: [agent],
  995. pluginAgents: [],
  996. capability: { userScopeAvailable: true },
  997. });
  998. let rejectWrite: ((reason?: unknown) => void) | undefined;
  999. mockSubagentsService.setBuiltInModelOverride.mockImplementationOnce(
  1000. () =>
  1001. new Promise<void>((_resolve, reject) => {
  1002. rejectWrite = reject;
  1003. }),
  1004. );
  1005. await renderInteractiveSubagentsSection();
  1006. await waitFor(() => {
  1007. expect(
  1008. capturedModelConfigSelects.some(
  1009. (candidate) => candidate.normalizedValue === "custom:custom-openai:glm-5.2",
  1010. ),
  1011. ).toBe(true);
  1012. });
  1013. const initialPicker = capturedModelConfigSelects.findLast(
  1014. (candidate) => candidate.normalizedValue === "custom:custom-openai:glm-5.2",
  1015. );
  1016. const onModelValueChange = initialPicker?.onValueChange;
  1017. expect(onModelValueChange).toBeTypeOf("function");
  1018. const beforeOptimisticRender = capturedModelConfigSelects.length;
  1019. act(() => {
  1020. (onModelValueChange as (value: string) => void)("custom:custom-openai:gpt-5.4");
  1021. });
  1022. await waitFor(() => {
  1023. expect(
  1024. capturedModelConfigSelects
  1025. .slice(beforeOptimisticRender)
  1026. .some((candidate) => candidate.normalizedValue === "custom:custom-openai:gpt-5.4"),
  1027. ).toBe(true);
  1028. });
  1029. expect(rejectWrite).toBeTypeOf("function");
  1030. const beforeRollbackRender = capturedModelConfigSelects.length;
  1031. const beforeThoughtRollbackRender = capturedThoughtLevelControls.length;
  1032. await act(async () => {
  1033. rejectWrite!(new Error("write failed"));
  1034. await Promise.resolve();
  1035. });
  1036. await waitFor(() => {
  1037. expect(
  1038. capturedModelConfigSelects
  1039. .slice(beforeRollbackRender)
  1040. .some((candidate) => candidate.normalizedValue === "custom:custom-openai:glm-5.2"),
  1041. ).toBe(true);
  1042. expect(
  1043. capturedThoughtLevelControls
  1044. .slice(beforeThoughtRollbackRender)
  1045. .some((candidate) => candidate.option?.currentValue === "high"),
  1046. ).toBe(true);
  1047. });
  1048. });
  1049. it("keeps the committed built-in config when the follow-up refresh fails", async () => {
  1050. const agent = {
  1051. id: "built-in:explore",
  1052. name: "Explore",
  1053. description: "Search broadly",
  1054. systemPrompt: "",
  1055. path: "built-in:Explore",
  1056. scope: "built-in" as const,
  1057. source: "built-in" as const,
  1058. enabled: true,
  1059. readOnly: true,
  1060. modelSelection: {
  1061. providerId: "custom-openai",
  1062. modelId: "glm-5.2",
  1063. options: { reasoningLevel: "high" },
  1064. },
  1065. modelSelectionOverride: {
  1066. providerId: "custom-openai",
  1067. modelId: "glm-5.2",
  1068. options: { reasoningLevel: "high" },
  1069. },
  1070. tools: ["Read"],
  1071. };
  1072. mockSubagentsService.list.mockResolvedValue({
  1073. agents: [agent],
  1074. userAgents: [agent],
  1075. pluginAgents: [],
  1076. capability: { userScopeAvailable: true },
  1077. });
  1078. mockRefreshLoadedSubagentsStoreForWorkspace.mockRejectedValueOnce(new Error("refresh failed"));
  1079. let resolveWrite: (() => void) | undefined;
  1080. mockSubagentsService.setBuiltInModelOverride.mockImplementationOnce(
  1081. () =>
  1082. new Promise<void>((resolve) => {
  1083. resolveWrite = resolve;
  1084. }),
  1085. );
  1086. await renderInteractiveSubagentsSection();
  1087. await waitFor(() => {
  1088. expect(capturedThoughtLevelControls.at(-1)?.option).toMatchObject({
  1089. currentValue: "high",
  1090. });
  1091. });
  1092. const onThoughtLevelChange = capturedThoughtLevelControls.at(-1)?.onValueChange;
  1093. expect(onThoughtLevelChange).toBeTypeOf("function");
  1094. act(() => {
  1095. (onThoughtLevelChange as (value: string) => void)("max");
  1096. });
  1097. await waitFor(() => {
  1098. expect(mockSubagentsService.setBuiltInModelOverride).toHaveBeenCalledWith({
  1099. agentName: "Explore",
  1100. modelSelection: {
  1101. providerId: "custom-openai",
  1102. modelId: "glm-5.2",
  1103. options: { reasoningLevel: "max" },
  1104. },
  1105. });
  1106. expect(capturedThoughtLevelControls.at(-1)).toMatchObject({
  1107. disabled: true,
  1108. option: expect.objectContaining({ currentValue: "max" }),
  1109. });
  1110. });
  1111. expect(resolveWrite).toBeTypeOf("function");
  1112. // 显式控制持久化提交点,避免慢速 CI 中乐观渲染与后续刷新微任务乱序。
  1113. await act(async () => {
  1114. resolveWrite!();
  1115. await Promise.resolve();
  1116. });
  1117. await waitFor(() => {
  1118. expect(mockRefreshLoadedSubagentsStoreForWorkspace).toHaveBeenCalledTimes(1);
  1119. expect(capturedThoughtLevelControls.at(-1)).toMatchObject({
  1120. disabled: false,
  1121. option: expect.objectContaining({ currentValue: "max" }),
  1122. });
  1123. });
  1124. });
  1125. it("clears built-in model overrides through the default model item", async () => {
  1126. stateOverrides = new Map<number, unknown>([
  1127. [
  1128. 1,
  1129. [
  1130. {
  1131. id: "built-in:explore",
  1132. name: "Explore",
  1133. description: "Search broadly",
  1134. systemPrompt: "",
  1135. path: "built-in:Explore",
  1136. scope: "built-in",
  1137. source: "built-in",
  1138. enabled: true,
  1139. readOnly: true,
  1140. modelSelection: { providerId: "custom-openai", modelId: "glm-5.2" },
  1141. modelSelectionOverride: { providerId: "custom-openai", modelId: "glm-5.2" },
  1142. tools: ["Read"],
  1143. },
  1144. ],
  1145. ],
  1146. [2, { userScopeAvailable: true }],
  1147. ]);
  1148. await renderSubagentsSection();
  1149. const explorePicker = capturedModelConfigSelects.find(
  1150. (picker) => picker.normalizedValue === "custom:custom-openai:glm-5.2",
  1151. );
  1152. const defaultAction = (
  1153. explorePicker?.footerActions as
  1154. | Array<{ key: string; onSelect?: () => Promise<void> | void }>
  1155. | undefined
  1156. )?.find((action) => action.key === "subagent-model:built-in-default");
  1157. expect(defaultAction?.onSelect).toBeTypeOf("function");
  1158. await defaultAction!.onSelect!();
  1159. expect(mockSubagentsService.setBuiltInModelOverride).toHaveBeenCalledWith({
  1160. agentName: "Explore",
  1161. modelSelection: undefined,
  1162. });
  1163. });
  1164. it("keeps the saved label when a built-in model override is no longer available", async () => {
  1165. const staleModel = "custom:retired-provider:GLM-5-Turbo";
  1166. stateOverrides = new Map<number, unknown>([
  1167. [
  1168. 1,
  1169. [
  1170. {
  1171. id: "built-in:general-purpose",
  1172. name: "general-purpose",
  1173. description: "General-purpose agent",
  1174. systemPrompt: "",
  1175. path: "built-in:general-purpose",
  1176. scope: "built-in",
  1177. source: "built-in",
  1178. enabled: true,
  1179. readOnly: true,
  1180. modelSelection: { providerId: "retired-provider", modelId: "GLM-5-Turbo" },
  1181. modelSelectionOverride: {
  1182. providerId: "retired-provider",
  1183. modelId: "GLM-5-Turbo",
  1184. },
  1185. tools: ["*"],
  1186. },
  1187. ],
  1188. ],
  1189. [2, { userScopeAvailable: true }],
  1190. ]);
  1191. await renderSubagentsSection();
  1192. expect(capturedModelConfigSelects).toContainEqual(
  1193. expect.objectContaining({
  1194. normalizedValue: staleModel,
  1195. triggerLabel: "Select model",
  1196. showManageModelsAction: false,
  1197. }),
  1198. );
  1199. expect(capturedModelConfigSelects).not.toContainEqual(
  1200. expect.objectContaining({
  1201. triggerLabel: "GLM-5-Turbo",
  1202. }),
  1203. );
  1204. const stalePicker = capturedModelConfigSelects.find(
  1205. (picker) => picker.normalizedValue === staleModel,
  1206. );
  1207. const selectableValues = ((stalePicker?.modelGroups ?? []) as ModelSelectGroup[]).flatMap(
  1208. (group) => group.items.map((item) => item.value),
  1209. );
  1210. expect(selectableValues).not.toContain(staleModel);
  1211. });
  1212. it("renders tools permissions using the workspace-access row pattern", async () => {
  1213. stateOverrides = new Map<number, unknown>([
  1214. [2, { userScopeAvailable: true }],
  1215. [7, true],
  1216. ]);
  1217. const html = await renderSubagentsSection();
  1218. expect(html).toContain("settings.subagents.form.tools.card.title");
  1219. expect(html).toContain("settings.subagents.form.tools.mode.all");
  1220. expect(html).toContain("settings.subagents.form.tools.mode.custom");
  1221. expect(html).toContain("settings.scope.label");
  1222. expect(html).toContain("scope");
  1223. expect(html).not.toContain('role="checkbox"');
  1224. expect(html).not.toContain("Bash(git diff *)");
  1225. });
  1226. it("uses the real chat toolbar model picker values with an inherit option in the form", async () => {
  1227. stateOverrides = new Map<number, unknown>([
  1228. [2, { userScopeAvailable: true }],
  1229. [7, true],
  1230. ]);
  1231. const html = await renderSubagentsSection();
  1232. const modelPicker = capturedModelConfigSelects.at(-1);
  1233. const modelGroups = modelPicker?.modelGroups as
  1234. | Array<{
  1235. key: string;
  1236. label?: string;
  1237. items: Array<{ value: string; name: string }>;
  1238. }>
  1239. | undefined;
  1240. const modelValues = modelGroups?.flatMap((group) => group.items.map((item) => item.value));
  1241. expect(html).toContain("Inherit default");
  1242. expect(modelPicker).toMatchObject({
  1243. normalizedValue: "inherit",
  1244. triggerLabel: "Inherit default",
  1245. showManageModelsAction: true,
  1246. manageModelsLabel: "Manage models",
  1247. contentSide: "bottom",
  1248. triggerClassName: expect.stringContaining("bg-clip-border"),
  1249. });
  1250. expect(modelValues).toEqual([
  1251. "custom:custom-openai:gpt-5.4",
  1252. "custom:custom-openai:glm-5.2",
  1253. "custom:custom-openai:plain-chat",
  1254. ]);
  1255. expect(modelPicker?.footerActions).toContainEqual(
  1256. expect.objectContaining({
  1257. key: "subagent-model:inherit",
  1258. label: "Inherit default",
  1259. selected: true,
  1260. }),
  1261. );
  1262. expect(modelValues).not.toContain("main");
  1263. expect(modelValues).not.toContain("lite");
  1264. expect(modelValues).not.toContain("inherit");
  1265. expect(modelPicker?.onManageModels).toBe(onManageModels);
  1266. expect(mockUseModelProviders).not.toHaveBeenCalled();
  1267. });
  1268. it("derives refreshed edit form state from the saved custom model value", async () => {
  1269. const { createSubagentFormInitialState } = await import("../src/settings/SubagentsSection.js");
  1270. const customModel = "custom:728858ba-605a-4be5-80f8-15cf4de51eae:mimo-v2.5-pro";
  1271. const formState = createSubagentFormInitialState({
  1272. name: "qa-reviewer",
  1273. description: "Review product flows",
  1274. systemPrompt: "Review carefully",
  1275. color: "blue",
  1276. modelSelection: {
  1277. providerId: "728858ba-605a-4be5-80f8-15cf4de51eae",
  1278. modelId: "mimo-v2.5-pro",
  1279. options: { reasoningLevel: "high" },
  1280. },
  1281. tools: ["Read", "Grep"],
  1282. });
  1283. expect(formState.model).toBe(customModel);
  1284. expect(formState.thoughtLevel).toBe("high");
  1285. expect(formState.injectAgentsMd).toBe(true);
  1286. expect(formState.inheritAllTools).toBe(false);
  1287. expect(formState.selectedTools).toEqual(["Read", "Grep"]);
  1288. });
  1289. it("preserves unknown intent and leaves an unsupported resolved effort unselected", async () => {
  1290. const {
  1291. createSubagentFormInitialState,
  1292. isSubagentThoughtLevelAvailable,
  1293. resolveSubagentThoughtOptionState,
  1294. } = await import("../src/settings/SubagentsSection.js");
  1295. const model = "custom:custom-openai:gpt-5.4";
  1296. const initial = createSubagentFormInitialState({
  1297. name: "qa-reviewer",
  1298. description: "Review product flows",
  1299. systemPrompt: "Review carefully",
  1300. modelSelection: {
  1301. providerId: "custom-openai",
  1302. modelId: "gpt-5.4",
  1303. options: { reasoningLevel: "medium" },
  1304. },
  1305. });
  1306. expect(initial.thoughtLevel).toBe("medium");
  1307. const unknownState = resolveSubagentThoughtOptionState({
  1308. model,
  1309. modelAvailable: true,
  1310. modelSelectionView: null,
  1311. modelSelectionLoading: true,
  1312. thoughtLevel: initial.thoughtLevel,
  1313. });
  1314. expect(unknownState).toEqual({ kind: "unknown", status: "loading" });
  1315. expect(isSubagentThoughtLevelAvailable(unknownState, initial.thoughtLevel)).toBe(true);
  1316. const supportedState = resolveSubagentThoughtOptionState({
  1317. model,
  1318. modelAvailable: true,
  1319. modelSelectionView: mockModelSelectionView,
  1320. modelSelectionLoading: false,
  1321. thoughtLevel: initial.thoughtLevel,
  1322. });
  1323. expect(supportedState.option?.currentValue).toBe("");
  1324. expect(initial.thoughtLevel).toBe("medium");
  1325. expect(isSubagentThoughtLevelAvailable(supportedState, initial.thoughtLevel)).toBe(false);
  1326. expect(isSubagentThoughtLevelAvailable(supportedState, "high")).toBe(true);
  1327. });
  1328. it("uses only the Local Host selection view to resolve reasoning", async () => {
  1329. const { resolveSubagentThoughtOptionState } =
  1330. await import("../src/settings/SubagentsSection.js");
  1331. const model = "custom:custom-openai:glm-5.2";
  1332. const state = resolveSubagentThoughtOptionState({
  1333. model,
  1334. modelAvailable: true,
  1335. modelSelectionView: mockModelSelectionView,
  1336. modelSelectionLoading: false,
  1337. thoughtLevel: undefined,
  1338. });
  1339. expect(state).toMatchObject({
  1340. kind: "supported",
  1341. option: {
  1342. currentValue: "",
  1343. options: [{ value: "high" }, { value: "max" }],
  1344. },
  1345. });
  1346. });
  1347. it.each(["idle", "loading", "error"] as const)(
  1348. "ignores the retired workspace catalog when its status is %s",
  1349. async (workspaceConfigStatus) => {
  1350. stateOverrides = new Map<number, unknown>([
  1351. [
  1352. 1,
  1353. [
  1354. {
  1355. id: "built-in:explore",
  1356. name: "Explore",
  1357. description: "Search broadly",
  1358. systemPrompt: "",
  1359. path: "built-in:Explore",
  1360. scope: "built-in",
  1361. source: "built-in",
  1362. enabled: true,
  1363. readOnly: true,
  1364. modelSelection: { providerId: "custom-openai", modelId: "gpt-5.4" },
  1365. modelSelectionOverride: { providerId: "custom-openai", modelId: "gpt-5.4" },
  1366. tools: ["Read"],
  1367. },
  1368. ],
  1369. ],
  1370. [2, { userScopeAvailable: true }],
  1371. ]);
  1372. mockToolbarConfigState.status = workspaceConfigStatus;
  1373. await renderSubagentsSection();
  1374. expect(capturedThoughtLevelControls).toHaveLength(1);
  1375. expect(capturedThoughtLevelControls[0]?.option).toMatchObject({ currentValue: "" });
  1376. },
  1377. );
  1378. it("uses only the Local Host view to resolve reasoning capability", async () => {
  1379. const { isSubagentThoughtLevelAvailable, resolveSubagentThoughtOptionState } =
  1380. await import("../src/settings/SubagentsSection.js");
  1381. const base = {
  1382. model: "custom:custom-openai:gpt-5.4",
  1383. modelAvailable: true,
  1384. modelSelectionLoading: false,
  1385. thoughtLevel: undefined,
  1386. };
  1387. const loading = resolveSubagentThoughtOptionState({
  1388. ...base,
  1389. modelSelectionView: null,
  1390. modelSelectionLoading: true,
  1391. });
  1392. expect(loading).toEqual({ kind: "unknown", status: "loading" });
  1393. // Registry 尚未发布时保持未知,不能把已保存的档位误判为非法并清空。
  1394. expect(isSubagentThoughtLevelAvailable(loading, "max")).toBe(true);
  1395. const error = resolveSubagentThoughtOptionState({
  1396. ...base,
  1397. modelSelectionView: null,
  1398. });
  1399. expect(error).toEqual({ kind: "unsupported" });
  1400. const targetModelMissing = resolveSubagentThoughtOptionState({
  1401. ...base,
  1402. model: "custom:custom-openai:other-model",
  1403. thoughtLevel: "max",
  1404. modelSelectionView: mockModelSelectionView,
  1405. });
  1406. expect(targetModelMissing).toEqual({ kind: "unsupported" });
  1407. expect(isSubagentThoughtLevelAvailable(targetModelMissing, "max")).toBe(false);
  1408. const targetModelReconciling = resolveSubagentThoughtOptionState({
  1409. ...base,
  1410. thoughtLevel: "max",
  1411. modelSelectionView: null,
  1412. modelSelectionLoading: true,
  1413. });
  1414. expect(targetModelReconciling).toEqual({ kind: "unknown", status: "loading" });
  1415. const authoritative = resolveSubagentThoughtOptionState({
  1416. ...base,
  1417. modelSelectionView: mockModelSelectionView,
  1418. });
  1419. expect(authoritative).toMatchObject({
  1420. kind: "supported",
  1421. option: {
  1422. currentValue: "",
  1423. options: [{ value: "low" }, { value: "high" }],
  1424. },
  1425. });
  1426. });
  1427. it("does not let retired workspace loading state override Local Host capability", async () => {
  1428. stateOverrides = new Map<number, unknown>([
  1429. [
  1430. 1,
  1431. [
  1432. {
  1433. id: "built-in:explore",
  1434. name: "Explore",
  1435. description: "Search broadly",
  1436. systemPrompt: "",
  1437. path: "built-in:Explore",
  1438. scope: "built-in",
  1439. source: "built-in",
  1440. enabled: true,
  1441. readOnly: true,
  1442. modelSelection: { providerId: "custom-openai", modelId: "plain-chat" },
  1443. modelSelectionOverride: { providerId: "custom-openai", modelId: "plain-chat" },
  1444. tools: ["Read"],
  1445. },
  1446. ],
  1447. ],
  1448. [2, { userScopeAvailable: true }],
  1449. ]);
  1450. mockToolbarConfigState.status = "loading";
  1451. const html = await renderSubagentsSection();
  1452. expect(capturedThoughtLevelControls).toEqual([
  1453. expect.objectContaining({
  1454. option: expect.objectContaining({ currentValue: "" }),
  1455. }),
  1456. ]);
  1457. expect(html).not.toContain('data-subagent-thought-level-loading="true"');
  1458. });
  1459. it("does not let retired workspace error state override Local Host capability", async () => {
  1460. stateOverrides = new Map<number, unknown>([
  1461. [
  1462. 1,
  1463. [
  1464. {
  1465. id: "built-in:explore",
  1466. name: "Explore",
  1467. description: "Search broadly",
  1468. systemPrompt: "",
  1469. path: "built-in:Explore",
  1470. scope: "built-in",
  1471. source: "built-in",
  1472. enabled: true,
  1473. readOnly: true,
  1474. modelSelection: { providerId: "custom-openai", modelId: "plain-chat" },
  1475. modelSelectionOverride: { providerId: "custom-openai", modelId: "plain-chat" },
  1476. tools: ["Read"],
  1477. },
  1478. ],
  1479. ],
  1480. [2, { userScopeAvailable: true }],
  1481. ]);
  1482. mockToolbarConfigState.status = "error";
  1483. const html = await renderSubagentsSection();
  1484. expect(capturedThoughtLevelControls).toEqual([
  1485. expect.objectContaining({
  1486. option: expect.objectContaining({ currentValue: "" }),
  1487. }),
  1488. ]);
  1489. expect(html).not.toContain('data-subagent-thought-level-unavailable="true"');
  1490. expect(html).not.toContain('data-subagent-thought-level-loading="true"');
  1491. });
  1492. it("uses the Registry selection view while it refreshes when there is no workspace", async () => {
  1493. const { resolveSubagentThoughtOptionState } =
  1494. await import("../src/settings/SubagentsSection.js");
  1495. const base = {
  1496. model: "custom:custom-openai:gpt-5.4",
  1497. modelAvailable: true,
  1498. modelSelectionView: {
  1499. revision: 1,
  1500. providers: [
  1501. {
  1502. providerId: "custom-openai",
  1503. config: {},
  1504. models: [
  1505. {
  1506. modelId: "gpt-5.4",
  1507. config: {
  1508. optionSpecs: {
  1509. reasoningLevel: {
  1510. values: ["low", "high"],
  1511. map: "{}",
  1512. },
  1513. maxOutputTokens: { max: 32_000, map: "{}" },
  1514. },
  1515. },
  1516. },
  1517. ],
  1518. },
  1519. ],
  1520. },
  1521. thoughtLevel: undefined,
  1522. };
  1523. expect(
  1524. resolveSubagentThoughtOptionState({
  1525. ...base,
  1526. modelSelectionLoading: true,
  1527. }),
  1528. ).toMatchObject({
  1529. kind: "supported",
  1530. option: {
  1531. currentValue: "",
  1532. options: [{ value: "low" }, { value: "high" }],
  1533. },
  1534. });
  1535. expect(
  1536. resolveSubagentThoughtOptionState({
  1537. ...base,
  1538. modelSelectionLoading: false,
  1539. }),
  1540. ).toMatchObject({
  1541. kind: "supported",
  1542. option: {
  1543. currentValue: "",
  1544. options: [{ value: "low" }, { value: "high" }],
  1545. },
  1546. });
  1547. });
  1548. it("does not infer reasoning from the model name before the Registry view is available", async () => {
  1549. const { resolveSubagentThoughtOptionState } =
  1550. await import("../src/settings/SubagentsSection.js");
  1551. expect(
  1552. resolveSubagentThoughtOptionState({
  1553. model: encodeCustomModelValue("provider-demo", "GLM-5.2"),
  1554. modelAvailable: true,
  1555. modelSelectionView: null,
  1556. modelSelectionLoading: true,
  1557. thoughtLevel: undefined,
  1558. }),
  1559. ).toEqual({ kind: "unknown", status: "loading" });
  1560. });
  1561. it("uses the Registry disabled option instead of App metadata", async () => {
  1562. const { isSubagentThoughtLevelAvailable, resolveSubagentThoughtOptionState } =
  1563. await import("../src/settings/SubagentsSection.js");
  1564. const base = {
  1565. model: "custom:custom-openai:plain-chat",
  1566. modelAvailable: true,
  1567. modelSelectionView: mockModelSelectionView,
  1568. modelSelectionLoading: false,
  1569. thoughtLevel: "high",
  1570. };
  1571. const disabled = resolveSubagentThoughtOptionState(base);
  1572. expect(disabled).toMatchObject({
  1573. kind: "supported",
  1574. option: {
  1575. currentValue: "",
  1576. options: [{ value: "disabled" }],
  1577. },
  1578. });
  1579. expect(isSubagentThoughtLevelAvailable(disabled, "high")).toBe(false);
  1580. });
  1581. it("defers persisted model availability validation only during initial provider loading", async () => {
  1582. const { isSubagentModelAvailable } = await import("../src/settings/SubagentsSection.js");
  1583. const model = "custom:custom-anthropic:claude-opus-4-8";
  1584. expect(isSubagentModelAvailable([], model, true)).toBe(true);
  1585. expect(isSubagentModelAvailable([], model, false)).toBe(false);
  1586. });
  1587. it("defaults new and legacy custom agents to AGENTS.md injection and preserves false", async () => {
  1588. const { createSubagentFormInitialState } = await import("../src/settings/SubagentsSection.js");
  1589. expect(createSubagentFormInitialState().injectAgentsMd).toBe(true);
  1590. expect(
  1591. createSubagentFormInitialState({
  1592. name: "legacy-reviewer",
  1593. description: "Legacy profile",
  1594. systemPrompt: "Review carefully",
  1595. }).injectAgentsMd,
  1596. ).toBe(true);
  1597. expect(
  1598. createSubagentFormInitialState({
  1599. name: "isolated-reviewer",
  1600. description: "Do not inherit instructions",
  1601. systemPrompt: "Review carefully",
  1602. injectAgentsMd: false,
  1603. }).injectAgentsMd,
  1604. ).toBe(false);
  1605. });
  1606. it("saves AGENTS.md injection and an explicitly selected reasoning level", async () => {
  1607. mockSubagentsService.list.mockResolvedValue({
  1608. agents: [],
  1609. userAgents: [],
  1610. pluginAgents: [],
  1611. capability: { userScopeAvailable: true },
  1612. });
  1613. const view = await renderInteractiveSubagentsSection();
  1614. const [addButton] = await screen.findAllByRole("button", { name: "New" });
  1615. fireEvent.click(addButton);
  1616. const onModelChange = capturedModelConfigSelects.at(-1)?.onValueChange;
  1617. expect(onModelChange).toBeTypeOf("function");
  1618. act(() => {
  1619. (onModelChange as (value: string) => void)("custom:custom-openai:gpt-5.4");
  1620. });
  1621. await waitFor(() => {
  1622. expect(capturedThoughtLevelControls.at(-1)).toMatchObject({
  1623. // 主动选模使用最高档;后续显式选低档仍须按用户选择保存。
  1624. option: expect.objectContaining({ currentValue: "high" }),
  1625. onCurrentValueCommit: expect.any(Function),
  1626. });
  1627. });
  1628. const onCurrentValueCommit = capturedThoughtLevelControls.at(-1)?.onCurrentValueCommit;
  1629. expect(onCurrentValueCommit).toBeTypeOf("function");
  1630. act(() => {
  1631. (onCurrentValueCommit as (value: string) => void)("low");
  1632. });
  1633. const systemPromptInput = screen.getByPlaceholderText(
  1634. "settings.subagents.form.systemPrompt.placeholder",
  1635. );
  1636. const injectSwitch = screen.getByRole("switch", {
  1637. name: "Inject AGENTS.md",
  1638. });
  1639. expect(systemPromptInput.compareDocumentPosition(injectSwitch)).toBe(
  1640. Node.DOCUMENT_POSITION_FOLLOWING,
  1641. );
  1642. expect(injectSwitch.parentElement?.classList.contains("items-center")).toBe(true);
  1643. expect(screen.queryByText("Include parent user and workspace instructions.")).toBeNull();
  1644. expect((injectSwitch as HTMLInputElement).checked).toBe(true);
  1645. fireEvent.click(injectSwitch);
  1646. expect((injectSwitch as HTMLInputElement).checked).toBe(false);
  1647. fireEvent.change(screen.getByPlaceholderText("settings.subagents.form.name.placeholder"), {
  1648. target: { value: "isolated-reviewer" },
  1649. });
  1650. fireEvent.change(
  1651. screen.getByPlaceholderText("settings.subagents.form.description.placeholder"),
  1652. { target: { value: "Review without parent instructions" } },
  1653. );
  1654. fireEvent.change(
  1655. screen.getByPlaceholderText("settings.subagents.form.systemPrompt.placeholder"),
  1656. { target: { value: "Review carefully." } },
  1657. );
  1658. fireEvent.submit(view.container.querySelector("form")!);
  1659. await waitFor(() => {
  1660. expect(mockSubagentsService.createAgent).toHaveBeenCalledWith(
  1661. expect.objectContaining({
  1662. config: expect.objectContaining({
  1663. injectAgentsMd: false,
  1664. modelSelection: {
  1665. providerId: "custom-openai",
  1666. modelId: "gpt-5.4",
  1667. options: { reasoningLevel: "low" },
  1668. },
  1669. }),
  1670. }),
  1671. );
  1672. });
  1673. });
  1674. it("preserves the unavailable selection but prompts to select a model in the edit form", async () => {
  1675. const customModel = "custom:728858ba-605a-4be5-80f8-15cf4de51eae:mimo-v2.5-pro";
  1676. const agent = {
  1677. id: "user:qa-reviewer",
  1678. name: "qa-reviewer",
  1679. description: "Review product flows",
  1680. systemPrompt: "Review carefully",
  1681. color: "blue",
  1682. modelSelection: {
  1683. providerId: "728858ba-605a-4be5-80f8-15cf4de51eae",
  1684. modelId: "mimo-v2.5-pro",
  1685. },
  1686. tools: ["Read", "Grep"],
  1687. path: "/tmp/agents/qa-reviewer.md",
  1688. scope: "user",
  1689. source: "user",
  1690. enabled: true,
  1691. readOnly: false,
  1692. };
  1693. stateOverrides = new Map<number, unknown>([
  1694. [1, [agent]],
  1695. [2, { userScopeAvailable: true }],
  1696. [8, agent],
  1697. ]);
  1698. mockToolbarConfigState.status = "error";
  1699. const html = await renderSubagentsSection();
  1700. expect(capturedModelConfigSelects.at(-1)).toMatchObject({
  1701. normalizedValue: customModel,
  1702. triggerLabel: "Select model",
  1703. });
  1704. expect(capturedThoughtLevelControls).toHaveLength(0);
  1705. expect(html).not.toContain('data-subagent-thought-level-unavailable="true"');
  1706. });
  1707. it("treats unavailable persisted models as invalid form selections", async () => {
  1708. const { isSubagentModelAvailable } = await import("../src/settings/SubagentsSection.js");
  1709. const modelGroups = [
  1710. {
  1711. key: "custom-openai",
  1712. label: "Custom OpenAI",
  1713. items: [
  1714. {
  1715. key: "custom-openai:gpt-5.4",
  1716. value: "custom:custom-openai:gpt-5.4",
  1717. name: "gpt-5.4",
  1718. },
  1719. ],
  1720. },
  1721. ];
  1722. expect(isSubagentModelAvailable(modelGroups, "custom:missing:mimo-v2.5-pro")).toBe(false);
  1723. expect(isSubagentModelAvailable([], "custom:missing:mimo-v2.5-pro", true)).toBe(true);
  1724. expect(isSubagentModelAvailable(modelGroups, "custom:custom-openai:gpt-5.4")).toBe(true);
  1725. expect(isSubagentModelAvailable(modelGroups, "inherit")).toBe(true);
  1726. expect(isSubagentModelAvailable(modelGroups, undefined)).toBe(true);
  1727. });
  1728. it("groups editable user agents and read-only built-ins like command settings lists", async () => {
  1729. stateOverrides = new Map<number, unknown>([
  1730. [
  1731. 1,
  1732. [
  1733. {
  1734. id: "user:code-reviewer",
  1735. name: "code-reviewer",
  1736. description: "Review code",
  1737. systemPrompt: "Review code carefully",
  1738. color: "blue",
  1739. tools: ["Read", "Grep"],
  1740. path: "/tmp/agents/code-reviewer.md",
  1741. scope: "user",
  1742. source: "user",
  1743. enabled: true,
  1744. readOnly: false,
  1745. },
  1746. {
  1747. id: "built-in:general-purpose",
  1748. name: "general-purpose",
  1749. description: "General-purpose agent",
  1750. systemPrompt: "General agent",
  1751. path: "builtin://general-purpose",
  1752. scope: "built-in",
  1753. source: "built-in",
  1754. enabled: true,
  1755. readOnly: true,
  1756. },
  1757. ],
  1758. ],
  1759. [2, { userScopeAvailable: true }],
  1760. ]);
  1761. const html = await renderSubagentsSection();
  1762. expect(html).toContain("Installed");
  1763. expect(html).toContain("Built-in subagents");
  1764. expect(html).toContain("code-reviewer");
  1765. expect(html).not.toContain("/tmp/agents/code-reviewer.md");
  1766. expect(html).not.toContain("built-in:general-purpose");
  1767. expect(html).toContain("general-purpose");
  1768. expect(html).not.toContain("Workspace-level creation or editing is unsupported");
  1769. expect(findButton("New")).toBeDefined();
  1770. expect(findButton("Open user subagents folder")).toBeUndefined();
  1771. });
  1772. });