listModelsToolCard.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. // @vitest-environment jsdom
  2. import { cleanup, render, screen } from "@testing-library/react";
  3. import { createElement } from "react";
  4. import { afterEach, describe, expect, it } from "vitest";
  5. import { BUILTIN_MODEL_PROVIDER_IDS } from "@zcode/shared";
  6. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  7. import { resolveToolCallRenderer } from "@/ToolCallBlocks/resolveRenderer.js";
  8. import {
  9. formatContextWindow,
  10. ListModelsToolCallBlock,
  11. readListModelsResult,
  12. } from "@/ToolCallBlocks/renderers/list-models.js";
  13. import type { ToolCallBlockRenderContext } from "@/ToolCallBlocks/shared.js";
  14. // 团队套餐的 providerId 是一个 UUID。它是本卡最重要的负面断言:一个字符都不该上屏。
  15. const TEAM_PROVIDER_UUID = "4fc7f541-2382-4c32-be11-f021b8d7ed1d";
  16. const BUILTIN_BIGMODEL_PROVIDER_ID = BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan;
  17. const CURRENT_MODEL_ID = `${BUILTIN_BIGMODEL_PROVIDER_ID}/GLM-5.3-Flash`;
  18. const LIST_MODELS_DISPLAY = {
  19. kind: "list_models",
  20. current: CURRENT_MODEL_ID,
  21. models: [
  22. {
  23. id: CURRENT_MODEL_ID,
  24. providerId: BUILTIN_BIGMODEL_PROVIDER_ID,
  25. modelId: "GLM-5.3-Flash",
  26. reasoningLevels: ["low", "medium", "high"],
  27. defaultReasoningLevel: "high",
  28. contextWindow: 128_000,
  29. },
  30. {
  31. id: `${BUILTIN_BIGMODEL_PROVIDER_ID}/GLM-5.3`,
  32. providerId: BUILTIN_BIGMODEL_PROVIDER_ID,
  33. modelId: "GLM-5.3",
  34. reasoningLevels: ["low", "medium", "high", "max"],
  35. defaultReasoningLevel: "max",
  36. contextWindow: 200_000,
  37. },
  38. {
  39. id: `${TEAM_PROVIDER_UUID}/glm-4.7`,
  40. providerId: TEAM_PROVIDER_UUID,
  41. modelId: "glm-4.7",
  42. providerLabel: "MyProxy",
  43. reasoningLevels: [],
  44. contextWindow: 1_000_000,
  45. },
  46. {
  47. id: `${TEAM_PROVIDER_UUID}/deepseek-v4`,
  48. providerId: TEAM_PROVIDER_UUID,
  49. modelId: "deepseek-v4",
  50. providerLabel: "MyProxy",
  51. reasoningLevels: [],
  52. disabledReason: "no API key",
  53. contextWindow: 128_000,
  54. },
  55. ],
  56. } as const;
  57. function buildContext(
  58. toolCall: Record<string, unknown>,
  59. overrides: Partial<ToolCallBlockRenderContext> = {},
  60. ): ToolCallBlockRenderContext {
  61. return {
  62. toolCallNode: { toolCall, childToolCalls: [] },
  63. workspacePath: "/workspace",
  64. displayModel: {
  65. inlinePreview: { type: "none" },
  66. planResult: null,
  67. viewerSource: null,
  68. viewerLabelId: "codeViewer.viewCode",
  69. showSummaryFileLink: false,
  70. showInput: false,
  71. showOutput: false,
  72. showKind: false,
  73. },
  74. viewerSource: null,
  75. rawFileSummaries: [],
  76. isRunning: false,
  77. statusLabel: "",
  78. childToolList: null,
  79. showIcon: true,
  80. // 卡体默认折叠,测试里强制展开以断言内容。
  81. forceOpen: true,
  82. canToggle: false,
  83. ...overrides,
  84. } as ToolCallBlockRenderContext;
  85. }
  86. function renderCard(
  87. component: (context: ToolCallBlockRenderContext) => unknown,
  88. context: ToolCallBlockRenderContext,
  89. locale: "en-US" | "zh-CN" = "en-US",
  90. ) {
  91. return render(
  92. createElement(
  93. ZCodeIntlProvider,
  94. { initialLocale: locale },
  95. createElement(component as never, context),
  96. ),
  97. );
  98. }
  99. /** 行按 data-model-id 取:模型 id 里有 `/` 与 `:`,这个 jsdom 没有 CSS.escape。 */
  100. function rowByModelId(modelId: string): Element | undefined {
  101. return [...document.querySelectorAll("[data-model-id]")].find(
  102. (element) => element.getAttribute("data-model-id") === modelId,
  103. );
  104. }
  105. /** `null` 表示这次调用没有 display 通道(老会话 / 降级路径);缺省参数会把 undefined 吃掉。 */
  106. function buildListModelsToolCall(
  107. display: unknown = LIST_MODELS_DISPLAY,
  108. overrides: Record<string, unknown> = {},
  109. ) {
  110. return {
  111. toolId: "tool-list-models-1",
  112. toolName: "ListModels",
  113. kind: "ListModels",
  114. title: "ListModels",
  115. status: "completed",
  116. input: {},
  117. // v4 wire 上 output.text 是模型面的 `<models>` 投影;结构化目录只走 display 通道。
  118. output: '<models count="4">…</models>',
  119. ...(display === null ? {} : { raw: { display } }),
  120. ...overrides,
  121. };
  122. }
  123. afterEach(cleanup);
  124. describe("resolveToolCallRenderer list-models dispatch", () => {
  125. it("routes ListModels by name in both wire spellings", () => {
  126. // 前置事实:这个名字不在 shared 的已知工具表里,identity 会回 unknown。
  127. expect(resolveToolCallRenderer(buildContext(buildListModelsToolCall()))).toBe(
  128. ListModelsToolCallBlock,
  129. );
  130. const snakeCase = {
  131. ...buildListModelsToolCall(),
  132. toolName: "list_models",
  133. kind: "list_models",
  134. title: "list_models",
  135. };
  136. expect(resolveToolCallRenderer(buildContext(snakeCase))).toBe(ListModelsToolCallBlock);
  137. });
  138. it("does not steal ListSavedWorkflows", () => {
  139. const savedWorkflows = {
  140. toolId: "tool-list-saved-1",
  141. toolName: "ListSavedWorkflows",
  142. kind: "ListSavedWorkflows",
  143. title: "ListSavedWorkflows",
  144. status: "completed",
  145. input: {},
  146. };
  147. expect(resolveToolCallRenderer(buildContext(savedWorkflows))).not.toBe(ListModelsToolCallBlock);
  148. });
  149. });
  150. describe("formatContextWindow", () => {
  151. it("reads as K below a million and as M above it", () => {
  152. expect(formatContextWindow(128_000)).toBe("128K");
  153. expect(formatContextWindow(200_000)).toBe("200K");
  154. expect(formatContextWindow(1_000_000)).toBe("1M");
  155. expect(formatContextWindow(1_500_000)).toBe("1.5M");
  156. // 千位以下原样:一个四位数的窗口没有可缩写的东西。
  157. expect(formatContextWindow(512)).toBe("512");
  158. });
  159. });
  160. describe("ListModelsToolCallBlock", () => {
  161. it("prefers the list_models display over the model-facing text projection", () => {
  162. const result = readListModelsResult(buildListModelsToolCall());
  163. expect(result?.models).toHaveLength(4);
  164. expect(result?.current).toBe(CURRENT_MODEL_ID);
  165. // 读不懂就是 null——空目录与解析失败必须可分辨。
  166. expect(readListModelsResult(buildListModelsToolCall(null))).toBeNull();
  167. });
  168. it("names the count, groups by provider name, and never prints a provider id", () => {
  169. renderCard(ListModelsToolCallBlock, buildContext(buildListModelsToolCall()));
  170. expect(screen.getByText("Available models")).toBeTruthy();
  171. expect(screen.getByText("4 models")).toBeTruthy();
  172. // 内置家族 → 家族名;自定义 provider → 载荷里的 providerLabel。
  173. expect(screen.getByText("BigModel")).toBeTruthy();
  174. expect(screen.getByText("MyProxy")).toBeTruthy();
  175. expect(screen.getByText("GLM-5.3-Flash")).toBeTruthy();
  176. expect(screen.getByText("glm-4.7")).toBeTruthy();
  177. // 本卡最重要的负面断言:UUID 与内置 providerId 一个字符都不上屏。
  178. expect(document.body.textContent).not.toContain(TEAM_PROVIDER_UUID);
  179. expect(document.body.textContent).not.toContain(BUILTIN_BIGMODEL_PROVIDER_ID);
  180. // 通用兜底会打印整包 toolCall;专用卡必须没有这些结构键。
  181. expect(document.body.textContent).not.toContain('"toolId"');
  182. expect(document.body.textContent).not.toContain("models count");
  183. });
  184. it("marks only the session's own model as current and shows the context window", () => {
  185. renderCard(ListModelsToolCallBlock, buildContext(buildListModelsToolCall()));
  186. const currentTags = document.querySelectorAll('[data-model-current="true"]');
  187. expect(currentTags).toHaveLength(1);
  188. expect(currentTags[0]?.textContent).toBe("current");
  189. expect(rowByModelId(CURRENT_MODEL_ID)?.textContent).toContain("128K");
  190. // 不可选用的行把理由摆在模型名旁边。
  191. expect(screen.getByText("no API key")).toBeTruthy();
  192. });
  193. it("puts the thinking levels and the canonical id in the row tooltip", () => {
  194. renderCard(ListModelsToolCallBlock, buildContext(buildListModelsToolCall()));
  195. const title = rowByModelId(CURRENT_MODEL_ID)?.getAttribute("title") ?? "";
  196. expect(title).toContain("Thinking levels: Low · Medium · High (default High)");
  197. // 规范 id 只住在 tooltip 里——它是给机器回填 subagent_model 用的。
  198. expect(title).toContain(CURRENT_MODEL_ID);
  199. expect(rowByModelId(`${TEAM_PROVIDER_UUID}/glm-4.7`)?.getAttribute("title")).toContain(
  200. "No thinking levels",
  201. );
  202. });
  203. it("says the host has none rather than showing an empty body", () => {
  204. renderCard(
  205. ListModelsToolCallBlock,
  206. buildContext(buildListModelsToolCall({ kind: "list_models", models: [] })),
  207. );
  208. expect(screen.getByText("No models are configured on this host")).toBeTruthy();
  209. // 一个模型也没有时没有可展开的内容。
  210. expect(document.querySelector('[data-model-list="true"]')).toBeNull();
  211. });
  212. it("notes truncation without reporting a second number", () => {
  213. renderCard(
  214. ListModelsToolCallBlock,
  215. buildContext(buildListModelsToolCall({ ...LIST_MODELS_DISPLAY, truncated: true })),
  216. );
  217. expect(screen.getByText("Not all models are shown")).toBeTruthy();
  218. });
  219. it("shows the status word on a failed call instead of an empty list", () => {
  220. renderCard(
  221. ListModelsToolCallBlock,
  222. buildContext(buildListModelsToolCall(null, { status: "failed" }), {
  223. statusLabel: "Failed",
  224. errorText: "model_catalog_unavailable: this session cannot list models",
  225. }),
  226. );
  227. expect(screen.getByText("Available models")).toBeTruthy();
  228. expect(screen.getByText("Failed")).toBeTruthy();
  229. // 「读不到目录」不是「没有模型」:卡上既不画列表也不说那句空话。
  230. expect(document.querySelector('[data-model-list="true"]')).toBeNull();
  231. expect(document.body.textContent).not.toContain("No models are configured on this host");
  232. });
  233. it("falls back to the generic card when the result is unreadable", () => {
  234. renderCard(ListModelsToolCallBlock, buildContext(buildListModelsToolCall(null)));
  235. expect(document.querySelector('[data-model-list="true"]')).toBeNull();
  236. expect(document.body.textContent).not.toContain("No models are configured on this host");
  237. });
  238. it("renders both locales", () => {
  239. renderCard(ListModelsToolCallBlock, buildContext(buildListModelsToolCall()), "zh-CN");
  240. expect(screen.getByText("可用模型")).toBeTruthy();
  241. expect(screen.getByText("4 个模型")).toBeTruthy();
  242. expect(document.querySelector('[data-model-current="true"]')?.textContent).toBe("当前");
  243. expect(rowByModelId(CURRENT_MODEL_ID)?.getAttribute("title")).toContain(
  244. "思考强度:低 · 中 · 高(默认 高)",
  245. );
  246. cleanup();
  247. renderCard(
  248. ListModelsToolCallBlock,
  249. buildContext(buildListModelsToolCall(), { isRunning: true }),
  250. "zh-CN",
  251. );
  252. expect(screen.getByText("正在列出模型")).toBeTruthy();
  253. });
  254. it("uses the singular count for one model", () => {
  255. renderCard(
  256. ListModelsToolCallBlock,
  257. buildContext(
  258. buildListModelsToolCall({
  259. kind: "list_models",
  260. models: [LIST_MODELS_DISPLAY.models[0]],
  261. }),
  262. ),
  263. );
  264. expect(screen.getByText("1 model")).toBeTruthy();
  265. });
  266. it("falls back to the word Provider when nothing names the provider", () => {
  267. renderCard(
  268. ListModelsToolCallBlock,
  269. buildContext(
  270. buildListModelsToolCall({
  271. kind: "list_models",
  272. models: [
  273. {
  274. id: `${TEAM_PROVIDER_UUID}/mystery-model`,
  275. providerId: TEAM_PROVIDER_UUID,
  276. modelId: "mystery-model",
  277. reasoningLevels: [],
  278. },
  279. ],
  280. }),
  281. ),
  282. );
  283. expect(screen.getByText("Provider")).toBeTruthy();
  284. expect(document.body.textContent).not.toContain(TEAM_PROVIDER_UUID);
  285. });
  286. });