subagentsSection.test.ts 71 KB

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