Elffuss BraidHub

kikocis/continue public

fix: model switcher not working when signed out, and other improvements
Changesetb3a6a97ce7a5857026c5bdeba0e4b73de1eec0a0548676a451f1a8dae9b56727
AuthorNate <sestinj@gmail.com> · 2025-08-24 17:52 -07:00
CommitterNate <sestinj@gmail.com> · 2025-08-24 17:52 -07:00
Parentsfc89067dc2f1

Browse the files at this changeset

21 files changed

modified extensions/cli/src/args-mcp.test.ts +4 −10
@@ -38,13 +38,7 @@
3838 });
3939
4040 it("should handle MCP flag with prompt", () => {
41- process.argv = [
42- "node",
43- "test",
44- "--mcp",
45- "my-org/my-mcp",
46- "hello world"
47- ];
41+ process.argv = ["node", "test", "--mcp", "my-org/my-mcp", "hello world"];
4842 const result = parseArgs();
4943 expect(result.mcps).toEqual(["my-org/my-mcp"]);
5044 expect(result.prompt).toBe("hello world");
@@ -57,8 +51,8 @@
5751 "actual prompt",
5852 "--rule",
5953 "my-rule",
60- "--mcp",
61- "my-org/my-mcp"
54+ "--mcp",
55+ "my-org/my-mcp",
6256 ];
6357 const result = parseArgs();
6458 expect(result.prompt).toBe("actual prompt");
@@ -78,4 +72,4 @@
7872 expect(result.prompt).toBe("my prompt");
7973 expect(result.mcps).toEqual([]);
8074 });
81-});
No newline at the end of the file
75+});
modified extensions/cli/src/args.ts +15 −4
@@ -37,7 +37,10 @@
3737 /**
3838 * Extract value for a single-value flag
3939 */
40-function extractSingleFlag(args: string[], flagName: string): string | undefined {
40+function extractSingleFlag(
41+ args: string[],
42+ flagName: string,
43+): string | undefined {
4144 const index = args.indexOf(flagName);
4245 if (index !== -1 && index + 1 < args.length) {
4346 return args[index + 1];
@@ -69,10 +72,10 @@
6972 }
7073
7174 result.configPath = extractSingleFlag(args, "--config");
72-
75+
7376 const orgValue = extractSingleFlag(args, "--org");
7477 if (orgValue) {
75- result.organizationSlug =
78+ result.organizationSlug =
7679 orgValue.toLowerCase() === "personal" ? undefined : orgValue;
7780 }
7881
@@ -107,7 +110,15 @@
107110 }
108111
109112 // Extract prompt from non-flag arguments
110- const flagsWithValues = ["--config", "--org", "--rule", "--mcp", "--model", "--prompt", "--format"];
113+ const flagsWithValues = [
114+ "--config",
115+ "--org",
116+ "--rule",
117+ "--mcp",
118+ "--model",
119+ "--prompt",
120+ "--format",
121+ ];
111122 const nonFlagArgs = args.filter((arg, index) => {
112123 if (arg.startsWith("--") || arg === "-p") return false;
113124 const prevArg = index > 0 ? args[index - 1] : "";
modified extensions/cli/src/configEnhancer.test.ts +30 −10
@@ -150,10 +150,26 @@
150150
151151 // Models from --model flag should be prepended (at the start)
152152 expect(config.models).toHaveLength(4);
153- expect(config.models?.[0]).toEqual({ name: "GPT-5", provider: "openai", model: "gpt-5" });
154- expect(config.models?.[1]).toEqual({ name: "Claude-3", provider: "anthropic", model: "claude-3" });
155- expect(config.models?.[2]).toEqual({ name: "GPT-4", provider: "openai", model: "gpt-4" });
156- expect(config.models?.[3]).toEqual({ name: "Claude-2", provider: "anthropic", model: "claude-2" });
153+ expect(config.models?.[0]).toEqual({
154+ name: "GPT-5",
155+ provider: "openai",
156+ model: "gpt-5",
157+ });
158+ expect(config.models?.[1]).toEqual({
159+ name: "Claude-3",
160+ provider: "anthropic",
161+ model: "claude-3",
162+ });
163+ expect(config.models?.[2]).toEqual({
164+ name: "GPT-4",
165+ provider: "openai",
166+ model: "gpt-4",
167+ });
168+ expect(config.models?.[3]).toEqual({
169+ name: "Claude-2",
170+ provider: "anthropic",
171+ model: "claude-2",
172+ });
157173 });
158174
159175 it("should prepend MCPs from --mcp flag", async () => {
@@ -164,9 +180,7 @@
164180 ]);
165181
166182 // Set up existing MCPs in config
167- mockConfig.mcpServers = [
168- { name: "Existing-MCP", command: "existing-mcp" },
169- ];
183+ mockConfig.mcpServers = [{ name: "Existing-MCP", command: "existing-mcp" }];
170184
171185 const options: BaseCommandOptions = {
172186 mcp: ["test/new-mcp"],
@@ -176,7 +190,13 @@
176190
177191 // MCPs from --mcp flag should be prepended (at the start)
178192 expect(config.mcpServers).toHaveLength(2);
179- expect(config.mcpServers?.[0]).toEqual({ name: "New-MCP", command: "new-mcp" });
180- expect(config.mcpServers?.[1]).toEqual({ name: "Existing-MCP", command: "existing-mcp" });
193+ expect(config.mcpServers?.[0]).toEqual({
194+ name: "New-MCP",
195+ command: "new-mcp",
196+ });
197+ expect(config.mcpServers?.[1]).toEqual({
198+ name: "Existing-MCP",
199+ command: "existing-mcp",
200+ });
181201 });
182-});
No newline at the end of the file
202+});
modified extensions/cli/src/configEnhancer.ts +7 −6
@@ -57,12 +57,13 @@
5757 for (const ruleSpec of rules) {
5858 try {
5959 const processedContent = await processRule(ruleSpec);
60-
60+
6161 // Check if this is a hub slug (contains / but doesn't start with . or /)
62- const isHubSlug = ruleSpec.includes("/") &&
63- !ruleSpec.startsWith(".") &&
64- !ruleSpec.startsWith("/");
65-
62+ const isHubSlug =
63+ ruleSpec.includes("/") &&
64+ !ruleSpec.startsWith(".") &&
65+ !ruleSpec.startsWith("/");
66+
6667 if (isHubSlug) {
6768 // Store as RuleObject with name (slug) and rule (content)
6869 processedRules.push({
@@ -149,4 +150,4 @@
149150 /**
150151 * Global config enhancer instance
151152 */
152-export const configEnhancer = new ConfigEnhancer();
No newline at the end of the file
153+export const configEnhancer = new ConfigEnhancer();
modified extensions/cli/src/configLoader.ts +10 −0
@@ -301,6 +301,16 @@
301301 renderSecrets: true,
302302 platformClient: new CLIPlatformClient(organizationId, apiClient),
303303 onPremProxyUrl: null,
304+ injectBlocks: [
305+ {
306+ uriType: "slug",
307+ fullSlug: {
308+ ownerSlug: "openai",
309+ packageSlug: "gpt-5",
310+ versionSlug: "latest",
311+ },
312+ },
313+ ],
304314 },
305315 );
306316
modified extensions/cli/src/hubLoader.test.ts +43 −23
@@ -17,7 +17,7 @@
1717
1818 // Mock JSZip
1919 vi.mock("jszip", () => ({
20- default: vi.fn()
20+ default: vi.fn(),
2121 }));
2222
2323 const mockedJSZip = vi.fn();
@@ -45,7 +45,9 @@
4545
4646 await expect(
4747 loadPackageFromHub("owner/package", ruleProcessor),
48- ).rejects.toThrow('Failed to load rule from hub "owner/package": HTTP 404: Not Found');
48+ ).rejects.toThrow(
49+ 'Failed to load rule from hub "owner/package": HTTP 404: Not Found',
50+ );
4951 });
5052
5153 it("should load rule content", async () => {
@@ -54,9 +56,9 @@
5456 // Check if JSZip is mocked
5557 const JSZipModule = await import("jszip");
5658 const JSZip = JSZipModule.default;
57-
59+
5860 // Since JSZip is mocked, it should be a mock function
59- if (typeof (JSZip as any).mockImplementation === 'function') {
61+ if (typeof (JSZip as any).mockImplementation === "function") {
6062 (JSZip as any).mockImplementation(() => ({
6163 loadAsync: vi.fn().mockResolvedValueOnce({
6264 files: {
@@ -65,7 +67,7 @@
6567 async: vi.fn().mockResolvedValue(ruleContent),
6668 },
6769 },
68- })
70+ }),
6971 }));
7072 } else {
7173 // If mock doesn't work, skip this test
@@ -84,7 +86,7 @@
8486
8587 it("should load MCP configuration", async () => {
8688 const mcpConfig = {
87- content: "name: test-mcp\nversion: 1.0.0"
89+ content: "name: test-mcp\nversion: 1.0.0",
8890 };
8991
9092 mockFetch.mockResolvedValueOnce({
@@ -96,7 +98,7 @@
9698 // Should parse the YAML content, not return the wrapper
9799 expect(result).toEqual({
98100 name: "test-mcp",
99- version: "1.0.0"
101+ version: "1.0.0",
100102 });
101103 });
102104
@@ -104,9 +106,9 @@
104106 // Check if JSZip is mocked
105107 const JSZipModule = await import("jszip");
106108 const JSZip = JSZipModule.default;
107-
109+
108110 // Since JSZip is mocked, it should be a mock function
109- if (typeof (JSZip as any).mockImplementation === 'function') {
111+ if (typeof (JSZip as any).mockImplementation === "function") {
110112 (JSZip as any).mockImplementation(() => ({
111113 loadAsync: vi.fn().mockResolvedValueOnce({
112114 files: {
@@ -115,7 +117,7 @@
115117 async: vi.fn().mockResolvedValue("not a rule"),
116118 },
117119 },
118- })
120+ }),
119121 }));
120122 } else {
121123 // If mock doesn't work, skip this test
@@ -140,23 +142,35 @@
140142 it("should define rule processor correctly", () => {
141143 expect(ruleProcessor.type).toBe("rule");
142144 expect(ruleProcessor.expectedFileExtensions).toEqual([".md"]);
143- expect(ruleProcessor.parseContent("test content", "test.md")).toBe("test content");
145+ expect(ruleProcessor.parseContent("test content", "test.md")).toBe(
146+ "test content",
147+ );
144148 });
145149
146150 it("should define MCP processor correctly", () => {
147151 expect(mcpProcessor.type).toBe("mcp");
148- expect(mcpProcessor.expectedFileExtensions).toEqual([".json", ".yaml", ".yml"]);
152+ expect(mcpProcessor.expectedFileExtensions).toEqual([
153+ ".json",
154+ ".yaml",
155+ ".yml",
156+ ]);
149157 });
150158
151159 it("should define model processor correctly", () => {
152160 expect(modelProcessor.type).toBe("model");
153- expect(modelProcessor.expectedFileExtensions).toEqual([".json", ".yaml", ".yml"]);
161+ expect(modelProcessor.expectedFileExtensions).toEqual([
162+ ".json",
163+ ".yaml",
164+ ".yml",
165+ ]);
154166 });
155167
156168 it("should define prompt processor correctly", () => {
157169 expect(promptProcessor.type).toBe("prompt");
158170 expect(promptProcessor.expectedFileExtensions).toEqual([".md", ".txt"]);
159- expect(promptProcessor.parseContent("test content", "test.md")).toBe("test content");
171+ expect(promptProcessor.parseContent("test content", "test.md")).toBe(
172+ "test content",
173+ );
160174 });
161175 });
162176
@@ -171,8 +185,11 @@
171185 });
172186
173187 it("should load rule from real hub: sanity/sanity-opinionated", async () => {
174- const result = await loadPackageFromHub("sanity/sanity-opinionated", ruleProcessor);
175-
188+ const result = await loadPackageFromHub(
189+ "sanity/sanity-opinionated",
190+ ruleProcessor,
191+ );
192+
176193 expect(result).toBeDefined();
177194 expect(typeof result).toBe("string");
178195 expect(result.length).toBeGreaterThan(0);
@@ -184,10 +201,10 @@
184201 // Restore real fetch and JSZip for this test
185202 global.fetch = originalFetch;
186203 vi.unmock("jszip");
187-
204+
188205 const testSlug = "upstash/context7-mcp";
189206 const result = await loadPackageFromHub(testSlug, mcpProcessor);
190-
207+
191208 expect(result).toBeDefined();
192209 expect(typeof result).toBe("object");
193210 // Should now return the parsed MCP configuration
@@ -202,10 +219,10 @@
202219 // Restore real fetch and JSZip for this test
203220 global.fetch = originalFetch;
204221 vi.unmock("jszip");
205-
222+
206223 const testSlug = "openai/gpt-5";
207224 const result = await loadPackageFromHub(testSlug, modelProcessor);
208-
225+
209226 expect(result).toBeDefined();
210227 expect(typeof result).toBe("object");
211228 // Should now return the extracted model from the models array
@@ -219,11 +236,14 @@
219236 }, 30000);
220237
221238 it("should load prompt from real hub: launchdarkly/using-flags", async () => {
222- const result = await loadPackageFromHub("launchdarkly/using-flags", promptProcessor);
223-
239+ const result = await loadPackageFromHub(
240+ "launchdarkly/using-flags",
241+ promptProcessor,
242+ );
243+
224244 expect(result).toBeDefined();
225245 expect(typeof result).toBe("string");
226246 expect(result.length).toBeGreaterThan(0);
227247 }, 30000);
228248 });
229-});
No newline at the end of the file
249+});
modified extensions/cli/src/hubLoader.ts +39 −20
@@ -41,13 +41,17 @@
4141 const yaml = await import("yaml");
4242 parsed = yaml.parse(content);
4343 }
44-
44+
4545 // If the parsed content has an 'mcpServers' array, extract the first MCP server
4646 // This handles hub packages that return a full config block
47- if (parsed.mcpServers && Array.isArray(parsed.mcpServers) && parsed.mcpServers.length > 0) {
47+ if (
48+ parsed.mcpServers &&
49+ Array.isArray(parsed.mcpServers) &&
50+ parsed.mcpServers.length > 0
51+ ) {
4852 return parsed.mcpServers[0];
4953 }
50-
54+
5155 return parsed;
5256 },
5357 };
@@ -66,13 +70,17 @@
6670 const yaml = await import("yaml");
6771 parsed = yaml.parse(content);
6872 }
69-
73+
7074 // If the parsed content has a 'models' array, extract the first model
7175 // This handles hub packages that return a full config block
72- if (parsed.models && Array.isArray(parsed.models) && parsed.models.length > 0) {
76+ if (
77+ parsed.models &&
78+ Array.isArray(parsed.models) &&
79+ parsed.models.length > 0
80+ ) {
7381 return parsed.models[0];
7482 }
75-
83+
7684 return parsed;
7785 },
7886 };
@@ -101,7 +109,7 @@
101109 }
102110
103111 const [ownerSlug, packageSlug] = parts;
104-
112+
105113 // Use different endpoints based on package type
106114 let downloadUrl: URL;
107115 if (processor.type === "mcp" || processor.type === "model") {
@@ -129,7 +137,7 @@
129137 if (processor.type === "mcp" || processor.type === "model") {
130138 // Registry endpoints return JSON with a 'content' field containing YAML/JSON
131139 const jsonResponse = await response.json();
132-
140+
133141 // Extract and parse the content field
134142 if (jsonResponse.content) {
135143 // Parse the YAML/JSON content
@@ -149,12 +157,14 @@
149157 const zipContents = await zip.loadAsync(arrayBuffer);
150158
151159 // Find files matching expected extensions
152- const matchingFiles = Object.keys(zipContents.files).filter((filename) => {
153- if (zipContents.files[filename].dir) return false;
154- return processor.expectedFileExtensions.some((ext) =>
155- filename.endsWith(ext),
156- );
157- });
160+ const matchingFiles = Object.keys(zipContents.files).filter(
161+ (filename) => {
162+ if (zipContents.files[filename].dir) return false;
163+ return processor.expectedFileExtensions.some((ext) =>
164+ filename.endsWith(ext),
165+ );
166+ },
167+ );
158168
159169 if (matchingFiles.length === 0) {
160170 throw new Error(
@@ -173,8 +183,13 @@
173183 );
174184
175185 // Validate if processor has validation
176- if (processor.validateContent && !processor.validateContent(parsedContent)) {
177- throw new Error(`Invalid ${processor.type} content in ${matchingFiles[0]}`);
186+ if (
187+ processor.validateContent &&
188+ !processor.validateContent(parsedContent)
189+ ) {
190+ throw new Error(
191+ `Invalid ${processor.type} content in ${matchingFiles[0]}`,
192+ );
178193 }
179194
180195 return parsedContent;
@@ -222,7 +237,7 @@
222237 ) {
223238 const fs = await import("fs");
224239 const path = await import("path");
225-
240+
226241 try {
227242 const absolutePath = path.resolve(ruleSpec);
228243 if (!fs.existsSync(absolutePath)) {
@@ -230,7 +245,9 @@
230245 }
231246 return fs.readFileSync(absolutePath, "utf-8");
232247 } catch (error: any) {
233- throw new Error(`Failed to read rule file "${ruleSpec}": ${error.message}`);
248+ throw new Error(
249+ `Failed to read rule file "${ruleSpec}": ${error.message}`,
250+ );
234251 }
235252 }
236253
@@ -252,9 +269,11 @@
252269 const content = await loadPackageFromHub(slug, processor);
253270 results.push(content);
254271 } catch (error: any) {
255- logger.warn(`Failed to load ${processor.type} "${slug}": ${error.message}`);
272+ logger.warn(
273+ `Failed to load ${processor.type} "${slug}": ${error.message}`,
274+ );
256275 }
257276 }
258277
259278 return results;
260-}
No newline at the end of the file
279+}
modified extensions/cli/src/integration/rule-duplication.test.ts +6 −6
@@ -1,5 +1,5 @@
11 import { AssistantUnrolled } from "@continuedev/config-yaml";
2-import { beforeEach, describe, expect, it, vi } from "vitest";
2+import { describe, expect, it, vi } from "vitest";
33
44 import { BaseCommandOptions } from "../commands/BaseCommandOptions.js";
55 import { ConfigEnhancer } from "../configEnhancer.js";
@@ -22,7 +22,7 @@
2222 describe("Rule duplication integration test", () => {
2323 it("should not duplicate rules when using --rule flag", async () => {
2424 const enhancer = new ConfigEnhancer();
25-
25+
2626 // Initial config without any rules
2727 const initialConfig: AssistantUnrolled = {
2828 name: "Test Assistant",
@@ -40,13 +40,13 @@
4040 // Verify the rule was added exactly once as a RuleObject
4141 expect(enhancedConfig.rules).toHaveLength(1);
4242 expect(enhancedConfig.rules).toEqual([
43- { name: "nate/spanish", rule: "Content for nate/spanish" }
43+ { name: "nate/spanish", rule: "Content for nate/spanish" },
4444 ]);
4545 });
4646
4747 it("should merge command-line rules with existing config rules", async () => {
4848 const enhancer = new ConfigEnhancer();
49-
49+
5050 // Initial config with existing rules
5151 const initialConfig: AssistantUnrolled = {
5252 name: "Test Assistant",
@@ -72,7 +72,7 @@
7272
7373 it("should handle rule content with frontmatter", async () => {
7474 const enhancer = new ConfigEnhancer();
75-
75+
7676 // Mock processRule to return content with frontmatter
7777 const { processRule } = await import("../hubLoader.js");
7878 (processRule as any).mockImplementation((rule: string) => {
@@ -104,4 +104,4 @@
104104 expect(ruleObj.rule).toContain("Always respond in Spanish.");
105105 expect(ruleObj.rule).toContain("alwaysApply: true");
106106 });
107-});
No newline at the end of the file
107+});
modified extensions/cli/src/loadMcpFromHub.test.ts +8 −7
@@ -18,7 +18,7 @@
1818
1919 beforeEach(async () => {
2020 vi.clearAllMocks();
21-
21+
2222 // Get the mocked JSZip constructor
2323 const JSZip = (await import("jszip")).default;
2424 mockJSZip = new JSZip();
@@ -52,13 +52,14 @@
5252
5353 it("should parse JSON configuration files", async () => {
5454 const mockConfig = {
55- content: "name: test-mcp\ncommand: npx test-mcp\nargs:\n - --port\n - 3000"
55+ content:
56+ "name: test-mcp\ncommand: npx test-mcp\nargs:\n - --port\n - 3000",
5657 };
5758
5859 // MCP packages now use the registry endpoint and return JSON directly
5960 mockFetch.mockResolvedValueOnce({
6061 ok: true,
61- json: vi.fn().mockResolvedValue(mockConfig)
62+ json: vi.fn().mockResolvedValue(mockConfig),
6263 });
6364
6465 const result = await loadMcpFromHub("continuedev/test-mcp");
@@ -66,7 +67,7 @@
6667 expect(result).toEqual({
6768 name: "test-mcp",
6869 command: "npx test-mcp",
69- args: ["--port", 3000]
70+ args: ["--port", 3000],
7071 });
7172 });
7273
@@ -75,7 +76,7 @@
7576 // If the content field is missing or empty, it should fail
7677 mockFetch.mockResolvedValueOnce({
7778 ok: true,
78- json: vi.fn().mockResolvedValue({})
79+ json: vi.fn().mockResolvedValue({}),
7980 });
8081
8182 const result = await loadMcpFromHub("continuedev/no-config");
@@ -88,11 +89,11 @@
8889 // If the registry returns invalid JSON, it should fail at the fetch level
8990 mockFetch.mockResolvedValueOnce({
9091 ok: true,
91- json: vi.fn().mockRejectedValue(new Error("Invalid JSON"))
92+ json: vi.fn().mockRejectedValue(new Error("Invalid JSON")),
9293 });
9394
9495 await expect(loadMcpFromHub("continuedev/invalid-json")).rejects.toThrow(
9596 'Failed to load mcp from hub "continuedev/invalid-json": Invalid JSON',
9697 );
9798 });
98-});
No newline at the end of the file
99+});
modified extensions/cli/src/mcp-flag.integration.test.ts +29 −21
@@ -13,23 +13,26 @@
1313 it("should demonstrate the complete --mcp flag functionality", () => {
1414 // Test command line parsing
1515 process.argv = [
16- "node",
16+ "node",
1717 "test",
18- "--config", "my-config.yaml",
19- "--mcp", "continuedev/filesystem",
20- "--mcp", "continuedev/github",
21- "hello world"
18+ "--config",
19+ "my-config.yaml",
20+ "--mcp",
21+ "continuedev/filesystem",
22+ "--mcp",
23+ "continuedev/github",
24+ "hello world",
2225 ];
2326
2427 const args = parseArgs();
25-
28+
2629 // Verify the parsed command line arguments
2730 expect(args).toEqual({
2831 configPath: "my-config.yaml",
2932 mcps: ["continuedev/filesystem", "continuedev/github"],
30- prompt: "hello world"
33+ prompt: "hello world",
3134 });
32-
35+
3336 // Verify MCP slugs are properly captured
3437 expect(args.mcps).toHaveLength(2);
3538 expect(args.mcps).toContain("continuedev/filesystem");
@@ -39,34 +42,39 @@
3942 it("should validate MCP slug format", async () => {
4043 // Test that invalid slug formats are rejected
4144 await expect(loadMcpFromHub("invalid-slug")).rejects.toThrow(
42- 'Invalid hub slug format. Expected "owner/package", got: invalid-slug'
45+ 'Invalid hub slug format. Expected "owner/package", got: invalid-slug',
4346 );
4447
4548 // Valid format should not throw during validation step
4649 const mockFetch = vi.fn().mockResolvedValue({
4750 ok: false,
4851 status: 404,
49- statusText: "Not Found"
52+ statusText: "Not Found",
5053 });
5154 global.fetch = mockFetch;
5255
5356 // This will fail at the HTTP level, not validation level
5457 await expect(loadMcpFromHub("valid/slug")).rejects.toThrow(
55- 'Failed to load mcp from hub "valid/slug": HTTP 404: Not Found'
58+ 'Failed to load mcp from hub "valid/slug": HTTP 404: Not Found',
5659 );
5760 });
5861
5962 it("should demonstrate MCP flag with other command line options", () => {
6063 process.argv = [
6164 "node",
62- "test",
63- "--config", "test-config.yaml",
64- "--org", "my-org",
65- "--rule", "my-rule",
66- "--mcp", "continuedev/filesystem",
67- "--allow", "readFile",
65+ "test",
66+ "--config",
67+ "test-config.yaml",
68+ "--org",
69+ "my-org",
70+ "--rule",
71+ "my-rule",
72+ "--mcp",
73+ "continuedev/filesystem",
74+ "--allow",
75+ "readFile",
6876 "--readonly",
69- "analyze this code"
77+ "analyze this code",
7078 ];
7179
7280 const args = parseArgs();
@@ -74,11 +82,11 @@
7482 // Verify all flags are parsed correctly together
7583 expect(args).toEqual({
7684 configPath: "test-config.yaml",
77- organizationSlug: "my-org",
85+ organizationSlug: "my-org",
7886 rules: ["my-rule"],
7987 mcps: ["continuedev/filesystem"],
8088 readonly: true,
81- prompt: "analyze this code"
89+ prompt: "analyze this code",
8290 });
8391 });
84-});
No newline at the end of the file
92+});
modified extensions/cli/src/services/BaseService.ts +8 −2
@@ -27,14 +27,20 @@
2727 * Public initialization method that wraps the implementation
2828 */
2929 async initialize(...args: any[]): Promise<TState> {
30- logger.debug(`Initializing ${this.serviceName}`);
30+ logger.debug(`Initializing ${this.serviceName}`, {
31+ wasInitialized: this.isInitialized,
32+ hadPreviousState: !!this.currentState,
33+ });
3134 this.emit("initializing");
3235
3336 try {
3437 const state = await this.doInitialize(...args);
3538 this.currentState = state;
3639 this.isInitialized = true;
37- logger.debug(`${this.serviceName} initialized successfully`);
40+ logger.debug(`${this.serviceName} initialized successfully`, {
41+ stateKeys: state ? Object.keys(state as any) : [],
42+ isNowInitialized: this.isInitialized,
43+ });
3844 this.emit("initialized", state);
3945 return state;
4046 } catch (error: any) {
modified extensions/cli/src/services/ConfigService.test.ts +2 −2
@@ -74,13 +74,13 @@
7474 config: mockConfig as any,
7575 source: { type: "cli-flag", path: "/config.yaml" } as any,
7676 });
77-
77+
7878 const expectedConfig = {
7979 ...mockConfig,
8080 systemMessage:
8181 "Test system message\n\nProcessed: rule1\n\nProcessed: rule2",
8282 };
83-
83+
8484 vi.mocked(configEnhancer.enhanceConfig).mockResolvedValue(expectedConfig);
8585
8686 const state = await service.initialize(
modified extensions/cli/src/services/ConfigService.ts +8 −3
@@ -1,4 +1,3 @@
1-
21 import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
32
43 import { AuthConfig, loadAuthConfig } from "../auth/workos.js";
@@ -53,7 +52,10 @@
5352 let config = result.config;
5453
5554 // Apply injected config if provided
56- if (injectedConfigOptions && this.hasInjectedConfig(injectedConfigOptions)) {
55+ if (
56+ injectedConfigOptions &&
57+ this.hasInjectedConfig(injectedConfigOptions)
58+ ) {
5759 config = await configEnhancer.enhanceConfig(
5860 config,
5961 injectedConfigOptions,
@@ -99,7 +101,10 @@
99101 let config = result.config;
100102
101103 // Apply injected config if provided
102- if (injectedConfigOptions && this.hasInjectedConfig(injectedConfigOptions)) {
104+ if (
105+ injectedConfigOptions &&
106+ this.hasInjectedConfig(injectedConfigOptions)
107+ ) {
103108 config = await configEnhancer.enhanceConfig(
104109 config,
105110 injectedConfigOptions,
added extensions/cli/src/services/ModelService.direct.test.ts +207 −0
@@ -0,0 +1,207 @@
1+import { describe, it, expect, beforeEach } from "vitest";
2+
3+import { ModelService } from "./ModelService.js";
4+
5+describe("ModelService - Direct Testing", () => {
6+ let modelService: ModelService;
7+
8+ beforeEach(() => {
9+ modelService = new ModelService();
10+ });
11+
12+ it("should throw 'ModelService not initialized' when switching without initialization", async () => {
13+ // The service is created but not initialized (no assistant or authConfig)
14+ expect(modelService.getCurrentModelIndex()).toBe(-1);
15+
16+ // Try to switch model without initialization
17+ try {
18+ await modelService.switchModel(0);
19+ // Should not reach here
20+ expect(true).toBe(false);
21+ } catch (error: any) {
22+ // Should throw the specific error
23+ expect(error.message).toBe(
24+ "ModelService not initialized - assistant data missing",
25+ );
26+ }
27+ });
28+
29+ it("should handle model switching with null authConfig for non-proxy models", async () => {
30+ // Initialize the service properly
31+ const mockAssistant = {
32+ name: "Test Assistant",
33+ version: "1.0.0",
34+ models: [
35+ {
36+ name: "claude-3.5-sonnet",
37+ provider: "anthropic",
38+ model: "claude-3.5-sonnet",
39+ apiKey: "test-anthropic-key",
40+ roles: ["chat"],
41+ },
42+ {
43+ name: "GPT-4",
44+ provider: "openai",
45+ model: "gpt-4",
46+ apiKey: "test-openai-key",
47+ roles: ["chat"],
48+ },
49+ ],
50+ };
51+
52+ // Initialize with null authConfig - valid for non-proxy models
53+ const initialState = await modelService.initialize(
54+ mockAssistant as any,
55+ null as any,
56+ );
57+
58+ // Verify initialization succeeded with null authConfig
59+ expect(initialState.assistant).toBe(mockAssistant);
60+ expect(initialState.authConfig).toBe(null);
61+ expect(initialState.model).toBeDefined();
62+ expect((initialState.model as any).name).toBe("claude-3.5-sonnet");
63+
64+ // Should be able to switch models even with null authConfig
65+ const switchedState = await modelService.switchModel(1);
66+ expect(switchedState.model).toBeDefined();
67+ expect((switchedState.model as any).name).toBe("GPT-4");
68+ expect(switchedState.assistant).toBe(mockAssistant);
69+ expect(switchedState.authConfig).toBe(null);
70+
71+ // Verify the model info
72+ const modelInfo = modelService.getModelInfo();
73+ expect(modelInfo?.name).toBe("GPT-4");
74+ expect(modelInfo?.provider).toBe("openai");
75+ });
76+
77+ it("should successfully switch model after proper initialization", async () => {
78+ // Initialize the service properly
79+ const mockAssistant = {
80+ name: "Test Assistant",
81+ version: "1.0.0",
82+ models: [
83+ {
84+ name: "GPT-4",
85+ provider: "openai",
86+ model: "gpt-4",
87+ apiKey: "test-key-1",
88+ roles: ["chat"],
89+ },
90+ {
91+ name: "GPT-3.5",
92+ provider: "openai",
93+ model: "gpt-3.5-turbo",
94+ apiKey: "test-key-2",
95+ roles: ["chat"],
96+ },
97+ ],
98+ };
99+
100+ const mockAuthConfig = {
101+ token: "test-token",
102+ };
103+
104+ // Initialize the service (note: initialize calls doInitialize and sets the state)
105+ const initialState = await modelService.initialize(
106+ mockAssistant as any,
107+ mockAuthConfig as any,
108+ );
109+
110+ // Verify we have models and the first one is selected
111+ const availableModels = modelService.getAvailableChatModels();
112+ expect(availableModels.length).toBe(2);
113+ expect(initialState.model).toBeDefined();
114+ expect((initialState.model as any).name).toBe("GPT-4");
115+
116+ // Now switch should work
117+ await modelService.switchModel(1);
118+ expect(modelService.getCurrentModelIndex()).toBe(1);
119+
120+ const modelInfo = modelService.getModelInfo();
121+ expect(modelInfo?.name).toBe("GPT-3.5");
122+ });
123+
124+ it("should handle switching to invalid model index", async () => {
125+ // Initialize properly first
126+ const mockAssistant = {
127+ name: "Test Assistant",
128+ version: "1.0.0",
129+ models: [
130+ {
131+ name: "GPT-4",
132+ provider: "openai",
133+ model: "gpt-4",
134+ apiKey: "test-key",
135+ },
136+ ],
137+ };
138+
139+ const mockAuthConfig = {
140+ token: "test-token",
141+ };
142+
143+ await modelService.initialize(mockAssistant as any, mockAuthConfig as any);
144+
145+ // Try to switch to invalid index
146+ try {
147+ await modelService.switchModel(5); // Only have 1 model at index 0
148+ expect(true).toBe(false);
149+ } catch (error: any) {
150+ expect(error.message).toContain("Invalid model index");
151+ }
152+ });
153+
154+ it("should successfully switch model when service is properly initialized via container", async () => {
155+ // This test simulates the fix where we ensure service is initialized before switching
156+ const mockAssistant = {
157+ name: "Test Assistant",
158+ version: "1.0.0",
159+ models: [
160+ {
161+ name: "GPT-4",
162+ provider: "openai",
163+ model: "gpt-4",
164+ apiKey: "test-key-1",
165+ roles: ["chat"],
166+ },
167+ {
168+ name: "GPT-3.5",
169+ provider: "openai",
170+ model: "gpt-3.5-turbo",
171+ apiKey: "test-key-2",
172+ roles: ["chat"],
173+ },
174+ ],
175+ };
176+
177+ const mockAuthConfig = {
178+ token: "test-token",
179+ };
180+
181+ // Initialize the service properly through initialize method (which sets isInitialized)
182+ await modelService.initialize(mockAssistant as any, mockAuthConfig as any);
183+
184+ // Verify initialization
185+ expect(modelService.isReady()).toBe(true);
186+ expect(modelService.getCurrentModelIndex()).toBe(0);
187+
188+ // Now switch should work and return success
189+ const newState = await modelService.switchModel(1);
190+
191+ // Verify switch was successful
192+ expect(modelService.getCurrentModelIndex()).toBe(1);
193+ expect(newState.model).toBeDefined();
194+ expect((newState.model as any).name).toBe("GPT-3.5");
195+
196+ // Get model info to verify success message data
197+ const modelInfo = modelService.getModelInfo();
198+ expect(modelInfo).toEqual({
199+ provider: "openai",
200+ name: "GPT-3.5",
201+ });
202+
203+ // This is what the success message would use
204+ const successMessage = `Switched to model: ${modelInfo?.provider}/${modelInfo?.name}`;
205+ expect(successMessage).toBe("Switched to model: openai/GPT-3.5");
206+ });
207+});
deleted extensions/cli/src/services/ModelService.refactored.ts +0 −260
@@ -1,260 +0,0 @@
1-import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
2-import { constructLlmApi, LLMConfig } from "@continuedev/openai-adapters";
3-
4-import {
5- AuthConfig,
6- getAccessToken,
7- getOrganizationId,
8- getModelName,
9-} from "../auth/workos.js";
10-import { getLlmApi } from "../config.js";
11-import { logger } from "../util/logger.js";
12-
13-import { BaseService, ServiceWithDependencies } from "./BaseService.js";
14-import { ModelServiceState } from "./types.js";
15-
16-/**
17- * Service for managing LLM and model state
18- * Extends BaseService and implements ServiceWithDependencies
19- */
20-export class ModelService
21- extends BaseService<ModelServiceState>
22- implements ServiceWithDependencies
23-{
24- private availableModels: ModelConfig[] = [];
25- private assistant: AssistantUnrolled | null = null;
26- private authConfig: AuthConfig | null = null;
27-
28- constructor() {
29- super("ModelService", {
30- llmApi: null,
31- model: null,
32- });
33- }
34-
35- /**
36- * Declare dependencies on other services
37- */
38- getDependencies(): string[] {
39- return ["auth", "config"];
40- }
41-
42- /**
43- * Initialize the model service
44- */
45- async doInitialize(
46- assistant: AssistantUnrolled,
47- authConfig: AuthConfig,
48- ): Promise<ModelServiceState> {
49- this.assistant = assistant;
50- this.authConfig = authConfig;
51- this.availableModels = (assistant.models?.filter(
52- (model) =>
53- model && (model.roles?.includes("chat") || model.roles === undefined),
54- ) || []) as ModelConfig[];
55-
56- // Check if we have a persisted model name and use it if valid
57- const persistedModelName = getModelName(authConfig);
58- if (persistedModelName) {
59- const modelIndex = this.getModelIndexByName(persistedModelName);
60- if (modelIndex === -1) {
61- // Model name not found, use default model selection
62- const [llmApi, model] = getLlmApi(assistant, authConfig);
63- return {
64- llmApi,
65- model,
66- };
67- } else {
68- // Use the persisted model
69- const state = await this.switchModel(modelIndex);
70- return state;
71- }
72- } else {
73- // Use default model selection
74- const [llmApi, model] = getLlmApi(assistant, authConfig);
75- return {
76- llmApi,
77- model,
78- };
79- }
80- }
81-
82- /**
83- * Update the model based on new config or auth changes
84- */
85- async update(
86- assistant: AssistantUnrolled,
87- authConfig: AuthConfig,
88- ): Promise<ModelServiceState> {
89- logger.debug("Updating ModelService");
90-
91- try {
92- this.assistant = assistant;
93- this.authConfig = authConfig;
94- this.availableModels = (assistant.models?.filter(
95- (model) =>
96- model && (model.roles?.includes("chat") || model.roles === undefined),
97- ) || []) as ModelConfig[];
98-
99- const [llmApi, model] = getLlmApi(assistant, authConfig);
100-
101- this.setState({
102- llmApi,
103- model,
104- });
105-
106- logger.debug("ModelService updated successfully", {
107- modelProvider: model.provider,
108- modelName: (model as any).name || "unnamed",
109- availableModels: this.availableModels.length,
110- });
111-
112- return this.getState();
113- } catch (error: any) {
114- logger.error("Failed to update ModelService:", error);
115- this.emit("error", error);
116- throw error;
117- }
118- }
119-
120- /**
121- * Override isReady to check for required state
122- */
123- override isReady(): boolean {
124- return (
125- super.isReady() &&
126- this.currentState.llmApi !== null &&
127- this.currentState.model !== null
128- );
129- }
130-
131- /**
132- * Get model information for display
133- */
134- getModelInfo(): { provider: string; name: string } | null {
135- if (!this.currentState.model) {
136- return null;
137- }
138-
139- return {
140- provider: this.currentState.model.provider,
141- name: (this.currentState.model as any).name || "unnamed",
142- };
143- }
144-
145- /**
146- * Get list of available chat models
147- */
148- getAvailableChatModels(): Array<{
149- provider: string;
150- name: string;
151- index: number;
152- }> {
153- return this.availableModels.map((model, index) => ({
154- provider: model.provider,
155- name: (model as any).name || (model as any).model || "unnamed",
156- index,
157- }));
158- }
159-
160- /**
161- * Switch to a different chat model by index
162- */
163- async switchModel(modelIndex: number): Promise<ModelServiceState> {
164- if (!this.assistant || !this.authConfig) {
165- throw new Error("ModelService not initialized");
166- }
167-
168- if (modelIndex < 0 || modelIndex >= this.availableModels.length) {
169- throw new Error(
170- `Invalid model index: ${modelIndex}. Available models: 0-${this.availableModels.length - 1}`,
171- );
172- }
173-
174- const selectedModel = this.availableModels[modelIndex];
175- logger.debug("Switching to model", {
176- modelIndex,
177- provider: selectedModel.provider,
178- name: (selectedModel as any).name || "unnamed",
179- });
180-
181- try {
182- const accessToken = getAccessToken(this.authConfig);
183- const organizationId = getOrganizationId(this.authConfig);
184-
185- const config: LLMConfig =
186- selectedModel.provider === "continue-proxy"
187- ? {
188- provider: selectedModel.provider,
189- requestOptions: selectedModel.requestOptions,
190- apiBase: selectedModel.apiBase,
191- apiKey: accessToken ?? undefined,
192- env: {
193- apiKeyLocation: (selectedModel as any).apiKeyLocation,
194- orgScopeId: organizationId,
195- proxyUrl: undefined,
196- },
197- }
198- : {
199- provider: selectedModel.provider as any,
200- apiKey: selectedModel.apiKey,
201- apiBase: selectedModel.apiBase,
202- requestOptions: selectedModel.requestOptions,
203- env: selectedModel.env,
204- };
205-
206- const llmApi = constructLlmApi(config);
207-
208- if (!llmApi) {
209- throw new Error("Failed to initialize LLM with selected model");
210- }
211-
212- this.setState({
213- llmApi,
214- model: selectedModel,
215- });
216-
217- logger.debug("Model switched successfully", {
218- modelProvider: selectedModel.provider,
219- modelName: (selectedModel as any).name || "unnamed",
220- });
221-
222- return this.getState();
223- } catch (error: any) {
224- logger.error("Failed to switch model:", error);
225- this.emit("error", error);
226- throw error;
227- }
228- }
229-
230- /**
231- * Get current model index
232- */
233- getCurrentModelIndex(): number {
234- if (!this.currentState.model) {
235- return -1;
236- }
237-
238- return this.availableModels.findIndex(
239- (model) =>
240- model.provider === this.currentState.model?.provider &&
241- (model as any).name === (this.currentState.model as any).name,
242- );
243- }
244-
245- /**
246- * Get model index by name and provider
247- */
248- getModelIndexByName(modelName: string, provider?: string): number {
249- return this.availableModels.findIndex((model) => {
250- const name = (model as any).name || (model as any).model;
251- const nameMatches = name === modelName;
252-
253- if (provider) {
254- return nameMatches && model.provider === provider;
255- }
256-
257- return nameMatches;
258- });
259- }
260-}
modified extensions/cli/src/services/ModelService.test.ts +6 −0
@@ -74,6 +74,8 @@
7474 expect(state).toEqual({
7575 llmApi: mockLlmApi,
7676 model: mockAssistant.models![0],
77+ assistant: mockAssistant,
78+ authConfig: mockAuthConfig,
7779 });
7880 });
7981
@@ -135,6 +137,8 @@
135137 expect(state).toEqual({
136138 llmApi: newLlmApi,
137139 model: newAssistant.models![0],
140+ assistant: newAssistant,
141+ authConfig: mockAuthConfig,
138142 });
139143 });
140144 });
@@ -157,6 +161,8 @@
157161 expect(state).toEqual({
158162 llmApi: newLlmApi,
159163 model: mockAssistant.models![1],
164+ assistant: mockAssistant,
165+ authConfig: mockAuthConfig,
160166 });
161167 expect(service.getState()).toEqual(state);
162168 });
modified extensions/cli/src/services/ModelService.ts +146 −17
@@ -29,6 +29,8 @@
2929 super("ModelService", {
3030 llmApi: null,
3131 model: null,
32+ assistant: null,
33+ authConfig: null,
3234 });
3335 }
3436
@@ -46,6 +48,12 @@
4648 assistant: AssistantUnrolled,
4749 authConfig: AuthConfig,
4850 ): Promise<ModelServiceState> {
51+ logger.debug("ModelService.doInitialize called", {
52+ hasAssistant: !!assistant,
53+ hasAuthConfig: !!authConfig,
54+ assistantModelsCount: assistant?.models?.length || 0,
55+ });
56+
4957 this.assistant = assistant;
5058 this.authConfig = authConfig;
5159 this.availableModels = (assistant.models?.filter(
@@ -56,18 +64,67 @@
5664 // Check if we have a persisted model name and use it if valid
5765 const persistedModelName = getModelName(authConfig);
5866 if (persistedModelName) {
59- const modelIndex = this.getModelIndexByName(persistedModelName);
67+ // During initialization, we need to check against availableModels directly
68+ const modelIndex = this.availableModels.findIndex((model) => {
69+ const name = (model as any).name || (model as any).model;
70+ return name === persistedModelName;
71+ });
6072 if (modelIndex === -1) {
6173 // Model name not found, use default model selection
6274 const [llmApi, model] = getLlmApi(assistant, authConfig);
6375 return {
6476 llmApi,
6577 model,
78+ assistant,
79+ authConfig,
6680 };
6781 } else {
68- // Use the persisted model
69- const state = await this.switchModel(modelIndex);
70- return state;
82+ // Use the persisted model - but we need to handle initialization specially
83+ // During init, currentState isn't set yet, so switchModel would fail
84+ // Instead, we'll manually switch here
85+ const selectedModel = this.availableModels[modelIndex];
86+ logger.debug("Using persisted model during initialization", {
87+ modelIndex,
88+ provider: selectedModel.provider,
89+ name: (selectedModel as any).name || "unnamed",
90+ });
91+
92+ const accessToken = getAccessToken(authConfig);
93+ const organizationId = getOrganizationId(authConfig);
94+
95+ const config: LLMConfig =
96+ selectedModel.provider === "continue-proxy"
97+ ? {
98+ provider: selectedModel.provider,
99+ requestOptions: selectedModel.requestOptions,
100+ apiBase: selectedModel.apiBase,
101+ apiKey: accessToken ?? undefined,
102+ env: {
103+ apiKeyLocation: (selectedModel as any).apiKeyLocation,
104+ orgScopeId: organizationId,
105+ proxyUrl: undefined,
106+ },
107+ }
108+ : {
109+ provider: selectedModel.provider as any,
110+ apiKey: selectedModel.apiKey,
111+ apiBase: selectedModel.apiBase,
112+ requestOptions: selectedModel.requestOptions,
113+ env: selectedModel.env,
114+ };
115+
116+ const llmApi = constructLlmApi(config);
117+
118+ if (!llmApi) {
119+ throw new Error("Failed to initialize LLM with persisted model");
120+ }
121+
122+ return {
123+ llmApi,
124+ model: selectedModel,
125+ assistant,
126+ authConfig,
127+ };
71128 }
72129 } else {
73130 // Use default model selection
@@ -75,6 +132,8 @@
75132 return {
76133 llmApi,
77134 model,
135+ assistant,
136+ authConfig,
78137 };
79138 }
80139 }
@@ -89,6 +148,7 @@
89148 logger.debug("Updating ModelService");
90149
91150 try {
151+ // Update instance properties for backward compatibility
92152 this.assistant = assistant;
93153 this.authConfig = authConfig;
94154 this.availableModels = (assistant.models?.filter(
@@ -98,9 +158,12 @@
98158
99159 const [llmApi, model] = getLlmApi(assistant, authConfig);
100160
161+ // Ensure state has all necessary data
101162 this.setState({
102163 llmApi,
103164 model,
165+ assistant,
166+ authConfig,
104167 });
105168
106169 logger.debug("ModelService updated successfully", {
@@ -150,7 +213,19 @@
150213 name: string;
151214 index: number;
152215 }> {
153- return this.availableModels.map((model, index) => ({
216+ // Get assistant from state to ensure we have the latest data
217+ const { assistant } = this.getState();
218+ if (!assistant || !assistant.models) {
219+ return [];
220+ }
221+
222+ // Filter for chat models
223+ const chatModels = (assistant.models.filter(
224+ (model) =>
225+ model && (model.roles?.includes("chat") || model.roles === undefined),
226+ ) || []) as ModelConfig[];
227+
228+ return chatModels.map((model, index) => ({
154229 provider: model.provider,
155230 name: (model as any).name || (model as any).model || "unnamed",
156231 index,
@@ -161,17 +236,51 @@
161236 * Switch to a different chat model by index
162237 */
163238 async switchModel(modelIndex: number): Promise<ModelServiceState> {
164- if (!this.assistant || !this.authConfig) {
165- throw new Error("ModelService not initialized");
239+ // Get assistant and authConfig from state, but fall back to instance properties
240+ // This is needed during initialization when state isn't set yet
241+ const stateValues = this.getState();
242+ const assistant = stateValues.assistant || this.assistant;
243+ const authConfig = stateValues.authConfig || this.authConfig;
244+
245+ // Debug logging to understand the state
246+ logger.debug("switchModel: Checking state", {
247+ hasStateAssistant: !!stateValues.assistant,
248+ hasStateAuthConfig: !!stateValues.authConfig,
249+ hasInstanceAssistant: !!this.assistant,
250+ hasInstanceAuthConfig: !!this.authConfig,
251+ isInitialized: this.isReady(),
252+ isReady: this.isReady(),
253+ modelIndex,
254+ });
255+
256+ if (!assistant) {
257+ logger.error("switchModel: Missing assistant data", {
258+ assistant: !!assistant,
259+ authConfig: !!authConfig,
260+ stateKeys: Object.keys(stateValues),
261+ currentState: {
262+ hasLlmApi: !!stateValues.llmApi,
263+ hasModel: !!stateValues.model,
264+ hasAssistant: !!stateValues.assistant,
265+ hasAuthConfig: !!stateValues.authConfig,
266+ },
267+ });
268+ throw new Error("ModelService not initialized - assistant data missing");
166269 }
167270
168- if (modelIndex < 0 || modelIndex >= this.availableModels.length) {
271+ // Get available models from assistant in state
272+ const availableModels = (assistant.models?.filter(
273+ (model) =>
274+ model && (model.roles?.includes("chat") || model.roles === undefined),
275+ ) || []) as ModelConfig[];
276+
277+ if (modelIndex < 0 || modelIndex >= availableModels.length) {
169278 throw new Error(
170- `Invalid model index: ${modelIndex}. Available models: 0-${this.availableModels.length - 1}`,
279+ `Invalid model index: ${modelIndex}. Available models: 0-${availableModels.length - 1}`,
171280 );
172281 }
173282
174- const selectedModel = this.availableModels[modelIndex];
283+ const selectedModel = availableModels[modelIndex];
175284 logger.debug("Switching to model", {
176285 modelIndex,
177286 provider: selectedModel.provider,
@@ -179,8 +288,8 @@
179288 });
180289
181290 try {
182- const accessToken = getAccessToken(this.authConfig);
183- const organizationId = getOrganizationId(this.authConfig);
291+ const accessToken = getAccessToken(authConfig);
292+ const organizationId = getOrganizationId(authConfig);
184293
185294 const config: LLMConfig =
186295 selectedModel.provider === "continue-proxy"
@@ -212,6 +321,8 @@
212321 this.setState({
213322 llmApi,
214323 model: selectedModel,
324+ assistant,
325+ authConfig,
215326 });
216327
217328 logger.debug("Model switched successfully", {
@@ -231,14 +342,21 @@
231342 * Get current model index
232343 */
233344 getCurrentModelIndex(): number {
234- if (!this.currentState.model) {
345+ const state = this.getState();
346+ if (!state.model || !state.assistant) {
235347 return -1;
236348 }
237349
238- return this.availableModels.findIndex(
350+ // Get available models from state
351+ const availableModels = (state.assistant.models?.filter(
352+ (model) =>
353+ model && (model.roles?.includes("chat") || model.roles === undefined),
354+ ) || []) as ModelConfig[];
355+
356+ return availableModels.findIndex(
239357 (model) =>
240- model.provider === this.currentState.model?.provider &&
241- (model as any).name === (this.currentState.model as any).name,
358+ model.provider === state.model?.provider &&
359+ (model as any).name === (state.model as any).name,
242360 );
243361 }
244362
@@ -246,7 +364,18 @@
246364 * Get model index by name and provider
247365 */
248366 getModelIndexByName(modelName: string, provider?: string): number {
249- return this.availableModels.findIndex((model) => {
367+ const state = this.getState();
368+ if (!state.assistant) {
369+ return -1;
370+ }
371+
372+ // Get available models from state
373+ const availableModels = (state.assistant.models?.filter(
374+ (model) =>
375+ model && (model.roles?.includes("chat") || model.roles === undefined),
376+ ) || []) as ModelConfig[];
377+
378+ return availableModels.findIndex((model) => {
250379 const name = (model as any).name || (model as any).model;
251380 const nameMatches = name === modelName;
252381
modified extensions/cli/src/services/types.ts +2 −0
@@ -52,6 +52,8 @@
5252 export interface ModelServiceState {
5353 llmApi: BaseLlmApi | null;
5454 model: ModelConfig | null;
55+ assistant: AssistantUnrolled | null;
56+ authConfig: AuthConfig | null;
5557 }
5658
5759 export type MCPServerStatus = "idle" | "connecting" | "connected" | "error";
modified extensions/cli/src/ui/IntroMessage.test.tsx +9 −13
@@ -51,14 +51,14 @@
5151
5252 // Count occurrences of "nate/spanish" in the output
5353 const matches = output?.match(/nate\/spanish/g) || [];
54-
54+
5555 // Should appear exactly once, not twice
5656 expect(matches.length).toBe(1);
57-
57+
5858 // Verify the slug is shown, not the content
5959 expect(output).toContain("nate/spanish");
6060 expect(output).not.toContain("Always respond in Spanish");
61-
61+
6262 // Verify plain string rule is shown as-is
6363 expect(output).toContain("Always be helpful");
6464 });
@@ -66,11 +66,7 @@
6666 it("should display rules from config correctly", () => {
6767 const config: AssistantUnrolled = {
6868 name: "Test Assistant",
69- rules: [
70- "Rule 1",
71- { name: "Rule 2" },
72- "Rule 3",
73- ],
69+ rules: ["Rule 1", { name: "Rule 2" }, "Rule 3"],
7470 } as any;
7571
7672 const { lastFrame } = render(
@@ -134,15 +130,15 @@
134130 const config: AssistantUnrolled = {
135131 name: "Test Assistant",
136132 rules: [
137- {
138- name: "org/complex-rule",
133+ {
134+ name: "org/complex-rule",
139135 rule: `---
140136 alwaysApply: true
141137 ---
142138
143139 This is a very long rule content that should not be displayed.
144140 It contains multiple lines and complex formatting.
145-The UI should only show the slug 'org/complex-rule'.`
141+The UI should only show the slug 'org/complex-rule'.`,
146142 },
147143 { name: "another/rule", rule: "Short content" },
148144 ],
@@ -161,10 +157,10 @@
161157 // Should show slugs only
162158 expect(output).toContain("org/complex-rule");
163159 expect(output).toContain("another/rule");
164-
160+
165161 // Should NOT show the rule content
166162 expect(output).not.toContain("This is a very long rule");
167163 expect(output).not.toContain("alwaysApply");
168164 expect(output).not.toContain("Short content");
169165 });
170-});
No newline at the end of the file
166+});
added extensions/cli/test-fixtures/model-switch-test-config.yaml +18 −0
@@ -0,0 +1,18 @@
1+name: Model Switch Test Config
2+version: 1.0.0
3+
4+models:
5+ - name: GPT-4
6+ provider: openai
7+ model: gpt-4
8+ apiKey: test-api-key-1
9+
10+ - name: GPT-3.5
11+ provider: openai
12+ model: gpt-3.5-turbo
13+ apiKey: test-api-key-2
14+
15+ - name: Claude 3
16+ provider: anthropic
17+ model: claude-3-opus
18+ apiKey: test-api-key-3
No newline at the end of the file
modified package-lock.json +1 −1
@@ -1,5 +1,5 @@
11 {
2- "name": "wt-nate-4",
2+ "name": "wt-mcp-flag",
33 "lockfileVersion": 3,
44 "requires": true,
55 "packages": {