v4ComposerToolbarRecovery.test.ts 44 KB

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