v4ComposerToolbarRecovery.test.ts 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379
  1. import { act, createElement, type ComponentProps } from "react";
  2. import { createRoot, type Root } from "react-dom/client";
  3. import { renderToStaticMarkup } from "react-dom/server";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import { BUILTIN_MODEL_PROVIDER_IDS } from "@zcode/shared";
  6. import type { ProviderSettingsView } from "@zcode/services";
  7. import { TooltipProvider } from "@/components/ui/tooltip.js";
  8. import { V4ComposerModelControls } from "@/v4/composer/V4ComposerToolbar.js";
  9. import type { ModelConfigSelect } from "@/ModelConfigSelect.js";
  10. globalThis.IS_REACT_ACT_ENVIRONMENT = true;
  11. type ModelConfigSelectProps = ComponentProps<typeof ModelConfigSelect>;
  12. type V4ComposerModelControlsProps = ComponentProps<typeof V4ComposerModelControls>;
  13. const customValue = "custom:custom-openai:gpt-4o";
  14. const captured = vi.hoisted(() => ({
  15. modelSelectProps: null as ModelConfigSelectProps | null,
  16. thoughtControlProps: null as {
  17. indicatorClassName?: string;
  18. triggerClassName?: string;
  19. composerCollapsePriority?: number;
  20. onValueChange: (value: string) => void;
  21. option: { currentValue?: unknown; options?: Array<{ value: string }> };
  22. } | null,
  23. usageProps: [] as Array<Record<string, unknown>>,
  24. }));
  25. const mocks = vi.hoisted(() => ({
  26. codingPlanEntitlements: {} as Record<string, unknown>,
  27. codingPlanEntitlementsRefresh: vi.fn(async () => undefined),
  28. // 修复原因:context hover 的 start plan onAccess 按 enabledStartPlanProviderIds 挂载;
  29. // 默认空数组模拟 Start Plan 尚无独立 Account Access,需要入口的用例显式提供 provider id。
  30. codingPlanEntitlementsEnabledStartPlanIds: [] as string[],
  31. configOptions: [] as Array<Record<string, unknown>>,
  32. configOptionsError: true,
  33. enterpriseProducts: { snapshot: { productList: [] }, loading: false, error: null } as Record<
  34. string,
  35. unknown
  36. >,
  37. modelSelectionView: {
  38. revision: 1,
  39. providers: [
  40. {
  41. providerId: "custom-openai",
  42. providerName: "Custom OpenAI",
  43. config: {
  44. access: { type: "api-key", apiKey: "test-key" },
  45. api: {
  46. type: "openai-chat-completions",
  47. baseUrl: "https://api.example.com/v1",
  48. },
  49. models: ["gpt-4o"],
  50. },
  51. models: [
  52. {
  53. modelId: "gpt-4o",
  54. config: {
  55. optionSpecs: {
  56. reasoningLevel: { values: ["disabled"], map: "{}" },
  57. maxOutputTokens: { max: 32_000, map: "{}" },
  58. },
  59. },
  60. },
  61. ],
  62. },
  63. ],
  64. } as null | {
  65. revision: number;
  66. providers: Array<{
  67. providerId: string;
  68. providerName?: string;
  69. config: Record<string, unknown>;
  70. models: Array<{ modelId: string; config: Record<string, unknown> }>;
  71. }>;
  72. },
  73. providerSettingsView: {
  74. revision: 1,
  75. addableProviders: [],
  76. providerOrder: [],
  77. providers: [],
  78. } as ProviderSettingsView,
  79. recoverCustomModelSelection: vi.fn(async () => {}),
  80. selectModel: vi.fn(),
  81. settings: {
  82. providerFamilyConnectionSelections: {},
  83. providerFamilyDomain: {},
  84. } as Record<string, unknown>,
  85. usageEntitlement: { snapshot: null, loading: false, error: null } as Record<string, unknown>,
  86. usageEntitlementRefresh: vi.fn(async () => undefined),
  87. }));
  88. function completeDisabledModelConfig() {
  89. return {
  90. optionSpecs: {
  91. reasoningLevel: { values: ["disabled"], map: "{}" },
  92. maxOutputTokens: { max: 32_000, map: "{}" },
  93. },
  94. };
  95. }
  96. vi.mock("@/ModelConfigSelect.js", async () => {
  97. const React = await import("react");
  98. return {
  99. ModelConfigSelect: (props: ModelConfigSelectProps) => {
  100. captured.modelSelectProps = props;
  101. if (props.triggerRef && "current" in props.triggerRef) {
  102. (props.triggerRef as { current: HTMLSpanElement | null }).current = {
  103. contains: () => false,
  104. getClientRects: () => [{ width: 1 }] as unknown as DOMRectList,
  105. } as HTMLSpanElement;
  106. }
  107. return React.createElement("button", {
  108. "data-testid": "mock-model-select",
  109. disabled: props.disabled,
  110. });
  111. },
  112. };
  113. });
  114. vi.mock("@/chat-input-toolbar/display.js", async () => {
  115. const React = await import("react");
  116. return {
  117. ChatContextUsage: (props: Record<string, unknown>) => {
  118. captured.usageProps.push(props);
  119. return React.createElement("span", { "data-testid": "mock-usage" });
  120. },
  121. };
  122. });
  123. vi.mock("@/chat-input-toolbar/ThoughtLevelCycleControl.js", async () => {
  124. const React = await import("react");
  125. return {
  126. ThoughtLevelCycleControl: (props: {
  127. onValueChange: (value: string) => void;
  128. option: { currentValue?: unknown; options?: Array<{ value: string }> };
  129. }) => {
  130. captured.thoughtControlProps = props;
  131. return React.createElement("span", { "data-testid": "mock-thought" });
  132. },
  133. };
  134. });
  135. vi.mock("@/v4/composer/toolbarShortcuts.js", () => ({
  136. useToolbarShortcutBindings: vi.fn(),
  137. }));
  138. vi.mock("@/chat-input-toolbar/modelSelection.js", () => ({
  139. resolveModelSelectTriggerDisplay: (value: string) => ({ value }),
  140. shouldShowManageModelsAction: () => false,
  141. }));
  142. vi.mock("@/store/TabStoreProvider.js", () => ({
  143. useTabStore: () => vi.fn(),
  144. }));
  145. vi.mock("@/hooks/useProviderSettingsView.js", () => ({
  146. useProviderSettingsView: () => ({
  147. state: mocks.providerSettingsView
  148. ? { status: "ready", view: mocks.providerSettingsView }
  149. : { status: "loading" },
  150. reload: vi.fn(),
  151. }),
  152. }));
  153. vi.mock("@/hooks/useSettingService.js", () => ({
  154. useSettings: () => ({
  155. settings: mocks.settings,
  156. }),
  157. }));
  158. vi.mock("@/hooks/useUsageEntitlement.js", () => ({
  159. useUsageEntitlement: () => ({
  160. ...mocks.usageEntitlement,
  161. refresh: mocks.usageEntitlementRefresh,
  162. }),
  163. }));
  164. vi.mock("@/hooks/useZCodeConfig.js", () => ({
  165. useToolbarConfigOptions: () => ({
  166. configOptions: mocks.configOptions,
  167. loading: false,
  168. error: mocks.configOptionsError,
  169. }),
  170. }));
  171. vi.mock("@/i18n/IntlProvider.js", () => ({
  172. useZCodeIntl: () => ({
  173. intl: {
  174. formatMessage: ({ id }: { id: string }) => id,
  175. },
  176. locale: "zh-CN",
  177. }),
  178. }));
  179. vi.mock("@/settings/CodingPlanUpgradeDialogProvider.js", () => ({
  180. useCodingPlanUpgradeDialog: () => ({ openCodingPlanUpgrade: vi.fn() }),
  181. }));
  182. vi.mock("@/settings/model-provider-section/useCodingPlanEntitlements.js", () => ({
  183. useCodingPlanEntitlements: () => ({
  184. entitlements: mocks.codingPlanEntitlements,
  185. enabledStartPlanProviderIds: mocks.codingPlanEntitlementsEnabledStartPlanIds,
  186. refresh: mocks.codingPlanEntitlementsRefresh,
  187. }),
  188. }));
  189. vi.mock("@/settings/model-provider-section/useEnterpriseCodingPlanProducts.js", () => ({
  190. useEnterpriseCodingPlanProducts: () => mocks.enterpriseProducts,
  191. }));
  192. vi.mock("@/lib/sidebarUsageCodingPlanProviderPreference.js", async () => {
  193. const actual = await vi.importActual("@/lib/sidebarUsageCodingPlanProviderPreference.js");
  194. return {
  195. ...(actual as Record<string, unknown>),
  196. writeSidebarUsageCodingPlanProviderPreference: vi.fn(),
  197. };
  198. });
  199. vi.mock("@/lib/codingPlanUsageSources.js", async () => {
  200. const actual = await vi.importActual("@/lib/codingPlanUsageSources.js");
  201. return actual;
  202. });
  203. vi.mock("@/lib/settingsNavigation.js", () => ({
  204. setPendingSettingsSectionIntent: vi.fn(),
  205. setPendingSettingsUsageIntent: vi.fn(),
  206. }));
  207. function createMinimalElement(ownerDocument: Document, tagName = "div") {
  208. const element = {
  209. addEventListener: () => {},
  210. appendChild: (child: { parentNode?: unknown }) => {
  211. child.parentNode = element;
  212. return child;
  213. },
  214. childNodes: [] as unknown[],
  215. getAttribute: () => null,
  216. insertBefore: (child: { parentNode?: unknown }) => {
  217. child.parentNode = element;
  218. return child;
  219. },
  220. nodeName: tagName.toUpperCase(),
  221. nodeType: 1,
  222. ownerDocument,
  223. parentNode: null as unknown,
  224. removeAttribute: () => {},
  225. removeChild: (child: { parentNode?: unknown }) => {
  226. child.parentNode = null;
  227. return child;
  228. },
  229. removeEventListener: () => {},
  230. setAttribute: () => {},
  231. style: {},
  232. tagName: tagName.toUpperCase(),
  233. };
  234. return element as unknown as Element;
  235. }
  236. function installMinimalDom() {
  237. const documentMock = {
  238. addEventListener: () => {},
  239. createElement: (tagName: string) =>
  240. createMinimalElement(documentMock as unknown as Document, tagName),
  241. createElementNS: (_namespace: string, tagName: string) =>
  242. createMinimalElement(documentMock as unknown as Document, tagName),
  243. createTextNode: (nodeValue: string) => ({
  244. nodeType: 3,
  245. nodeValue,
  246. ownerDocument: documentMock,
  247. parentNode: null,
  248. }),
  249. nodeType: 9,
  250. removeEventListener: () => {},
  251. } as unknown as Document;
  252. const windowMock = {
  253. addEventListener: () => {},
  254. clearTimeout,
  255. document: documentMock,
  256. HTMLElement: function HTMLElement() {},
  257. HTMLIFrameElement: function HTMLIFrameElement() {},
  258. Node: function Node() {},
  259. removeEventListener: () => {},
  260. setTimeout,
  261. } as unknown as Window & typeof globalThis;
  262. Object.assign(globalThis, {
  263. document: documentMock,
  264. window: windowMock,
  265. HTMLElement: windowMock.HTMLElement,
  266. HTMLIFrameElement: windowMock.HTMLIFrameElement,
  267. Node: windowMock.Node,
  268. });
  269. return createMinimalElement(documentMock, "div");
  270. }
  271. async function flushMicrotasks(): Promise<void> {
  272. await Promise.resolve();
  273. await Promise.resolve();
  274. }
  275. function addAccountProviderAccess(
  276. providerId: string,
  277. access:
  278. | {
  279. accountType: "zai" | "bigmodel";
  280. mode: "individual-coding-plan";
  281. }
  282. | {
  283. accountType: "zai" | "bigmodel";
  284. mode: "team-coding-plan";
  285. },
  286. label = providerId,
  287. ) {
  288. mocks.providerSettingsView = {
  289. revision: mocks.providerSettingsView.revision + 1,
  290. addableProviders: mocks.providerSettingsView.addableProviders,
  291. providerOrder: mocks.providerSettingsView.providerOrder,
  292. providers: [
  293. ...mocks.providerSettingsView.providers.filter(
  294. (provider) => provider.providerId !== providerId,
  295. ),
  296. {
  297. providerId,
  298. enabled: true,
  299. executable: true,
  300. effectiveConfig: {
  301. access: {
  302. type: "zhipu-account",
  303. entitled: true,
  304. ...access,
  305. },
  306. api: {
  307. type: "anthropic-messages",
  308. baseUrl: "https://example.com",
  309. },
  310. label,
  311. builtinModelIds: [],
  312. },
  313. issues: [],
  314. models: [],
  315. },
  316. ],
  317. };
  318. }
  319. function createActiveEntitlement(providerId: string, extra: Record<string, unknown> = {}) {
  320. return {
  321. generatedAt: 1,
  322. authenticated: true,
  323. provider: {
  324. id: providerId,
  325. name: providerId,
  326. },
  327. remaining: null,
  328. subscription: null,
  329. quota: {
  330. level: "pro",
  331. limits: [
  332. {
  333. type: "TOKENS_LIMIT",
  334. unit: 3,
  335. number: 5,
  336. percentage: 35,
  337. usageDetails: [],
  338. },
  339. ],
  340. },
  341. ...extra,
  342. };
  343. }
  344. function renderToolbarMarkup(overrides: Partial<V4ComposerModelControlsProps> = {}): string {
  345. // 纯工具条测试显式提供已初始化的 Composer;生产初始化由 scope owner 负责。
  346. const seed = overrides.config ?? {
  347. provider: "custom-openai",
  348. model: "gpt-4o",
  349. thought: "disabled",
  350. mode: "build",
  351. };
  352. return renderToStaticMarkup(
  353. // HighspeedModelIndicator 走 ControlHintTooltip,缺少 TooltipProvider 会直接抛错,
  354. // 所以工具条快照统一包一层 Provider。
  355. createElement(
  356. TooltipProvider,
  357. null,
  358. createElement(V4ComposerModelControls, {
  359. workspacePath: "/workspace",
  360. modelSelectionView: mocks.modelSelectionView,
  361. sessionId: null,
  362. phase: null,
  363. config: {
  364. provider: "custom-openai",
  365. model: "gpt-4o",
  366. thought: "medium",
  367. thoughtLevels: ["medium", "high"],
  368. followupMode: "queue",
  369. mode: "build",
  370. },
  371. usage: {
  372. contextWindow: {
  373. usedTokens: 1024,
  374. maxTokens: 2048,
  375. autoCompactThresholdTokens: null,
  376. },
  377. cumulative: {
  378. inputTokens: 1024,
  379. outputTokens: 0,
  380. cacheReadTokens: 0,
  381. cacheWriteTokens: 0,
  382. },
  383. },
  384. disabled: false,
  385. onSelectModel: mocks.selectModel,
  386. onSelectThought: vi.fn(),
  387. onSwitchMode: vi.fn(),
  388. draftConfig: {
  389. mode: seed.mode,
  390. modelSelection: {
  391. providerId: seed.provider,
  392. modelId: seed.model,
  393. ...(seed.thought ? { options: { reasoningLevel: seed.thought } } : {}),
  394. },
  395. },
  396. ...overrides,
  397. }),
  398. ),
  399. );
  400. }
  401. function latestUsageProps(): Record<string, unknown> {
  402. return captured.usageProps[captured.usageProps.length - 1] ?? {};
  403. }
  404. afterEach(() => {
  405. captured.modelSelectProps = null;
  406. captured.thoughtControlProps = null;
  407. captured.usageProps = [];
  408. mocks.codingPlanEntitlementsRefresh.mockClear();
  409. mocks.usageEntitlementRefresh.mockClear();
  410. mocks.codingPlanEntitlements = {};
  411. mocks.codingPlanEntitlementsEnabledStartPlanIds = [];
  412. mocks.configOptions = [];
  413. mocks.configOptionsError = true;
  414. mocks.enterpriseProducts = { snapshot: { productList: [] }, loading: false, error: null };
  415. mocks.modelSelectionView = {
  416. revision: 1,
  417. providers: [
  418. {
  419. providerId: "custom-openai",
  420. providerName: "Custom OpenAI",
  421. config: {
  422. access: { type: "api-key", apiKey: "test-key" },
  423. api: {
  424. type: "openai-chat-completions",
  425. baseUrl: "https://api.example.com/v1",
  426. },
  427. models: ["gpt-4o"],
  428. },
  429. models: [{ modelId: "gpt-4o", config: completeDisabledModelConfig() }],
  430. },
  431. ],
  432. };
  433. mocks.providerSettingsView = {
  434. revision: 1,
  435. addableProviders: [],
  436. providerOrder: [],
  437. providers: [],
  438. };
  439. mocks.settings = {
  440. providerFamilyConnectionSelections: {},
  441. providerFamilyDomain: {},
  442. };
  443. mocks.usageEntitlement = { snapshot: null, loading: false, error: null };
  444. vi.clearAllMocks();
  445. });
  446. describe("V4ComposerModelControls recovery", () => {
  447. it("Highspeed 卡生效期间隐藏 context token usage 圈圈", () => {
  448. const normalHtml = renderToolbarMarkup();
  449. const highspeedHtml = renderToolbarMarkup({ modelLocked: true });
  450. expect(normalHtml).toContain('data-testid="mock-usage"');
  451. expect(highspeedHtml).not.toContain('data-testid="mock-usage"');
  452. });
  453. it("把无晃动的固定宽度倒计时放在模型和 Think 之间", () => {
  454. vi.spyOn(Date, "now").mockReturnValue(1_000);
  455. const html = renderToolbarMarkup({
  456. highspeedExpiresAt: 60_000,
  457. highspeedModel: "GLM-5.3",
  458. highspeedPresented: true,
  459. });
  460. const modelIndex = html.indexOf('data-highspeed-model-indicator="true"');
  461. const countdownIndex = html.indexOf('data-highspeed-countdown="true"');
  462. const thoughtIndex = html.indexOf('data-testid="mock-thought"');
  463. expect(modelIndex).toBeGreaterThanOrEqual(0);
  464. expect(countdownIndex).toBeGreaterThan(modelIndex);
  465. expect(thoughtIndex).toBeGreaterThan(countdownIndex);
  466. expect(html).toContain("00:00:59");
  467. expect(html).toContain("h-7");
  468. expect(html).toContain("w-[82px]");
  469. expect(html).toContain("w-[54px]");
  470. expect(html).toContain("tabular-nums");
  471. expect(html).toMatch(/data-highspeed-countdown="true"[^>]*@max-xl\/composer:w-7/);
  472. expect(html).toMatch(
  473. /title="chat.highspeed.remainingTime"[^>]*data-highspeed-countdown="true"/,
  474. );
  475. expect(html).toMatch(/data-highspeed-countdown-value="true"[^>]*@max-xl\/composer:hidden/);
  476. expect(html).not.toContain("animate-zcode-alarm-ring");
  477. expect(html).not.toMatch(/data-highspeed-countdown="true"[^>]*text-icon-purple/);
  478. });
  479. it("已有会话的 Composer 模型留空时仍能打开模型菜单重选", () => {
  480. renderToolbarMarkup({
  481. sessionId: "existing-session",
  482. draftMode: false,
  483. draftConfig: { mode: "build" },
  484. });
  485. expect(captured.modelSelectProps).not.toBeNull();
  486. expect(captured.modelSelectProps?.normalizedValue).toBe("");
  487. expect(captured.thoughtControlProps).toBeNull();
  488. });
  489. it("renders an explicit retry action when the target Host model view fails", () => {
  490. const html = renderToolbarMarkup({
  491. modelSelectionView: null,
  492. modelSelectionState: { status: "error", error: new Error("read failed") },
  493. modelSelectionReload: vi.fn(),
  494. });
  495. expect(html).toContain("chat.toolbar.model.loadFailedRetry");
  496. expect(html).not.toContain('data-testid="mock-model-select"');
  497. });
  498. it("Start 权益目录更新不自动改输入框模型或显示旧领取引导", async () => {
  499. const providerId = BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan;
  500. mocks.settings = {
  501. providerFamilyConnectionSelections: { bigmodel: { kind: "start-plan" } },
  502. providerFamilyDomain: {},
  503. };
  504. mocks.modelSelectionView = {
  505. revision: 2,
  506. providers: [
  507. {
  508. providerId,
  509. providerName: "BigModel Start Plan",
  510. config: {
  511. access: { type: "zhipu-account", accountType: "bigmodel", mode: "start-plan" },
  512. api: {
  513. type: "anthropic-messages",
  514. baseUrl: "https://open.bigmodel.cn/api/anthropic",
  515. },
  516. models: ["GLM-5.3-Flash"],
  517. },
  518. models: [{ modelId: "GLM-5.3-Flash", config: completeDisabledModelConfig() }],
  519. },
  520. ],
  521. };
  522. const root: Root = createRoot(installMinimalDom());
  523. const props = {
  524. workspacePath: "/workspace",
  525. modelSelectionView: mocks.modelSelectionView,
  526. sessionId: null,
  527. phase: null,
  528. draftConfig: {
  529. mode: "build",
  530. modelSelection: {
  531. providerId: "custom-openai",
  532. modelId: "gpt-4o",
  533. options: { reasoningLevel: "medium" },
  534. },
  535. },
  536. config: {
  537. provider: "custom-openai",
  538. model: "gpt-4o",
  539. thought: "medium",
  540. thoughtLevels: ["medium"],
  541. followupMode: "queue" as const,
  542. mode: "build" as const,
  543. },
  544. usage: null,
  545. disabled: false,
  546. onSelectModel: mocks.selectModel,
  547. onSelectThought: vi.fn(),
  548. onSwitchMode: vi.fn(),
  549. };
  550. await act(async () => {
  551. root.render(createElement(V4ComposerModelControls, props));
  552. await flushMicrotasks();
  553. });
  554. expect(mocks.selectModel).not.toHaveBeenCalled();
  555. expect(captured.modelSelectProps?.guideTooltipOpen).toBeUndefined();
  556. await act(async () => {
  557. root.render(createElement(V4ComposerModelControls, props));
  558. await flushMicrotasks();
  559. });
  560. expect(mocks.selectModel).not.toHaveBeenCalled();
  561. await act(async () => root.unmount());
  562. });
  563. it("将供应商配置名称传给模型触发器展示", () => {
  564. renderToolbarMarkup();
  565. expect(captured.modelSelectProps?.triggerLabel).toBe("Custom OpenAI/gpt-4o");
  566. expect(captured.modelSelectProps?.indicatorClassName).not.toContain("@sm/composer");
  567. expect(captured.modelSelectProps?.indicatorClassName).toContain(
  568. "group-data-[composer-model-icon=true]/toolbar:hidden",
  569. );
  570. expect(captured.modelSelectProps?.triggerClassName).toContain(
  571. "group-data-[composer-model-icon=true]/toolbar:size-7",
  572. );
  573. expect(captured.modelSelectProps?.triggerLabelPrefixClassName).not.toContain("@2xl/composer");
  574. expect(captured.modelSelectProps?.triggerLabelPrefixClassName).toContain(
  575. "group-data-[composer-provider-compact=true]/toolbar:hidden",
  576. );
  577. });
  578. it("Registry 已发布时只使用 Registry providerName", () => {
  579. mocks.modelSelectionView = {
  580. revision: 1,
  581. providers: [
  582. {
  583. providerId: "custom-openai",
  584. providerName: "Registry OpenAI",
  585. config: {
  586. access: { type: "api-key", apiKey: "test-key" },
  587. api: {
  588. type: "openai-chat-completions",
  589. baseUrl: "https://registry.example.com/v1",
  590. },
  591. models: ["gpt-4o"],
  592. },
  593. models: [{ modelId: "gpt-4o", config: completeDisabledModelConfig() }],
  594. },
  595. ],
  596. };
  597. renderToolbarMarkup();
  598. expect(captured.modelSelectProps?.triggerLabel).toBe("Registry OpenAI/gpt-4o");
  599. });
  600. it("prewarm 未就绪时不把旧 configOptions 模型当作 Selection 来源", async () => {
  601. mocks.configOptions = [
  602. {
  603. id: "model",
  604. name: "Model",
  605. category: "model",
  606. type: "select",
  607. currentValue: customValue,
  608. options: [{ value: customValue, name: "GPT-4o" }],
  609. },
  610. ];
  611. mocks.modelSelectionView = {
  612. revision: 2,
  613. providers: [
  614. ...mocks.modelSelectionView!.providers,
  615. {
  616. providerId: "alternate-provider",
  617. providerName: "Alternate API",
  618. config: {
  619. access: { type: "api-key", apiKey: "alternate-key" },
  620. api: {
  621. type: "openai-chat-completions",
  622. baseUrl: "https://alt.example.com/v1",
  623. },
  624. models: ["deepseek-v4-pro"],
  625. },
  626. models: [{ modelId: "deepseek-v4-pro", config: completeDisabledModelConfig() }],
  627. },
  628. ],
  629. };
  630. const root: Root = createRoot(installMinimalDom());
  631. await act(async () => {
  632. root.render(
  633. createElement(V4ComposerModelControls, {
  634. workspacePath: "/workspace",
  635. modelSelectionView: mocks.modelSelectionView,
  636. sessionId: null,
  637. phase: null,
  638. config: null,
  639. draftMode: true,
  640. usage: null,
  641. disabled: false,
  642. onSelectModel: mocks.selectModel,
  643. onSelectThought: vi.fn(),
  644. onSwitchMode: vi.fn(),
  645. }),
  646. );
  647. await flushMicrotasks();
  648. });
  649. await act(async () => {
  650. captured.modelSelectProps?.onValueChange("custom:alternate-provider:deepseek-v4-pro");
  651. await flushMicrotasks();
  652. });
  653. expect(mocks.selectModel).toHaveBeenCalledWith("alternate-provider", "deepseek-v4-pro", null);
  654. await act(async () => {
  655. root.unmount();
  656. });
  657. });
  658. it("V4 任务边界不再刷新 entitlement", async () => {
  659. const root: Root = createRoot(installMinimalDom());
  660. const renderPhase = (phase: V4ComposerModelControlsProps["phase"]) =>
  661. createElement(V4ComposerModelControls, {
  662. workspacePath: "/workspace",
  663. modelSelectionView: mocks.modelSelectionView,
  664. sessionId: "session-usage-refresh",
  665. phase,
  666. config: {
  667. provider: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  668. model: "glm-5",
  669. thought: "medium",
  670. thoughtLevels: ["medium"],
  671. followupMode: "queue",
  672. mode: "build",
  673. },
  674. usage: null,
  675. disabled: false,
  676. onSelectModel: mocks.selectModel,
  677. onSelectThought: vi.fn(),
  678. onSwitchMode: vi.fn(),
  679. });
  680. await act(async () => {
  681. root.render(renderPhase("running"));
  682. await flushMicrotasks();
  683. });
  684. expect(mocks.codingPlanEntitlementsRefresh).not.toHaveBeenCalled();
  685. await act(async () => {
  686. root.render(renderPhase("completedInterrupted"));
  687. await flushMicrotasks();
  688. });
  689. expect(mocks.codingPlanEntitlementsRefresh).not.toHaveBeenCalled();
  690. await act(async () => {
  691. root.render(renderPhase("running"));
  692. await flushMicrotasks();
  693. });
  694. expect(mocks.codingPlanEntitlementsRefresh).not.toHaveBeenCalled();
  695. await act(async () => {
  696. root.render(renderPhase("completedSuccess"));
  697. await flushMicrotasks();
  698. });
  699. expect(mocks.codingPlanEntitlementsRefresh).not.toHaveBeenCalled();
  700. await act(async () => {
  701. root.unmount();
  702. });
  703. });
  704. it("忽略模型切换期间受控 Select 产生的空 thought 事件", () => {
  705. mocks.configOptions = [
  706. {
  707. id: "thought_level",
  708. name: "Thought Level",
  709. category: "thought_level",
  710. type: "select",
  711. currentValue: "medium",
  712. options: [
  713. { label: "Medium", value: "medium" },
  714. { label: "High", value: "high" },
  715. ],
  716. },
  717. ];
  718. mocks.configOptionsError = false;
  719. const onSelectThought = vi.fn();
  720. renderToolbarMarkup({ onSelectThought });
  721. expect(captured.thoughtControlProps?.indicatorClassName).toBe("block");
  722. expect(captured.thoughtControlProps?.composerCollapsePriority).toBe(3);
  723. captured.thoughtControlProps?.onValueChange("");
  724. expect(onSelectThought).not.toHaveBeenCalled();
  725. captured.thoughtControlProps?.onValueChange("high");
  726. expect(onSelectThought).toHaveBeenCalledWith("high", {
  727. provider: "custom-openai",
  728. model: "gpt-4o",
  729. });
  730. });
  731. it("会话态候选档位只取目标 Host View,不取旧 Session 或 workspace 目录", () => {
  732. mocks.configOptions = [
  733. {
  734. id: "thought_level",
  735. name: "Thought Level",
  736. category: "thought_level",
  737. type: "select",
  738. currentValue: "off",
  739. options: ["off", "low", "medium", "high", "max"].map((value) => ({ value })),
  740. },
  741. ];
  742. mocks.modelSelectionView!.providers[0]!.models.push({
  743. modelId: "GLM-5.2",
  744. config: {
  745. optionSpecs: {
  746. reasoningLevel: { values: ["low", "high", "max"], map: "{}" },
  747. },
  748. },
  749. });
  750. renderToolbarMarkup({
  751. config: {
  752. provider: "custom-openai",
  753. model: "GLM-5.2",
  754. thought: "high",
  755. thoughtLevels: ["max", "high", "nothink"],
  756. followupMode: "queue",
  757. mode: "build",
  758. },
  759. });
  760. expect(captured.thoughtControlProps?.option.options?.map(({ value }) => value)).toEqual([
  761. "low",
  762. "high",
  763. "max",
  764. ]);
  765. });
  766. it.each([{ thoughtLevels: [] }, { thoughtLevels: ["disabled"] }])(
  767. "恢复的空档位不被目录补齐:$thoughtLevels",
  768. ({ thoughtLevels }) => {
  769. renderToolbarMarkup({
  770. config: {
  771. provider: "custom-openai",
  772. model: "gpt-4o",
  773. thought: "",
  774. thoughtLevels,
  775. followupMode: "queue",
  776. mode: "build",
  777. },
  778. });
  779. expect(captured.thoughtControlProps?.option.currentValue).toBe("");
  780. },
  781. );
  782. it("草稿预热完成后仍展示 Composer 选择与 Host 候选,不消费旧投影档位", () => {
  783. renderToolbarMarkup({
  784. draftMode: true,
  785. draftConfig: {
  786. mode: "build",
  787. modelSelection: {
  788. providerId: "custom-openai",
  789. modelId: "gpt-4o",
  790. options: { reasoningLevel: "disabled" },
  791. },
  792. },
  793. config: {
  794. provider: "custom-openai",
  795. model: "gpt-4o",
  796. thought: "high",
  797. thoughtLevels: ["max", "high", "nothink"],
  798. followupMode: "queue",
  799. mode: "build",
  800. },
  801. });
  802. expect(captured.thoughtControlProps?.option).toMatchObject({
  803. currentValue: "disabled",
  804. options: [{ value: "disabled" }],
  805. });
  806. });
  807. it("草稿切换目标模型时不复用旧预热投影的 thought 档位", () => {
  808. renderToolbarMarkup({
  809. draftMode: true,
  810. config: {
  811. provider: "custom-openai",
  812. model: "gpt-4o",
  813. thought: "high",
  814. thoughtLevels: ["medium", "high"],
  815. followupMode: "queue",
  816. mode: "build",
  817. },
  818. draftConfig: {
  819. modelSelection: { providerId: "custom-openai", modelId: "gpt-4.1" },
  820. },
  821. });
  822. expect(captured.thoughtControlProps).toBeNull();
  823. });
  824. it("输入框工具条不再渲染 provider retry 状态", () => {
  825. const html = renderToolbarMarkup();
  826. expect(html).not.toContain("重新连接中...");
  827. expect(html).toContain('data-testid="mock-usage"');
  828. });
  829. it("does not pass derived capacity or plan props for a non-plan model with no usage", () => {
  830. renderToolbarMarkup({
  831. usage: null,
  832. });
  833. const props = latestUsageProps();
  834. expect(props).not.toHaveProperty("contextCapacityTokens");
  835. expect(props.codingPlanUsageRemaining).toBeUndefined();
  836. expect(props.startPlanBalance).toBeUndefined();
  837. });
  838. it("Registry 尚未发布时不从旧 Provider Snapshot 构造模型菜单", () => {
  839. mocks.modelSelectionView = null;
  840. renderToolbarMarkup();
  841. expect(captured.modelSelectProps).toBeNull();
  842. });
  843. it("passes Coding Plan usage only when the current connection is the selected OAuth Coding Plan", () => {
  844. addAccountProviderAccess(
  845. BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  846. { accountType: "zai", mode: "individual-coding-plan" },
  847. "Z.ai - Coding Plan",
  848. );
  849. mocks.codingPlanEntitlements = {
  850. [BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan]: {
  851. snapshot: createActiveEntitlement(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  852. loading: false,
  853. error: null,
  854. },
  855. };
  856. renderToolbarMarkup({
  857. config: {
  858. provider: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  859. model: "glm-5",
  860. thought: "medium",
  861. thoughtLevels: ["medium"],
  862. followupMode: "queue",
  863. mode: "build",
  864. },
  865. usage: null,
  866. });
  867. expect(latestUsageProps().codingPlanUsageRemaining).toBeUndefined();
  868. captured.usageProps = [];
  869. mocks.settings = {
  870. providerFamilyConnectionSelections: {
  871. zai: { kind: "individual-coding-plan" },
  872. },
  873. providerFamilyDomain: {},
  874. };
  875. renderToolbarMarkup({
  876. config: {
  877. provider: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  878. model: "glm-5",
  879. thought: "medium",
  880. thoughtLevels: ["medium"],
  881. followupMode: "queue",
  882. mode: "build",
  883. },
  884. usage: null,
  885. });
  886. const props = latestUsageProps();
  887. expect(props.codingPlanUsageRemaining).toMatchObject({
  888. selectedProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  889. });
  890. expect(props.startPlanBalance).toBeUndefined();
  891. });
  892. it("does not derive Coding Plan usage from a legacy provider without Account Access", () => {
  893. mocks.codingPlanEntitlements = {
  894. [BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan]: {
  895. snapshot: createActiveEntitlement(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  896. loading: false,
  897. error: null,
  898. },
  899. };
  900. mocks.settings = {
  901. providerFamilyConnectionSelections: {
  902. zai: { kind: "individual-coding-plan" },
  903. },
  904. providerFamilyDomain: {},
  905. };
  906. renderToolbarMarkup({
  907. config: {
  908. provider: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  909. model: "glm-5",
  910. thought: "medium",
  911. thoughtLevels: ["medium"],
  912. followupMode: "queue",
  913. mode: "build",
  914. },
  915. usage: null,
  916. });
  917. expect(latestUsageProps().codingPlanUsageRemaining).toBeUndefined();
  918. });
  919. it.each([
  920. undefined,
  921. { kind: "start-plan" },
  922. { kind: "individual-coding-plan" },
  923. { kind: "team-coding-plan", organizationId: "org", projectId: "project", productId: "plan" },
  924. ] as const)(
  925. "Start balance follows composer selection independent of saved connection %j",
  926. (selection) => {
  927. mocks.codingPlanEntitlements = {
  928. [BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan]: {
  929. snapshot: createActiveEntitlement(BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan),
  930. loading: false,
  931. error: null,
  932. },
  933. };
  934. mocks.settings = {
  935. providerFamilyConnectionSelections: {
  936. zai: selection,
  937. },
  938. providerFamilyDomain: {},
  939. };
  940. renderToolbarMarkup({
  941. config: {
  942. provider: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  943. model: "glm-5",
  944. thought: "medium",
  945. thoughtLevels: ["medium"],
  946. followupMode: "queue",
  947. mode: "build",
  948. },
  949. usage: null,
  950. });
  951. const props = latestUsageProps();
  952. expect(props.codingPlanUsageRemaining).toBeUndefined();
  953. expect(props.startPlanBalance).toMatchObject({
  954. loading: false,
  955. snapshot: {
  956. provider: {
  957. id: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  958. },
  959. },
  960. });
  961. },
  962. );
  963. it("does not pass Start Plan balance when the entitlement hook hides fallback balance", () => {
  964. mocks.codingPlanEntitlements = {
  965. [BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan]: {
  966. snapshot: createActiveEntitlement(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  967. loading: false,
  968. error: null,
  969. },
  970. [BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan]: {
  971. snapshot: null,
  972. loading: false,
  973. error: null,
  974. },
  975. };
  976. mocks.settings = {
  977. providerFamilyConnectionSelections: {
  978. zai: { kind: "start-plan" },
  979. },
  980. providerFamilyDomain: {},
  981. };
  982. renderToolbarMarkup({
  983. config: {
  984. provider: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  985. model: "glm-5",
  986. thought: "medium",
  987. thoughtLevels: ["medium"],
  988. followupMode: "queue",
  989. mode: "build",
  990. },
  991. usage: null,
  992. });
  993. expect(latestUsageProps().startPlanBalance).toBeUndefined();
  994. });
  995. it("attaches the hover access refresh entry when the Start Plan entitlement is enabled", () => {
  996. mocks.codingPlanEntitlements = {
  997. [BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan]: {
  998. snapshot: null,
  999. loading: false,
  1000. error: null,
  1001. },
  1002. };
  1003. mocks.codingPlanEntitlementsEnabledStartPlanIds = [BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan];
  1004. mocks.settings = {
  1005. providerFamilyConnectionSelections: {
  1006. zai: { kind: "start-plan" },
  1007. },
  1008. providerFamilyDomain: {},
  1009. };
  1010. renderToolbarMarkup({
  1011. config: {
  1012. provider: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  1013. model: "glm-5",
  1014. thought: "medium",
  1015. thoughtLevels: ["medium"],
  1016. followupMode: "queue",
  1017. mode: "build",
  1018. },
  1019. usage: null,
  1020. });
  1021. const startPlanBalance = latestUsageProps().startPlanBalance as {
  1022. onAccess?: () => unknown;
  1023. };
  1024. // 修复原因:start plan 用户原先没有 hover onAccess 入口,context 面板从不主动刷新今日余额。
  1025. expect(typeof startPlanBalance?.onAccess).toBe("function");
  1026. expect(startPlanBalance.onAccess).not.toBeNull();
  1027. });
  1028. it("recovers a Team Plan usage source from entitlement snapshot when products are not hydrated", () => {
  1029. const teamSourceId = "team:bigmodel:team-pro:org-1:project-1";
  1030. addAccountProviderAccess(BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan, {
  1031. accountType: "bigmodel",
  1032. mode: "team-coding-plan",
  1033. });
  1034. mocks.settings = {
  1035. providerFamilyConnectionSelections: {
  1036. bigmodel: {
  1037. kind: "team-coding-plan",
  1038. productId: "team-pro",
  1039. organizationId: "org-1",
  1040. projectId: "project-1",
  1041. },
  1042. },
  1043. providerFamilyDomain: {},
  1044. };
  1045. mocks.codingPlanEntitlements = {
  1046. [BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan]: {
  1047. snapshot: createActiveEntitlement(BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan, {
  1048. context: {
  1049. scope: "team",
  1050. organizationId: "org-1",
  1051. projectId: "project-1",
  1052. productId: "team-pro",
  1053. displayName: "Platform",
  1054. },
  1055. subscription: {
  1056. details: [
  1057. {
  1058. beginTime: "2026-01-01T00:00:00Z",
  1059. expireTime: "2026-12-31T00:00:00Z",
  1060. productId: "team-pro",
  1061. productName: "Platform",
  1062. purchaseTime: "2026-01-01T00:00:00Z",
  1063. },
  1064. ],
  1065. },
  1066. }),
  1067. loading: false,
  1068. error: null,
  1069. },
  1070. };
  1071. mocks.usageEntitlement = {
  1072. snapshot: createActiveEntitlement(BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan, {
  1073. context: {
  1074. scope: "team",
  1075. organizationId: "org-1",
  1076. projectId: "project-1",
  1077. productId: "team-pro",
  1078. displayName: "Platform",
  1079. },
  1080. }),
  1081. loading: false,
  1082. error: null,
  1083. };
  1084. renderToolbarMarkup({
  1085. config: {
  1086. provider: BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  1087. model: "glm-5",
  1088. thought: "medium",
  1089. thoughtLevels: ["medium"],
  1090. followupMode: "queue",
  1091. mode: "build",
  1092. },
  1093. usage: null,
  1094. });
  1095. expect(latestUsageProps().codingPlanUsageRemaining).toMatchObject({
  1096. selectedProviderId: teamSourceId,
  1097. });
  1098. });
  1099. it("routes custom model selection to the recovery callback when configOptions failed", async () => {
  1100. const root: Root = createRoot(installMinimalDom());
  1101. await act(async () => {
  1102. root.render(
  1103. createElement(V4ComposerModelControls, {
  1104. workspacePath: "/workspace",
  1105. modelSelectionView: mocks.modelSelectionView,
  1106. sessionId: null,
  1107. phase: null,
  1108. draftConfig: {
  1109. mode: "build",
  1110. modelSelection: {
  1111. providerId: "primary-provider",
  1112. modelId: "source-model",
  1113. options: { reasoningLevel: "high" },
  1114. },
  1115. },
  1116. config: {
  1117. provider: "primary-provider",
  1118. model: "source-model",
  1119. thought: "high",
  1120. thoughtLevels: ["high"],
  1121. followupMode: "queue",
  1122. mode: "build",
  1123. },
  1124. draftMode: true,
  1125. usage: null,
  1126. disabled: false,
  1127. onSelectModel: mocks.selectModel,
  1128. onSelectThought: vi.fn(),
  1129. onSwitchMode: vi.fn(),
  1130. onRecoverCustomModelSelection: mocks.recoverCustomModelSelection,
  1131. }),
  1132. );
  1133. await flushMicrotasks();
  1134. });
  1135. await act(async () => {
  1136. captured.modelSelectProps?.onValueChange(customValue);
  1137. await flushMicrotasks();
  1138. });
  1139. expect(mocks.recoverCustomModelSelection).toHaveBeenCalledWith(customValue, {
  1140. provider: "primary-provider",
  1141. model: "source-model",
  1142. });
  1143. expect(mocks.selectModel).not.toHaveBeenCalled();
  1144. await act(async () => {
  1145. root.unmount();
  1146. });
  1147. });
  1148. it("does not expose a legacy-only provider after an empty Registry view is published", async () => {
  1149. mocks.modelSelectionView = { revision: 1, providers: [] };
  1150. const root: Root = createRoot(installMinimalDom());
  1151. await act(async () => {
  1152. root.render(
  1153. createElement(V4ComposerModelControls, {
  1154. workspacePath: "/workspace",
  1155. modelSelectionView: mocks.modelSelectionView,
  1156. sessionId: null,
  1157. phase: null,
  1158. config: {
  1159. provider: "primary-provider",
  1160. model: "source-model",
  1161. thought: "high",
  1162. thoughtLevels: ["high"],
  1163. followupMode: "queue",
  1164. mode: "build",
  1165. },
  1166. draftMode: true,
  1167. usage: null,
  1168. disabled: false,
  1169. onSelectModel: mocks.selectModel,
  1170. onSelectThought: vi.fn(),
  1171. onSwitchMode: vi.fn(),
  1172. onRecoverCustomModelSelection: mocks.recoverCustomModelSelection,
  1173. }),
  1174. );
  1175. await flushMicrotasks();
  1176. });
  1177. expect(captured.modelSelectProps).toBeNull();
  1178. expect(mocks.recoverCustomModelSelection).not.toHaveBeenCalled();
  1179. expect(mocks.selectModel).not.toHaveBeenCalled();
  1180. await act(async () => {
  1181. root.unmount();
  1182. });
  1183. });
  1184. it("does not route builtin model selection through custom recovery when configOptions failed", async () => {
  1185. const providerId = BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan;
  1186. mocks.modelSelectionView = {
  1187. revision: 2,
  1188. providers: [
  1189. {
  1190. providerId,
  1191. providerName: "BigModel Coding",
  1192. config: {
  1193. access: {
  1194. type: "zhipu-account",
  1195. },
  1196. api: {
  1197. type: "anthropic-messages",
  1198. baseUrl: "https://open.bigmodel.cn/api/anthropic",
  1199. },
  1200. models: ["glm-5"],
  1201. },
  1202. models: [{ modelId: "glm-5", config: completeDisabledModelConfig() }],
  1203. },
  1204. ],
  1205. };
  1206. const value = `custom:${encodeURIComponent(providerId)}:glm-5`;
  1207. const root: Root = createRoot(installMinimalDom());
  1208. await act(async () => {
  1209. root.render(
  1210. createElement(V4ComposerModelControls, {
  1211. workspacePath: "/workspace",
  1212. modelSelectionView: mocks.modelSelectionView,
  1213. sessionId: null,
  1214. phase: null,
  1215. config: null,
  1216. draftMode: true,
  1217. usage: null,
  1218. disabled: false,
  1219. onSelectModel: mocks.selectModel,
  1220. onSelectThought: vi.fn(),
  1221. onSwitchMode: vi.fn(),
  1222. onRecoverCustomModelSelection: mocks.recoverCustomModelSelection,
  1223. }),
  1224. );
  1225. await flushMicrotasks();
  1226. });
  1227. await act(async () => {
  1228. captured.modelSelectProps?.onValueChange(value);
  1229. await flushMicrotasks();
  1230. });
  1231. expect(mocks.recoverCustomModelSelection).not.toHaveBeenCalled();
  1232. expect(mocks.selectModel).toHaveBeenCalledWith(providerId, "glm-5", null);
  1233. await act(async () => {
  1234. root.unmount();
  1235. });
  1236. });
  1237. it("does not write a menu-first fallback when a session model is absent from the visible catalog", async () => {
  1238. const root: Root = createRoot(installMinimalDom());
  1239. await act(async () => {
  1240. root.render(
  1241. createElement(V4ComposerModelControls, {
  1242. workspacePath: "/workspace",
  1243. modelSelectionView: mocks.modelSelectionView,
  1244. sessionId: "session-removed-model",
  1245. phase: "completedSuccess",
  1246. config: {
  1247. provider: "removed-provider",
  1248. model: "removed-model",
  1249. thought: "high",
  1250. thoughtLevels: ["high"],
  1251. followupMode: "queue",
  1252. mode: "build",
  1253. },
  1254. usage: null,
  1255. disabled: false,
  1256. onSelectModel: mocks.selectModel,
  1257. onSelectThought: vi.fn(),
  1258. onSwitchMode: vi.fn(),
  1259. }),
  1260. );
  1261. await flushMicrotasks();
  1262. });
  1263. expect(mocks.selectModel).not.toHaveBeenCalled();
  1264. await act(async () => {
  1265. root.unmount();
  1266. });
  1267. });
  1268. });