runtime-product-access.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. import {
  2. requireTuiAgentAccess,
  3. requireTuiAccountLogin,
  4. } from "../../src/application/login-gate.js";
  5. import type { CliService } from "@mavis/local-runtime-v2/cli-service";
  6. import { describe, expect, it, vi } from "vitest";
  7. import { TuiRuntimeAdapter } from "../../src/runtime/adapter.js";
  8. import { buildTuiSkillCommands } from "../../src/tui/controller/run/active-run-flow.js";
  9. describe("TuiRuntimeAdapter product access", () => {
  10. it("forwards the shared Provider Presets and Codex OAuth capability", async () => {
  11. const listProviderPresets = vi.fn(async () => [
  12. {
  13. providerId: "openai",
  14. name: "OpenAI",
  15. baseUrl: "https://api.openai.com/v1",
  16. apiFormat: "openai-responses",
  17. models: [{ modelId: "gpt-5.6", toolCall: true }],
  18. },
  19. ]);
  20. const getCodexOAuthStatus = vi.fn(async () => ({
  21. state: "disconnected",
  22. providerId: "openai-codex",
  23. }));
  24. const startCodexOAuthLogin = vi.fn(async () => ({
  25. state: "pending",
  26. providerId: "openai-codex",
  27. authUrl: "https://auth.example",
  28. }));
  29. const cancelCodexOAuthLogin = vi.fn(async () => ({
  30. state: "disconnected",
  31. providerId: "openai-codex",
  32. }));
  33. const adapter = new TuiRuntimeAdapter({
  34. cancelCodexOAuthLogin,
  35. listProviderPresets,
  36. getCodexOAuthStatus,
  37. startCodexOAuthLogin,
  38. } as never);
  39. await expect(adapter.listProviderPresets()).resolves.toEqual([
  40. expect.objectContaining({
  41. providerId: "openai",
  42. apiFormat: "openai-responses",
  43. }),
  44. ]);
  45. await expect(adapter.getCodexOAuthStatus()).resolves.toMatchObject({
  46. state: "disconnected",
  47. });
  48. await expect(
  49. adapter.startCodexOAuthLogin({ method: "device_code" }),
  50. ).resolves.toMatchObject({
  51. state: "pending",
  52. authUrl: "https://auth.example",
  53. });
  54. expect(listProviderPresets).toHaveBeenCalledOnce();
  55. expect(getCodexOAuthStatus).toHaveBeenCalledOnce();
  56. expect(startCodexOAuthLogin).toHaveBeenCalledWith({
  57. method: "device_code",
  58. });
  59. await adapter.cancelCodexOAuthLogin("attempt-1");
  60. expect(cancelCodexOAuthLogin).toHaveBeenCalledWith("attempt-1");
  61. });
  62. it("uses the Runtime startup model projection without saving a global selection", async () => {
  63. const service = {
  64. listModels: vi.fn(async () => [
  65. { providerId: "minimax", modelId: "MiniMax-M3", selected: true },
  66. ]),
  67. selectModel: vi.fn(async () => true),
  68. };
  69. const adapter = new TuiRuntimeAdapter(service as never);
  70. await expect(adapter.listModels()).resolves.toEqual([
  71. { providerId: "minimax", modelId: "MiniMax-M3", selected: true },
  72. ]);
  73. expect(service.selectModel).not.toHaveBeenCalled();
  74. });
  75. it("keeps manual model selection available if no official legacy replacement exists", async () => {
  76. const work = {
  77. providerId: "custom_provider:work",
  78. modelId: "work-model",
  79. selected: false,
  80. };
  81. const selectModel = vi.fn(async () => true);
  82. const adapter = new TuiRuntimeAdapter({
  83. listModels: vi.fn(async () => [work]),
  84. selectModel,
  85. } as never);
  86. await expect(adapter.listModels()).resolves.toEqual([work]);
  87. expect(selectModel).not.toHaveBeenCalled();
  88. });
  89. it.each([
  90. "custom_provider:minimax-legacy",
  91. "custom_provider:minimax-legacy-2",
  92. ])(
  93. "uses the Runtime projection while preserving the stored Session alias: %s",
  94. async (providerId) => {
  95. const legacy = { providerId, modelId: "MiniMax-M3" };
  96. const official = { providerId: "minimax", modelId: "MiniMax-M3" };
  97. const service = {
  98. listModels: vi.fn(async () => [
  99. { ...official, selected: true },
  100. {
  101. providerId: "custom_provider:work",
  102. modelId: "work-model",
  103. selected: false,
  104. },
  105. ]),
  106. getSession: vi.fn(async () => ({ session: { model: legacy } })),
  107. getMessages: vi.fn(async () => ({ messages: [] })),
  108. selectModel: vi.fn(async () => true),
  109. };
  110. const adapter = new TuiRuntimeAdapter(service as never);
  111. const models = await adapter.listModels("session-1");
  112. expect(service.selectModel).not.toHaveBeenCalled();
  113. expect(models.find((model) => model.selected)).toEqual({
  114. ...official,
  115. selected: true,
  116. });
  117. expect(models.map((model) => model.providerId)).toEqual([
  118. "minimax",
  119. "custom_provider:work",
  120. ]);
  121. await expect(
  122. adapter.getContextSnapshot("session-1"),
  123. ).resolves.toMatchObject({
  124. model: { provider: "minimax", id: "MiniMax-M3" },
  125. });
  126. },
  127. );
  128. it("forwards tested provider candidates through the process-local Runtime", async () => {
  129. const saveUserModelProviderCandidate = vi.fn(async () => ({
  130. success: true,
  131. provider: { providerId: "custom_provider:deepseek" },
  132. }));
  133. const adapter = new TuiRuntimeAdapter({
  134. saveUserModelProviderCandidate,
  135. } as never);
  136. await expect(
  137. adapter.saveUserModelProviderCandidate({
  138. name: "DeepSeek",
  139. baseUrl: "https://api.deepseek.com/v1",
  140. apiKey: "sk-test",
  141. apiFormat: "openai-completions",
  142. models: [{ modelId: "deepseek-chat", toolCall: true }],
  143. modelId: "deepseek-chat",
  144. saveAndUse: true,
  145. }),
  146. ).resolves.toMatchObject({ success: true });
  147. expect(saveUserModelProviderCandidate).toHaveBeenCalledWith({
  148. candidate: {
  149. name: "DeepSeek",
  150. baseUrl: "https://api.deepseek.com/v1",
  151. apiKey: "sk-test",
  152. apiFormat: "openai-completions",
  153. models: [{ modelId: "deepseek-chat", toolCall: true }],
  154. },
  155. modelId: "deepseek-chat",
  156. saveAndUse: true,
  157. });
  158. });
  159. it("projects the process-local model catalog with the same thinking shape as Desktop", async () => {
  160. const listModels = vi.fn(async () => [
  161. {
  162. providerId: "custom_provider:openai",
  163. modelId: "gpt-5.6",
  164. thinkingConfig: { mode: "switchable", default_value: "true" },
  165. effortOptions: ["low", "high", "max"],
  166. },
  167. ]);
  168. const getSession = vi.fn(async () => ({ session: { id: "session-1" } }));
  169. const adapter = new TuiRuntimeAdapter({ listModels, getSession } as never);
  170. await expect(adapter.listModels("session-1")).resolves.toEqual([
  171. {
  172. providerId: "custom_provider:openai",
  173. modelId: "gpt-5.6",
  174. thinkingConfig: { mode: "switchable", defaultValue: "true" },
  175. effortOptions: ["low", "high", "max"],
  176. },
  177. ]);
  178. expect(listModels).toHaveBeenCalledWith({ sessionId: "session-1" });
  179. expect(getSession).not.toHaveBeenCalled();
  180. });
  181. it("reuses generated CliService usage, context, compaction, and Session contracts", async () => {
  182. const cliService = cliServiceFixture();
  183. const adapter = new TuiRuntimeAdapter(cliService);
  184. await expect(adapter.getSessionUsage("session-1")).resolves.toEqual({
  185. summary: { inputTokens: 10, outputTokens: 5, totalTokens: 15, turns: 1 },
  186. rows: [{ model: "minimax/MiniMax-M3" }],
  187. });
  188. await expect(adapter.getSessionUsageSummary("session-1")).resolves.toEqual({
  189. inputTokens: 10,
  190. cacheReadTokens: 80,
  191. cacheWriteTokens: 10,
  192. });
  193. expect(cliService.getSessionUsageSummary).toHaveBeenCalledWith({
  194. id: "session-1",
  195. });
  196. const signal = new AbortController().signal;
  197. const commits = adapter.watchSessionUsageCommits(signal);
  198. await expect(commits.next()).resolves.toEqual({
  199. done: false,
  200. value: "session-1",
  201. });
  202. expect(cliService.watchSessionUsageCommits).toHaveBeenCalledWith(signal);
  203. await expect(
  204. adapter.requestCompaction("session-1", "mavis", "keep decisions"),
  205. ).resolves.toMatchObject({
  206. success: true,
  207. sessionId: "session-1",
  208. tokensBefore: 100,
  209. tokensAfter: 40,
  210. });
  211. expect(cliService.requestCompaction).toHaveBeenCalledWith({
  212. name: "mavis",
  213. id: "session-1",
  214. reason: "ui_request",
  215. customInstructions: "keep decisions",
  216. });
  217. await expect(
  218. adapter.getContextSnapshot("session-1"),
  219. ).resolves.toMatchObject({
  220. status: "stale",
  221. model: { provider: "minimax", id: "MiniMax-M3", contextWindow: 1000 },
  222. contextUsage: {
  223. contextWindowTokens: 1000,
  224. usedTokens: 300,
  225. totalCountSource: "PROVIDER_USAGE_ANCHORED",
  226. },
  227. });
  228. expect(cliService.getMessages).toHaveBeenCalledWith({
  229. id: "session-1",
  230. limit: 80,
  231. });
  232. expect(cliService.listModels).toHaveBeenCalledWith({
  233. sessionId: "session-1",
  234. });
  235. await expect(adapter.getActiveRun("session-1")).resolves.toEqual({
  236. schemaVersion: 1,
  237. sessionId: "session-1",
  238. state: "running",
  239. turnId: "turn-1",
  240. actions: { steer: true },
  241. });
  242. expect(cliService.getActiveTurn).toHaveBeenCalledWith("session-1");
  243. });
  244. it("derives decision-blocked active state from generated interaction contracts", async () => {
  245. const cliService = cliServiceFixture();
  246. vi.mocked(cliService.listPendingPermissions).mockResolvedValueOnce({
  247. requests: [
  248. {
  249. requestId: "permission-1",
  250. sessionId: "session-1",
  251. agentName: "mavis",
  252. toolName: "bash",
  253. ruleContents: ["git status"],
  254. reason: "needs approval",
  255. allowAlwaysSupported: true,
  256. createdAt: 10,
  257. },
  258. ],
  259. });
  260. const adapter = new TuiRuntimeAdapter(cliService);
  261. await expect(adapter.getActiveRun("session-1")).resolves.toMatchObject({
  262. state: "decision-blocked",
  263. actions: { steer: false },
  264. });
  265. });
  266. it("does not advertise steer for a Turn owned by another Runtime", async () => {
  267. const cliService = cliServiceFixture();
  268. vi.mocked(cliService.getActiveTurn).mockResolvedValueOnce({
  269. turnId: "turn-foreign",
  270. busyReason: "turn",
  271. locallyOwned: false,
  272. });
  273. const adapter = new TuiRuntimeAdapter(cliService);
  274. await expect(adapter.getActiveRun("session-1")).resolves.toMatchObject({
  275. state: "running",
  276. turnId: "turn-foreign",
  277. actions: { steer: false },
  278. });
  279. });
  280. it("routes peripheral product capabilities through CliService", async () => {
  281. const adapter = new TuiRuntimeAdapter(cliServiceFixture());
  282. await expect(adapter.getAccountStatus("session-1")).resolves.toMatchObject({
  283. status: "ready",
  284. defaultModel: "minimax/MiniMax-M3",
  285. });
  286. await expect(adapter.getRuntimeDiagnostics()).resolves.toMatchObject({
  287. status: "ok",
  288. });
  289. await expect(adapter.getInstructionSources("/repo")).resolves.toEqual([
  290. { scope: "project", path: "/repo/AGENTS.md" },
  291. ]);
  292. await expect(adapter.getPermissionMode()).resolves.toBe("default");
  293. await expect(adapter.setPermissionMode("bypassPermissions")).resolves.toBe(
  294. "bypassPermissions",
  295. );
  296. await expect(adapter.listModels("session-1")).resolves.toEqual([
  297. {
  298. providerId: "minimax",
  299. modelId: "MiniMax-M3",
  300. selected: true,
  301. contextLimit: 400_000,
  302. },
  303. ]);
  304. await expect(adapter.listSkills("mavis")).resolves.toEqual({
  305. skills: [{ name: "review", enabled: true }],
  306. hasMore: false,
  307. });
  308. await expect(adapter.listMcpServers()).resolves.toEqual([
  309. { name: "browser", enabled: true, transport: "stdio" },
  310. ]);
  311. });
  312. it("projects only verified identity fields during lightweight account hydration", async () => {
  313. const tokenPlanAccountStatusGetter = vi.fn(async () => ({
  314. quotaState: "available" as const,
  315. quota: {
  316. fiveHour: { remainingPercent: 90, unlimited: false },
  317. weekly: { remainingPercent: 80, unlimited: false },
  318. },
  319. }));
  320. const service = cliServiceFixture();
  321. const adapter = new TuiRuntimeAdapter(service, {
  322. tokenPlanAccountStatusGetter,
  323. accountIdentityGetter: () => ({
  324. email: "dev@example.com",
  325. name: "Dev",
  326. accessToken: "never-project",
  327. }),
  328. });
  329. await expect(
  330. adapter.getAccountStatus(undefined, { includeMembership: false }),
  331. ).resolves.toMatchObject({
  332. modelSource: "token-plan",
  333. managedTokenPresent: true,
  334. });
  335. expect(tokenPlanAccountStatusGetter).not.toHaveBeenCalled();
  336. const account = await adapter.getAccountStatus(undefined, {
  337. includeMembership: false,
  338. });
  339. expect(account.identity).toEqual({ email: "dev@example.com", name: "Dev" });
  340. expect(JSON.stringify(account)).not.toContain("never-project");
  341. await expect(
  342. adapter.getAccountStatus(undefined, { includeMembership: true }),
  343. ).resolves.toMatchObject({
  344. tokenPlanQuotaState: "available",
  345. tokenPlanQuota: { fiveHour: { remainingPercent: 90 } },
  346. });
  347. expect(tokenPlanAccountStatusGetter).toHaveBeenCalledOnce();
  348. vi.mocked(service.getAccountStatus).mockResolvedValueOnce({
  349. auth: { tokenPresent: false },
  350. });
  351. expect(
  352. (await adapter.getAccountStatus(undefined, { includeMembership: false }))
  353. .identity,
  354. ).toBeUndefined();
  355. });
  356. it("keeps BYOK usable while account-only actions surface unavailable OAuth", async () => {
  357. const cliService = cliServiceFixture();
  358. vi.mocked(cliService.getAccountStatus).mockResolvedValue({
  359. selection: { defaultModel: "custom/model" },
  360. provider: { id: "custom_provider:example", authMode: "api-key" },
  361. auth: { tokenPresent: false },
  362. warnings: [],
  363. });
  364. const failure = new TypeError("fetch failed");
  365. const synchronizeAuth = vi.fn(async () => {
  366. throw failure;
  367. });
  368. const adapter = new TuiRuntimeAdapter(cliService, { synchronizeAuth });
  369. await expect(requireTuiAgentAccess(adapter)).resolves.toMatchObject({
  370. modelSource: "byok",
  371. });
  372. expect(synchronizeAuth).not.toHaveBeenCalled();
  373. await expect(requireTuiAccountLogin(adapter)).rejects.toBe(failure);
  374. expect(synchronizeAuth).toHaveBeenCalledOnce();
  375. });
  376. it("keeps BYOK usable while account-only actions surface unavailable OAuth", async () => {
  377. const cliService = cliServiceFixture();
  378. vi.mocked(cliService.getAccountStatus).mockResolvedValue({
  379. selection: { defaultModel: "custom/model" },
  380. provider: { id: "custom_provider:example", authMode: "api-key" },
  381. auth: { tokenPresent: false },
  382. warnings: [],
  383. });
  384. const failure = new TypeError("fetch failed");
  385. const synchronizeAuth = vi.fn(async () => {
  386. throw failure;
  387. });
  388. const adapter = new TuiRuntimeAdapter(cliService, { synchronizeAuth });
  389. await expect(requireTuiAgentAccess(adapter)).resolves.toMatchObject({
  390. modelSource: "byok",
  391. });
  392. expect(synchronizeAuth).not.toHaveBeenCalled();
  393. await expect(requireTuiAccountLogin(adapter)).rejects.toBe(failure);
  394. expect(synchronizeAuth).toHaveBeenCalledOnce();
  395. });
  396. it("hydrates explicit Token Plan usage for a BYOK account", async () => {
  397. const cliService = cliServiceFixture();
  398. vi.mocked(cliService.getAccountStatus).mockResolvedValueOnce({
  399. selection: { defaultModel: "custom/gpt-5.6" },
  400. provider: { id: "custom_provider:openai", authMode: "api-key" },
  401. auth: { tokenPresent: false },
  402. warnings: [],
  403. });
  404. const tokenPlanAccountStatusGetter = vi.fn(async () => ({
  405. summary: { tier: "Pro Plan" },
  406. quotaState: "available" as const,
  407. quota: {
  408. fiveHour: { remainingPercent: 75, unlimited: false },
  409. weekly: { remainingPercent: 50, unlimited: false },
  410. },
  411. }));
  412. const adapter = new TuiRuntimeAdapter(cliService, {
  413. tokenPlanAccountStatusGetter,
  414. });
  415. await expect(
  416. adapter.getAccountStatus(undefined, {
  417. includeMembership: true,
  418. forceRefresh: true,
  419. }),
  420. ).resolves.toMatchObject({
  421. modelSource: "byok",
  422. managedTokenPresent: false,
  423. tokenPlanSummary: { tier: "Pro Plan" },
  424. tokenPlanQuotaState: "available",
  425. tokenPlanQuota: { fiveHour: { remainingPercent: 75 } },
  426. });
  427. expect(tokenPlanAccountStatusGetter).toHaveBeenCalledWith({
  428. forceRefresh: true,
  429. });
  430. });
  431. it("forwards an explicit account refresh to Token Plan hydration", async () => {
  432. const tokenPlanAccountStatusGetter = vi.fn(async () => ({
  433. quotaState: "available" as const,
  434. quota: {
  435. fiveHour: { remainingPercent: 90, unlimited: false },
  436. weekly: { remainingPercent: 80, unlimited: false },
  437. },
  438. }));
  439. const adapter = new TuiRuntimeAdapter(cliServiceFixture(), {
  440. tokenPlanAccountStatusGetter,
  441. });
  442. await adapter.getAccountStatus(undefined, {
  443. includeMembership: true,
  444. forceRefresh: true,
  445. });
  446. expect(tokenPlanAccountStatusGetter).toHaveBeenCalledWith({
  447. forceRefresh: true,
  448. });
  449. });
  450. it("updates both the active Session and the TUI default model", async () => {
  451. const cliService = cliServiceFixture();
  452. const adapter = new TuiRuntimeAdapter(cliService);
  453. const selection = {
  454. providerId: "minimax",
  455. modelId: "MiniMax-M3",
  456. variant: "thinking",
  457. contextLimit: 1_000_000,
  458. thinking: { effort: "high" },
  459. };
  460. const defaultSelection = {
  461. providerId: selection.providerId,
  462. modelId: selection.modelId,
  463. variant: selection.variant,
  464. contextLimit: selection.contextLimit,
  465. thinking: selection.thinking,
  466. };
  467. await expect(adapter.selectModel(selection, "session-1")).resolves.toBe(
  468. true,
  469. );
  470. expect(cliService.selectModel).toHaveBeenNthCalledWith(1, defaultSelection);
  471. expect(cliService.selectModel).toHaveBeenNthCalledWith(2, {
  472. ...selection,
  473. sessionId: "session-1",
  474. });
  475. vi.mocked(cliService.selectModel).mockClear();
  476. await expect(adapter.selectModel(selection)).resolves.toBe(true);
  477. expect(cliService.selectModel).toHaveBeenCalledOnce();
  478. expect(cliService.selectModel).toHaveBeenCalledWith(defaultSelection);
  479. });
  480. it("can update one Session model without changing the process default", async () => {
  481. const cliService = cliServiceFixture();
  482. const adapter = new TuiRuntimeAdapter(cliService);
  483. const selection = {
  484. providerId: "minimax",
  485. modelId: "MiniMax-M3",
  486. variant: "thinking",
  487. thinking: { effort: "high" },
  488. };
  489. await expect(
  490. adapter.selectSessionModel(selection, "session-1"),
  491. ).resolves.toBe(true);
  492. expect(cliService.selectModel).toHaveBeenCalledOnce();
  493. expect(cliService.selectModel).toHaveBeenCalledWith({
  494. ...selection,
  495. sessionId: "session-1",
  496. });
  497. });
  498. it("does not change the active Session when saving the TUI default is rejected", async () => {
  499. const cliService = cliServiceFixture();
  500. vi.mocked(cliService.selectModel).mockResolvedValueOnce(false);
  501. const adapter = new TuiRuntimeAdapter(cliService);
  502. const selection = {
  503. providerId: "minimax",
  504. modelId: "MiniMax-M3",
  505. };
  506. await expect(adapter.selectModel(selection, "session-1")).resolves.toBe(
  507. false,
  508. );
  509. expect(cliService.selectModel).toHaveBeenCalledOnce();
  510. expect(cliService.selectModel).toHaveBeenCalledWith(selection);
  511. });
  512. it("registers installed Plugin Skills from the unified Runtime roster as slash commands", async () => {
  513. const cliService = cliServiceFixture();
  514. vi.mocked(cliService.listRuntimeSkills).mockImplementationOnce(
  515. async (input) => {
  516. const skills = [{ name: "review", enabled: true }];
  517. if (input.includePluginSkills === true) {
  518. skills.push({ name: "traceink:generate", enabled: true });
  519. }
  520. return { skills, refreshedAt: 123 };
  521. },
  522. );
  523. const adapter = new TuiRuntimeAdapter(cliService);
  524. const result = await adapter.listSkills("mavis");
  525. expect(cliService.listRuntimeSkills).toHaveBeenCalledWith({
  526. agentName: "mavis",
  527. includePluginSkills: true,
  528. });
  529. expect(result.skills).toHaveLength(2);
  530. expect(buildTuiSkillCommands(result)).toEqual(
  531. expect.arrayContaining([
  532. expect.objectContaining({ name: "traceink:generate" }),
  533. ]),
  534. );
  535. expect(result.hasMore).toBe(false);
  536. });
  537. });
  538. function cliServiceFixture(): CliService {
  539. return {
  540. watchSessionUsageCommits: vi.fn(async function* watchSessionUsageCommits() {
  541. yield "session-1";
  542. }),
  543. getSessionUsageSummary: vi.fn(async () => ({
  544. inputTokens: 10,
  545. cacheReadTokens: 80,
  546. cacheWriteTokens: 10,
  547. })),
  548. getSessionUsage: vi.fn(async () => ({
  549. summary: { inputTokens: 10, outputTokens: 5, totalTokens: 15, turns: 1 },
  550. rows: [{ model: "minimax/MiniMax-M3" }],
  551. })),
  552. getMessages: vi.fn(async () => ({
  553. messages: [
  554. {
  555. msgId: "assistant-1",
  556. kind: "final",
  557. rawJson: JSON.stringify({
  558. msg_id: "assistant-1",
  559. turnId: "turn-1",
  560. context_usage: {
  561. contextWindowTokens: 1000,
  562. usedTokens: 300,
  563. totalCountSource: "PROVIDER_USAGE_ANCHORED",
  564. components: [{ kind: "MESSAGES", tokens: 300 }],
  565. },
  566. }),
  567. },
  568. ],
  569. })),
  570. requestCompaction: vi.fn(async () => ({
  571. success: true,
  572. sessionId: "session-1",
  573. compactionId: "compaction-1",
  574. messagesBefore: 10,
  575. messagesAfter: 4,
  576. tokensBefore: 100,
  577. tokensAfter: 40,
  578. })),
  579. getSession: vi.fn(async () => ({
  580. session: {
  581. sessionId: "session-1",
  582. agentName: "mavis",
  583. status: { statusType: 1 },
  584. model: {
  585. providerId: "minimax",
  586. modelId: "MiniMax-M3",
  587. contextLimit: 1000,
  588. },
  589. },
  590. })),
  591. listModels: vi.fn(async () => [
  592. {
  593. providerId: "minimax",
  594. modelId: "MiniMax-M3",
  595. selected: true,
  596. contextLimit: 400_000,
  597. },
  598. ]),
  599. getActiveTurn: vi.fn(async () => ({
  600. turnId: "turn-1",
  601. busyReason: "turn" as const,
  602. locallyOwned: true,
  603. })),
  604. listPendingPermissions: vi.fn(async () => ({ requests: [] })),
  605. getPendingQuestionnaire: vi.fn(async () => ({})),
  606. getAccountStatus: vi.fn(async () => ({
  607. selection: { defaultModel: "minimax/MiniMax-M3" },
  608. provider: { id: "minimax", authMode: "managed-login" },
  609. auth: { tokenPresent: true },
  610. warnings: [],
  611. })),
  612. getRuntimeDiagnostics: vi.fn(async () => ({ status: "ok" })),
  613. getInstructionSources: vi.fn(async ({ workspaceDir }) => [
  614. { scope: "project", path: `${workspaceDir}/AGENTS.md` },
  615. ]),
  616. getPermissionMode: vi.fn(async () => "default"),
  617. setPermissionMode: vi.fn(async ({ mode }) => mode),
  618. selectModel: vi.fn(async () => true),
  619. listRuntimeSkills: vi.fn(async () => ({
  620. skills: [{ name: "review", enabled: true }],
  621. refreshedAt: 123,
  622. })),
  623. listMcpServers: vi.fn(async () => ({
  624. servers: [{ name: "browser", enabled: true, transport: "stdio" }],
  625. })),
  626. } as unknown as CliService;
  627. }
  628. it("forwards saved-credential discovery and revision-checked model-only updates", async () => {
  629. const discoverUserModelsCandidate = vi.fn(async () => [
  630. { modelId: "latest" },
  631. ]);
  632. const saveUserModelProviderCandidate = vi.fn(async () => ({ success: true }));
  633. const adapter = new TuiRuntimeAdapter({
  634. discoverUserModelsCandidate,
  635. saveUserModelProviderCandidate,
  636. } as never);
  637. const candidate = {
  638. providerId: "custom_provider:work",
  639. expectedRevision: "rev-1",
  640. baseUrl: "https://models.example/v1",
  641. };
  642. await expect(adapter.discoverUserModelsCandidate(candidate)).resolves.toEqual(
  643. [{ modelId: "latest" }],
  644. );
  645. expect(discoverUserModelsCandidate).toHaveBeenCalledWith(candidate);
  646. await adapter.saveUserModelProviderCandidate({
  647. ...candidate,
  648. models: [{ modelId: "latest" }],
  649. modelId: "latest",
  650. skipConnectionTest: true,
  651. saveAndUse: false,
  652. });
  653. expect(saveUserModelProviderCandidate).toHaveBeenCalledWith({
  654. candidate: { ...candidate, models: [{ modelId: "latest" }] },
  655. modelId: "latest",
  656. skipConnectionTest: true,
  657. saveAndUse: false,
  658. });
  659. await adapter.saveUserModelProviderCandidate({
  660. ...candidate,
  661. apiKey: "new-key",
  662. modelId: "latest",
  663. saveAndUse: false,
  664. });
  665. expect(saveUserModelProviderCandidate).toHaveBeenLastCalledWith({
  666. candidate: { ...candidate, apiKey: "new-key" },
  667. modelId: "latest",
  668. saveAndUse: false,
  669. });
  670. });