composerConnectionSwitch.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. // @vitest-environment jsdom
  2. import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
  3. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  4. import { resolveEffectiveModelSelection, type ProviderRegistryView } from "@zcode/provider";
  5. import type { ComposerConnection } from "@/lib/composerPlanGroups.js";
  6. import { useComposerConnectionSwitch } from "@/hooks/useComposerConnectionSwitch.js";
  7. import { persistProviderFamilyConnection } from "@/lib/providerFamilyConnectionTransition.js";
  8. import type { AppSettings } from "@zcode/shared";
  9. import { encodeCustomModelValue } from "@/lib/zcodeCustomModelValue.js";
  10. import { useModelSelectionServiceView } from "@/hooks/useModelSelectionView.js";
  11. const mocks = vi.hoisted(() => {
  12. const settings = { providerFamilyConnectionSelections: {} } as Record<string, unknown>;
  13. const base = {
  14. settingService: { get: vi.fn(async () => settings) },
  15. providerSettingsService: { refresh: vi.fn(async () => {}) },
  16. modelSelectionService: { getView: vi.fn(), onDidChange: vi.fn(() => ({ dispose: vi.fn() })) },
  17. };
  18. return {
  19. base,
  20. target: base,
  21. settings,
  22. update: vi.fn(async (patch: unknown) => {
  23. Object.assign(settings, patch);
  24. }),
  25. };
  26. });
  27. vi.mock("@/hooks/useWorkspaceServices.js", () => ({
  28. useBaseWorkspaceServices: () => mocks.base,
  29. useWorkspaceServicesResolution: () => ({ services: mocks.target, rpcReady: true }),
  30. }));
  31. vi.mock("@/hooks/useSettingService.js", () => ({ useSettings: () => ({ update: mocks.update }) }));
  32. vi.mock("@/i18n/IntlProvider.js", () => ({
  33. useZCodeIntl: () => ({ intl: { formatMessage: () => "Switch failed; select again to retry" } }),
  34. }));
  35. const providerId = "account:bigmodel-team-coding-plan";
  36. const connection: ComposerConnection = {
  37. key: "team1",
  38. label: "Team One",
  39. family: "bigmodel",
  40. providerId,
  41. selection: { kind: "team-coding-plan", productId: "p", organizationId: "o", projectId: "j" },
  42. items: [],
  43. };
  44. const view = {
  45. revision: 2,
  46. providers: [
  47. {
  48. providerId,
  49. config: {
  50. access: { type: "zhipu-account", accountType: "bigmodel", mode: "team-coding-plan" },
  51. api: { type: "anthropic-messages" },
  52. },
  53. models: [{ modelId: "GLM-5.3", config: { optionSpecs: { reasoningLevel: { values: [] } } } }],
  54. },
  55. ],
  56. };
  57. function deferred<T>() {
  58. let resolve!: (v: T) => void;
  59. const promise = new Promise<T>((r) => {
  60. resolve = r;
  61. });
  62. return { promise, resolve };
  63. }
  64. beforeEach(() => {
  65. vi.clearAllMocks();
  66. mocks.target = mocks.base;
  67. mocks.settings.providerFamilyConnectionSelections = {
  68. bigmodel: { kind: "individual-coding-plan" },
  69. };
  70. mocks.base.modelSelectionService.getView.mockResolvedValue(view);
  71. mocks.base.providerSettingsService.refresh.mockResolvedValue(undefined);
  72. });
  73. afterEach(cleanup);
  74. describe("Composer connection switching ownership", () => {
  75. it("同步完成才选择目标模型,快速重复点击只提交一次", async () => {
  76. const wait = deferred<void>();
  77. mocks.base.providerSettingsService.refresh.mockReturnValueOnce(wait.promise);
  78. const onSelectModel = vi.fn();
  79. const { result } = renderHook(() =>
  80. useComposerConnectionSwitch({
  81. workspacePath: "/work",
  82. agentProvider: "glm",
  83. normalizedValue: "",
  84. onSelectModel,
  85. }),
  86. );
  87. let task!: Promise<void>;
  88. await act(async () => {
  89. task = result.current.select(connection);
  90. await Promise.resolve();
  91. });
  92. expect(result.current.pending).toBe(true);
  93. expect(onSelectModel).not.toHaveBeenCalled();
  94. await act(async () => {
  95. await result.current.select(connection);
  96. });
  97. expect(mocks.update).toHaveBeenCalledTimes(1);
  98. await act(async () => {
  99. wait.resolve();
  100. await task;
  101. });
  102. expect(onSelectModel).toHaveBeenCalledWith(encodeCustomModelValue(providerId, "GLM-5.3"));
  103. expect(result.current.pending).toBe(false);
  104. });
  105. it("普通 API 进入团队时携带刚同步目录的思考档位,不能依赖旧 API 目录", async () => {
  106. mocks.base.modelSelectionService.getView.mockResolvedValue({
  107. ...view,
  108. providers: [
  109. {
  110. ...view.providers[0],
  111. models: [
  112. {
  113. modelId: "GLM-5.3",
  114. config: { optionSpecs: { reasoningLevel: { values: ["low", "high", "max"] } } },
  115. },
  116. ],
  117. },
  118. ],
  119. });
  120. const onSelectModel = vi.fn();
  121. const { result } = renderHook(() =>
  122. useComposerConnectionSwitch({
  123. workspacePath: "/work",
  124. agentProvider: "glm",
  125. normalizedValue: encodeCustomModelValue("ordinary-api", "GLM-5.3"),
  126. onSelectModel,
  127. }),
  128. );
  129. await act(async () => {
  130. await result.current.select(connection);
  131. });
  132. expect(onSelectModel).toHaveBeenCalledWith(
  133. encodeCustomModelValue(providerId, "GLM-5.3"),
  134. "max",
  135. );
  136. });
  137. it.each(["account:bigmodel-individual-coding-plan", providerId])(
  138. "同一账号族的同名模型只切连接,不重新选模清空 reasoning:%s",
  139. async (sourceProvider) => {
  140. const onSelectModel = vi.fn();
  141. const { result } = renderHook(() =>
  142. useComposerConnectionSwitch({
  143. workspacePath: "/work",
  144. agentProvider: "glm",
  145. normalizedValue: encodeCustomModelValue(sourceProvider, "GLM-5.3"),
  146. onSelectModel,
  147. }),
  148. );
  149. await act(async () => {
  150. await result.current.select(connection);
  151. });
  152. expect(mocks.update).toHaveBeenCalledTimes(1);
  153. expect(onSelectModel).not.toHaveBeenCalled();
  154. expect(result.current.error).toBeNull();
  155. },
  156. );
  157. it.each([
  158. ["individual-coding-plan", "team-coding-plan"],
  159. ["team-coding-plan", "individual-coding-plan"],
  160. ] as const)("同名账号模型等待有效选择呈现后结束 loading,并可切回:%s → %s", async (from, to) => {
  161. const id = (kind: string) => `account:bigmodel-${kind}`;
  162. const original = {
  163. providerId: id(from),
  164. modelId: "GLM-5.3",
  165. options: { reasoningLevel: "high" },
  166. };
  167. const catalog = {
  168. ...view,
  169. providers: [from, to].map((kind) => ({
  170. ...view.providers[0],
  171. providerId: id(kind),
  172. config: {
  173. ...view.providers[0]!.config,
  174. access: {
  175. type: "zhipu-account",
  176. accountType: "bigmodel",
  177. mode: kind,
  178. },
  179. },
  180. models: [
  181. {
  182. modelId: "GLM-5.3",
  183. config: {
  184. optionSpecs: { reasoningLevel: { values: ["low", "high", "max"] } },
  185. },
  186. },
  187. ],
  188. })),
  189. };
  190. mocks.settings.providerFamilyConnectionSelections = { bigmodel: { kind: from } };
  191. mocks.base.modelSelectionService.getView.mockResolvedValue(catalog);
  192. const onSelectModel = vi.fn();
  193. const { result } = renderHook(() => {
  194. const current = (
  195. mocks.settings.providerFamilyConnectionSelections as {
  196. bigmodel: { kind: string };
  197. }
  198. ).bigmodel.kind;
  199. // 对齐生产草稿 owner:保留原意图,展示与提交消费 Host 解析的有效选择。
  200. const selection = resolveEffectiveModelSelection({
  201. selection: original,
  202. registry: catalog as unknown as ProviderRegistryView,
  203. classifyProvider: () => "account-plan",
  204. accountStates: {
  205. [id(current)]: { availability: "available", entitled: true, current: true },
  206. },
  207. }).effectiveSelection!;
  208. const switching = useComposerConnectionSwitch({
  209. workspacePath: "/work",
  210. agentProvider: "glm",
  211. normalizedValue: encodeCustomModelValue(selection.providerId, selection.modelId),
  212. waitForPresentation: true,
  213. presentationStatus: "ready",
  214. onSelectModel,
  215. });
  216. return { ...switching, selection };
  217. });
  218. for (const kind of [to, from]) {
  219. await act(async () => {
  220. await result.current.select({
  221. ...connection,
  222. providerId: id(kind),
  223. key: kind,
  224. selection:
  225. kind === "individual-coding-plan" ? { kind } : { ...connection.selection!, kind },
  226. });
  227. });
  228. expect(result.current.pending).toBe(false);
  229. expect(result.current.error).toBeNull();
  230. expect(result.current.selection).toEqual({ ...original, providerId: id(kind) });
  231. expect(onSelectModel).not.toHaveBeenCalled();
  232. }
  233. expect(mocks.update).toHaveBeenCalledTimes(2);
  234. expect(original.providerId).toBe(id(from));
  235. });
  236. it("不同 workspaceIdentity 即使路径相同也拒绝旧结果", async () => {
  237. const wait = deferred<typeof view>();
  238. mocks.base.modelSelectionService.getView.mockReturnValueOnce(wait.promise);
  239. const onSelectModel = vi.fn();
  240. const { result, rerender } = renderHook(
  241. ({ identity }) =>
  242. useComposerConnectionSwitch({
  243. workspacePath: "/work",
  244. workspaceIdentity: identity,
  245. agentProvider: "glm",
  246. normalizedValue: "",
  247. onSelectModel,
  248. }),
  249. { initialProps: { identity: "ssh:first" } },
  250. );
  251. let task!: Promise<void>;
  252. await act(async () => {
  253. task = result.current.select(connection);
  254. await Promise.resolve();
  255. });
  256. rerender({ identity: "ssh:second" });
  257. await act(async () => {
  258. wait.resolve(view);
  259. await task;
  260. });
  261. expect(onSelectModel).not.toHaveBeenCalled();
  262. });
  263. it("同步失败恢复原身份并允许重试", async () => {
  264. mocks.base.providerSettingsService.refresh.mockRejectedValueOnce(new Error("offline"));
  265. const onSelectModel = vi.fn();
  266. const { result } = renderHook(() =>
  267. useComposerConnectionSwitch({
  268. workspacePath: "/work",
  269. agentProvider: "glm",
  270. normalizedValue: "",
  271. onSelectModel,
  272. }),
  273. );
  274. await act(async () => {
  275. await result.current.select(connection);
  276. });
  277. expect(result.current.error).toContain("retry");
  278. expect(onSelectModel).not.toHaveBeenCalled();
  279. expect(mocks.settings.providerFamilyConnectionSelections).toEqual({
  280. bigmodel: { kind: "individual-coding-plan" },
  281. });
  282. await act(async () => {
  283. await result.current.select(connection);
  284. });
  285. expect(onSelectModel).toHaveBeenCalledTimes(1);
  286. expect(result.current.error).toBeNull();
  287. });
  288. it("远端目录仍是旧团队身份时拒绝提交,即使同名模型存在", async () => {
  289. mocks.base.providerSettingsService.refresh.mockResolvedValue({
  290. providers: [{ providerId, accountState: { connectionKey: "new-team" } }],
  291. } as never);
  292. mocks.target = {
  293. ...mocks.base,
  294. providerSettingsService: {
  295. refresh: vi.fn().mockResolvedValue({
  296. providers: [{ providerId, accountState: { connectionKey: "old-team" } }],
  297. }),
  298. },
  299. modelSelectionService: { getView: vi.fn().mockResolvedValue(view) },
  300. };
  301. const onSelectModel = vi.fn();
  302. const { result } = renderHook(() =>
  303. useComposerConnectionSwitch({
  304. workspacePath: "/work",
  305. workspaceIdentity: "ssh:host",
  306. agentProvider: "glm",
  307. normalizedValue: "",
  308. onSelectModel,
  309. }),
  310. );
  311. await act(async () => {
  312. await result.current.select(connection);
  313. });
  314. expect(onSelectModel).not.toHaveBeenCalled();
  315. expect(result.current.error).toContain("retry");
  316. expect(mocks.settings.providerFamilyConnectionSelections).toEqual({
  317. bigmodel: { kind: "individual-coding-plan" },
  318. });
  319. });
  320. it("连接读取完成后仍 loading,直到界面确认目标选择", async () => {
  321. const onSelectModel = vi.fn();
  322. const { result, rerender } = renderHook(
  323. ({ value, status }) =>
  324. useComposerConnectionSwitch({
  325. workspacePath: "/work",
  326. agentProvider: "glm",
  327. normalizedValue: value,
  328. waitForPresentation: true,
  329. presentationStatus: status as "loading" | "ready",
  330. onSelectModel,
  331. }),
  332. { initialProps: { value: encodeCustomModelValue("api", "model"), status: "loading" } },
  333. );
  334. await act(async () => {
  335. await result.current.select(connection, "previous");
  336. });
  337. expect(result.current.pending).toBe(true);
  338. rerender({ value: encodeCustomModelValue(providerId, "GLM-5.3"), status: "ready" });
  339. expect(result.current.pending).toBe(false);
  340. });
  341. it("展示读取失败会解除等待并显示可重试错误", async () => {
  342. const { result, rerender } = renderHook(
  343. ({ status }: { status: "loading" | "error" }) =>
  344. useComposerConnectionSwitch({
  345. workspacePath: "/work",
  346. agentProvider: "glm",
  347. normalizedValue: "",
  348. waitForPresentation: true,
  349. presentationStatus: status,
  350. onSelectModel: vi.fn(),
  351. }),
  352. { initialProps: { status: "loading" } },
  353. );
  354. await act(async () => {
  355. await result.current.select(connection);
  356. });
  357. expect(result.current.pending).toBe(true);
  358. rerender({ status: "error" });
  359. expect(result.current.pending).toBe(false);
  360. expect(result.current.error).toBeTruthy();
  361. });
  362. it("API 选择不写套餐设置", async () => {
  363. const onSelectModel = vi.fn();
  364. const { result } = renderHook(() =>
  365. useComposerConnectionSwitch({
  366. workspacePath: "/work",
  367. agentProvider: "glm",
  368. normalizedValue: "",
  369. onSelectModel,
  370. }),
  371. );
  372. await act(async () => {
  373. await result.current.select({ ...connection, selection: undefined });
  374. });
  375. expect(mocks.update).not.toHaveBeenCalled();
  376. expect(onSelectModel).toHaveBeenCalledTimes(1);
  377. });
  378. });
  379. describe("Connection rollback ownership", () => {
  380. it.each(["zai", "bigmodel"] as const)(
  381. "另一窗口更新品牌版本 %s 后,旧请求失败不能覆盖新意图",
  382. async (nextFamily) => {
  383. let settings: Partial<AppSettings> = {
  384. providerFamilyDomain: "bigmodel",
  385. providerFamilyDomainUpdatedAt: 1,
  386. providerFamilyConnectionSelections: { bigmodel: { kind: "individual-coding-plan" } },
  387. };
  388. const update = vi.fn(async (patch: Partial<AppSettings>) => {
  389. settings = { ...settings, ...patch };
  390. });
  391. const synchronize = vi.fn(async () => {
  392. settings = {
  393. ...settings,
  394. providerFamilyDomain: nextFamily,
  395. providerFamilyDomainUpdatedAt: (settings.providerFamilyDomainUpdatedAt ?? 0) + 1,
  396. providerFamilyConnectionSelections: {
  397. ...settings.providerFamilyConnectionSelections,
  398. zai: { kind: "individual-coding-plan" },
  399. },
  400. };
  401. throw new Error("synchronization failed");
  402. });
  403. await expect(
  404. persistProviderFamilyConnection({
  405. family: "bigmodel",
  406. selection: connection.selection!,
  407. read: async () => structuredClone(settings),
  408. update,
  409. synchronize,
  410. }),
  411. ).rejects.toThrow("synchronization failed");
  412. expect(settings.providerFamilyDomain).toBe(nextFamily);
  413. expect(settings.providerFamilyConnectionSelections?.zai).toEqual({
  414. kind: "individual-coding-plan",
  415. });
  416. expect(update).toHaveBeenCalledTimes(1);
  417. expect(synchronize).toHaveBeenCalledTimes(1);
  418. },
  419. );
  420. });
  421. describe("CAS connection admission", () => {
  422. it("两个 deferred 请求同读后写:后写冲突,不抹掉先写的 family", async () => {
  423. let settings: Partial<AppSettings> = {
  424. providerFamilyDomain: "bigmodel",
  425. providerFamilyConnectionSelections: {},
  426. };
  427. const reads = [deferred<Partial<AppSettings>>(), deferred<Partial<AppSettings>>()];
  428. let readCount = 0;
  429. const update = vi.fn(async (patch: Partial<AppSettings>, expected?: Partial<AppSettings>) => {
  430. if (
  431. !expected ||
  432. expected.providerFamilyDomain !== settings.providerFamilyDomain ||
  433. JSON.stringify(expected.providerFamilyConnectionSelections) !==
  434. JSON.stringify(settings.providerFamilyConnectionSelections)
  435. )
  436. throw new Error("Account connection settings changed");
  437. settings = { ...settings, ...patch };
  438. });
  439. const read = () => reads[readCount++]!.promise;
  440. const synchronize = vi.fn(async () => undefined);
  441. const first = persistProviderFamilyConnection({
  442. family: "bigmodel",
  443. selection: connection.selection!,
  444. read,
  445. update,
  446. synchronize,
  447. });
  448. const second = persistProviderFamilyConnection({
  449. family: "zai",
  450. selection: { kind: "individual-coding-plan" },
  451. read,
  452. update,
  453. synchronize,
  454. });
  455. const rejected = expect(second).rejects.toThrow("Account connection settings changed");
  456. const snapshot = structuredClone(settings);
  457. reads[0]!.resolve(snapshot);
  458. await first;
  459. reads[1]!.resolve(snapshot);
  460. await rejected;
  461. expect(settings.providerFamilyConnectionSelections).toEqual({ bigmodel: connection.selection });
  462. expect(synchronize).toHaveBeenCalledTimes(1);
  463. });
  464. it("回滚检查后有另一写入:锁内 CAS 不撤销成功设置", async () => {
  465. let settings: Partial<AppSettings> = {
  466. providerFamilyDomain: "bigmodel",
  467. providerFamilyConnectionSelections: {},
  468. };
  469. let writes = 0;
  470. const update = vi.fn(async (patch: Partial<AppSettings>, expected?: Partial<AppSettings>) => {
  471. if (++writes === 2)
  472. settings = {
  473. ...settings,
  474. providerFamilyDomain: "zai",
  475. providerFamilyConnectionSelections: {
  476. ...settings.providerFamilyConnectionSelections,
  477. zai: { kind: "individual-coding-plan" },
  478. },
  479. };
  480. if (
  481. expected &&
  482. (expected.providerFamilyDomain !== settings.providerFamilyDomain ||
  483. JSON.stringify(expected.providerFamilyConnectionSelections) !==
  484. JSON.stringify(settings.providerFamilyConnectionSelections))
  485. )
  486. throw new Error("Account connection settings changed");
  487. settings = { ...settings, ...patch };
  488. });
  489. const synchronize = vi.fn(async () => {
  490. throw new Error("offline");
  491. });
  492. await expect(
  493. persistProviderFamilyConnection({
  494. family: "bigmodel",
  495. selection: connection.selection!,
  496. read: async () => structuredClone(settings),
  497. update,
  498. synchronize,
  499. }),
  500. ).rejects.toThrow("offline");
  501. expect(settings.providerFamilyDomain).toBe("zai");
  502. expect(settings.providerFamilyConnectionSelections?.bigmodel).toEqual(connection.selection);
  503. expect(settings.providerFamilyConnectionSelections?.zai).toEqual({
  504. kind: "individual-coding-plan",
  505. });
  506. expect(synchronize).toHaveBeenCalledTimes(1);
  507. });
  508. it("后一个请求同步失败:只恢复它提交前的设置,保留前一个成功 family", async () => {
  509. let settings: Partial<AppSettings> = {
  510. providerFamilyDomain: "bigmodel",
  511. providerFamilyConnectionSelections: {},
  512. };
  513. const update = async (patch: Partial<AppSettings>, expected?: Partial<AppSettings>) => {
  514. if (
  515. expected &&
  516. JSON.stringify(expected.providerFamilyConnectionSelections) !==
  517. JSON.stringify(settings.providerFamilyConnectionSelections)
  518. )
  519. throw new Error("Account connection settings changed");
  520. settings = { ...settings, ...patch };
  521. };
  522. const read = async () => structuredClone(settings);
  523. await persistProviderFamilyConnection({
  524. family: "bigmodel",
  525. selection: connection.selection!,
  526. read,
  527. update,
  528. synchronize: async () => undefined,
  529. });
  530. const synchronize = vi.fn(async (restoring?: boolean) => {
  531. if (!restoring) throw new Error("offline");
  532. });
  533. await expect(
  534. persistProviderFamilyConnection({
  535. family: "zai",
  536. selection: { kind: "individual-coding-plan" },
  537. read,
  538. update,
  539. synchronize,
  540. }),
  541. ).rejects.toThrow("offline");
  542. expect(settings.providerFamilyConnectionSelections?.bigmodel).toEqual(connection.selection);
  543. expect(settings.providerFamilyConnectionSelections?.zai).toBeUndefined();
  544. expect(settings.providerFamilyDomain).toBe("bigmodel");
  545. expect(synchronize).toHaveBeenCalledWith(true);
  546. });
  547. });
  548. it("ready 不匹配解除 pending,显示错误并允许下一次选择", async () => {
  549. const { result, rerender } = renderHook(
  550. ({ status, value }) =>
  551. useComposerConnectionSwitch({
  552. workspacePath: "/work",
  553. agentProvider: "glm",
  554. normalizedValue: value,
  555. waitForPresentation: true,
  556. presentationStatus: status as "loading" | "ready",
  557. onSelectModel: vi.fn(),
  558. }),
  559. { initialProps: { status: "loading", value: "" } },
  560. );
  561. await act(async () => {
  562. await result.current.select(connection);
  563. });
  564. expect(result.current.pending).toBe(true);
  565. rerender({ status: "ready", value: "another/model" });
  566. expect(result.current.pending).toBe(false);
  567. expect(result.current.error).toContain("retry");
  568. rerender({ status: "loading", value: "" });
  569. await act(async () => {
  570. await result.current.select(connection);
  571. });
  572. expect(result.current.pending).toBe(true);
  573. rerender({ status: "ready", value: encodeCustomModelValue(providerId, "GLM-5.3") });
  574. expect(result.current.error).toBeNull();
  575. expect(result.current.pending).toBe(false);
  576. });
  577. it("旧 ready 不是本次展示回执:等待目标 revision,再对不匹配结果结束并报错", async () => {
  578. const { result, rerender } = renderHook(
  579. ({ revision, errorRevision }) =>
  580. useComposerConnectionSwitch({
  581. workspacePath: "/work",
  582. agentProvider: "glm",
  583. normalizedValue: "old/model",
  584. waitForPresentation: true,
  585. presentationStatus: "ready",
  586. presentationRevision: revision,
  587. presentationErrorRevision: errorRevision,
  588. onSelectModel: vi.fn(),
  589. }),
  590. { initialProps: { revision: 1, errorRevision: 1 as number | undefined } },
  591. );
  592. await act(async () => {
  593. await result.current.select(connection);
  594. });
  595. expect(result.current.pending).toBe(true);
  596. expect(result.current.error).toBeNull();
  597. rerender({ revision: 2, errorRevision: undefined });
  598. expect(result.current.pending).toBe(false);
  599. expect(result.current.error).toContain("retry");
  600. });
  601. it("回滚前另一操作重新选择相同身份,也必须由操作版本 CAS 保护", async () => {
  602. let settings: Partial<AppSettings> = {
  603. providerFamilyDomain: "bigmodel",
  604. providerFamilyDomainUpdatedAt: 1,
  605. providerFamilyConnectionSelections: { bigmodel: { kind: "individual-coding-plan" } },
  606. };
  607. let writes = 0;
  608. const update = async (patch: Partial<AppSettings>, expected?: Partial<AppSettings>) => {
  609. if (++writes === 2)
  610. settings = {
  611. ...settings,
  612. providerFamilyDomainUpdatedAt: (settings.providerFamilyDomainUpdatedAt ?? 0) + 1,
  613. };
  614. if (expected?.providerFamilyDomainUpdatedAt !== settings.providerFamilyDomainUpdatedAt)
  615. throw new Error("Account connection settings changed");
  616. settings = { ...settings, ...patch };
  617. };
  618. await expect(
  619. persistProviderFamilyConnection({
  620. family: "bigmodel",
  621. selection: connection.selection!,
  622. read: async () => structuredClone(settings),
  623. update,
  624. synchronize: async () => {
  625. throw new Error("offline");
  626. },
  627. }),
  628. ).rejects.toThrow("offline");
  629. expect(settings.providerFamilyConnectionSelections?.bigmodel).toEqual(connection.selection);
  630. });
  631. it("真实展示 hook 保留旧 ready 时,目标刷新失败也必须结束连接等待并允许重试", async () => {
  632. let listener: ((candidate: any) => void) | undefined;
  633. let failPresentation = false;
  634. let revision = 1;
  635. const initial = { ...view, revision: 1, effectiveSelection: { providerId, modelId: "GLM-5.3" } };
  636. mocks.base.modelSelectionService.onDidChange.mockImplementation((callback: any) => {
  637. listener = callback;
  638. return { dispose: vi.fn() };
  639. });
  640. mocks.base.modelSelectionService.getView.mockImplementation(async (input?: unknown) => {
  641. if (input && failPresentation) throw new Error("presentation failed");
  642. return input ? { ...initial, revision } : view;
  643. });
  644. mocks.base.providerSettingsService.refresh.mockImplementation(async () => {
  645. if (revision === 1) listener?.(view);
  646. revision = 2;
  647. return undefined;
  648. });
  649. const value = encodeCustomModelValue(providerId, "GLM-5.3");
  650. const hook = renderHook(() => {
  651. const presentation = useModelSelectionServiceView(
  652. mocks.base.modelSelectionService as any,
  653. true,
  654. "remote-waiting",
  655. {
  656. selection: { providerId, modelId: "GLM-5.3" },
  657. },
  658. );
  659. const state = presentation.state;
  660. return useComposerConnectionSwitch({
  661. workspacePath: "/work",
  662. agentProvider: "glm",
  663. normalizedValue: value,
  664. onSelectModel: vi.fn(),
  665. waitForPresentation: true,
  666. refreshPresentation: presentation.refresh,
  667. presentationStatus: state.status,
  668. presentationRevision: state.status === "ready" ? state.view.revision : undefined,
  669. presentationErrorRevision:
  670. state.status === "ready" ? state.refreshError?.revision : undefined,
  671. });
  672. });
  673. await waitFor(() => expect(mocks.base.modelSelectionService.getView).toHaveBeenCalled());
  674. failPresentation = true;
  675. await act(async () => {
  676. await hook.result.current.select(connection);
  677. });
  678. await waitFor(() => expect(hook.result.current.pending).toBe(false));
  679. expect(hook.result.current.error).toContain("retry");
  680. failPresentation = false;
  681. await act(async () => {
  682. await hook.result.current.select(connection);
  683. });
  684. expect(mocks.update).toHaveBeenCalledTimes(2);
  685. expect(hook.result.current.pending).toBe(false);
  686. expect(hook.result.current.error).toBeNull();
  687. });
  688. it("真实展示 hook 的旧读取失败不能否定新输入已成功的连接切换", async () => {
  689. let rejectOld!: (error: Error) => void;
  690. let oldStarted = false;
  691. let armed = false;
  692. const effective = { ...view, effectiveSelection: { providerId, modelId: "GLM-5.3" } };
  693. mocks.base.modelSelectionService.getView.mockImplementation((input?: unknown) => {
  694. if (input && armed && !oldStarted) {
  695. oldStarted = true;
  696. return new Promise((_resolve, reject) => {
  697. rejectOld = reject;
  698. });
  699. }
  700. return Promise.resolve(effective);
  701. });
  702. const value = encodeCustomModelValue(providerId, "GLM-5.3");
  703. const hook = renderHook(
  704. ({ reasoning }) => {
  705. const presentation = useModelSelectionServiceView(
  706. mocks.base.modelSelectionService as any,
  707. true,
  708. "remote-waiting",
  709. {
  710. selection: { providerId, modelId: "GLM-5.3", options: { reasoningLevel: reasoning } },
  711. },
  712. );
  713. const state = presentation.state;
  714. return {
  715. state,
  716. connection: useComposerConnectionSwitch({
  717. workspacePath: "/work",
  718. agentProvider: "glm",
  719. normalizedValue: value,
  720. onSelectModel: vi.fn(),
  721. waitForPresentation: true,
  722. refreshPresentation: presentation.refresh,
  723. presentationStatus: state.status,
  724. presentationRevision: state.status === "ready" ? state.view.revision : undefined,
  725. presentationErrorRevision:
  726. state.status === "ready" ? state.refreshError?.revision : undefined,
  727. }),
  728. };
  729. },
  730. { initialProps: { reasoning: "disabled" } },
  731. );
  732. await waitFor(() => expect(hook.result.current.state.status).toBe("ready"));
  733. armed = true;
  734. let operation!: Promise<void>;
  735. await act(async () => {
  736. operation = hook.result.current.connection.select(connection);
  737. });
  738. await waitFor(() => expect(oldStarted).toBe(true));
  739. hook.rerender({ reasoning: "enabled" });
  740. await waitFor(() => expect(hook.result.current.state.status).toBe("ready"));
  741. await act(async () => {
  742. rejectOld(new Error("obsolete input failed"));
  743. await operation;
  744. });
  745. await waitFor(() => expect(hook.result.current.connection.pending).toBe(false));
  746. expect(hook.result.current.connection.error).toBeNull();
  747. });