fix: model switcher not working when signed out, and other improvements
This commit is contained in:
parent
07f092402d
commit
791ad6bb17
21 changed files with 598 additions and 405 deletions
|
|
@ -38,13 +38,7 @@ describe("parseArgs --mcp flag", () => {
|
|||
});
|
||||
|
||||
it("should handle MCP flag with prompt", () => {
|
||||
process.argv = [
|
||||
"node",
|
||||
"test",
|
||||
"--mcp",
|
||||
"my-org/my-mcp",
|
||||
"hello world"
|
||||
];
|
||||
process.argv = ["node", "test", "--mcp", "my-org/my-mcp", "hello world"];
|
||||
const result = parseArgs();
|
||||
expect(result.mcps).toEqual(["my-org/my-mcp"]);
|
||||
expect(result.prompt).toBe("hello world");
|
||||
|
|
@ -57,8 +51,8 @@ describe("parseArgs --mcp flag", () => {
|
|||
"actual prompt",
|
||||
"--rule",
|
||||
"my-rule",
|
||||
"--mcp",
|
||||
"my-org/my-mcp"
|
||||
"--mcp",
|
||||
"my-org/my-mcp",
|
||||
];
|
||||
const result = parseArgs();
|
||||
expect(result.prompt).toBe("actual prompt");
|
||||
|
|
@ -78,4 +72,4 @@ describe("parseArgs --mcp flag", () => {
|
|||
expect(result.prompt).toBe("my prompt");
|
||||
expect(result.mcps).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -37,7 +37,10 @@ function extractMultipleFlags(args: string[], flagName: string): string[] {
|
|||
/**
|
||||
* Extract value for a single-value flag
|
||||
*/
|
||||
function extractSingleFlag(args: string[], flagName: string): string | undefined {
|
||||
function extractSingleFlag(
|
||||
args: string[],
|
||||
flagName: string,
|
||||
): string | undefined {
|
||||
const index = args.indexOf(flagName);
|
||||
if (index !== -1 && index + 1 < args.length) {
|
||||
return args[index + 1];
|
||||
|
|
@ -69,10 +72,10 @@ export function parseArgs(): CommandLineArgs {
|
|||
}
|
||||
|
||||
result.configPath = extractSingleFlag(args, "--config");
|
||||
|
||||
|
||||
const orgValue = extractSingleFlag(args, "--org");
|
||||
if (orgValue) {
|
||||
result.organizationSlug =
|
||||
result.organizationSlug =
|
||||
orgValue.toLowerCase() === "personal" ? undefined : orgValue;
|
||||
}
|
||||
|
||||
|
|
@ -107,7 +110,15 @@ export function parseArgs(): CommandLineArgs {
|
|||
}
|
||||
|
||||
// Extract prompt from non-flag arguments
|
||||
const flagsWithValues = ["--config", "--org", "--rule", "--mcp", "--model", "--prompt", "--format"];
|
||||
const flagsWithValues = [
|
||||
"--config",
|
||||
"--org",
|
||||
"--rule",
|
||||
"--mcp",
|
||||
"--model",
|
||||
"--prompt",
|
||||
"--format",
|
||||
];
|
||||
const nonFlagArgs = args.filter((arg, index) => {
|
||||
if (arg.startsWith("--") || arg === "-p") return false;
|
||||
const prevArg = index > 0 ? args[index - 1] : "";
|
||||
|
|
|
|||
|
|
@ -150,10 +150,26 @@ describe("ConfigEnhancer", () => {
|
|||
|
||||
// Models from --model flag should be prepended (at the start)
|
||||
expect(config.models).toHaveLength(4);
|
||||
expect(config.models?.[0]).toEqual({ name: "GPT-5", provider: "openai", model: "gpt-5" });
|
||||
expect(config.models?.[1]).toEqual({ name: "Claude-3", provider: "anthropic", model: "claude-3" });
|
||||
expect(config.models?.[2]).toEqual({ name: "GPT-4", provider: "openai", model: "gpt-4" });
|
||||
expect(config.models?.[3]).toEqual({ name: "Claude-2", provider: "anthropic", model: "claude-2" });
|
||||
expect(config.models?.[0]).toEqual({
|
||||
name: "GPT-5",
|
||||
provider: "openai",
|
||||
model: "gpt-5",
|
||||
});
|
||||
expect(config.models?.[1]).toEqual({
|
||||
name: "Claude-3",
|
||||
provider: "anthropic",
|
||||
model: "claude-3",
|
||||
});
|
||||
expect(config.models?.[2]).toEqual({
|
||||
name: "GPT-4",
|
||||
provider: "openai",
|
||||
model: "gpt-4",
|
||||
});
|
||||
expect(config.models?.[3]).toEqual({
|
||||
name: "Claude-2",
|
||||
provider: "anthropic",
|
||||
model: "claude-2",
|
||||
});
|
||||
});
|
||||
|
||||
it("should prepend MCPs from --mcp flag", async () => {
|
||||
|
|
@ -164,9 +180,7 @@ describe("ConfigEnhancer", () => {
|
|||
]);
|
||||
|
||||
// Set up existing MCPs in config
|
||||
mockConfig.mcpServers = [
|
||||
{ name: "Existing-MCP", command: "existing-mcp" },
|
||||
];
|
||||
mockConfig.mcpServers = [{ name: "Existing-MCP", command: "existing-mcp" }];
|
||||
|
||||
const options: BaseCommandOptions = {
|
||||
mcp: ["test/new-mcp"],
|
||||
|
|
@ -176,7 +190,13 @@ describe("ConfigEnhancer", () => {
|
|||
|
||||
// MCPs from --mcp flag should be prepended (at the start)
|
||||
expect(config.mcpServers).toHaveLength(2);
|
||||
expect(config.mcpServers?.[0]).toEqual({ name: "New-MCP", command: "new-mcp" });
|
||||
expect(config.mcpServers?.[1]).toEqual({ name: "Existing-MCP", command: "existing-mcp" });
|
||||
expect(config.mcpServers?.[0]).toEqual({
|
||||
name: "New-MCP",
|
||||
command: "new-mcp",
|
||||
});
|
||||
expect(config.mcpServers?.[1]).toEqual({
|
||||
name: "Existing-MCP",
|
||||
command: "existing-mcp",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -57,12 +57,13 @@ export class ConfigEnhancer {
|
|||
for (const ruleSpec of rules) {
|
||||
try {
|
||||
const processedContent = await processRule(ruleSpec);
|
||||
|
||||
|
||||
// Check if this is a hub slug (contains / but doesn't start with . or /)
|
||||
const isHubSlug = ruleSpec.includes("/") &&
|
||||
!ruleSpec.startsWith(".") &&
|
||||
!ruleSpec.startsWith("/");
|
||||
|
||||
const isHubSlug =
|
||||
ruleSpec.includes("/") &&
|
||||
!ruleSpec.startsWith(".") &&
|
||||
!ruleSpec.startsWith("/");
|
||||
|
||||
if (isHubSlug) {
|
||||
// Store as RuleObject with name (slug) and rule (content)
|
||||
processedRules.push({
|
||||
|
|
@ -149,4 +150,4 @@ export class ConfigEnhancer {
|
|||
/**
|
||||
* Global config enhancer instance
|
||||
*/
|
||||
export const configEnhancer = new ConfigEnhancer();
|
||||
export const configEnhancer = new ConfigEnhancer();
|
||||
|
|
|
|||
|
|
@ -301,6 +301,16 @@ async function unrollAssistantWithConfig(
|
|||
renderSecrets: true,
|
||||
platformClient: new CLIPlatformClient(organizationId, apiClient),
|
||||
onPremProxyUrl: null,
|
||||
injectBlocks: [
|
||||
{
|
||||
uriType: "slug",
|
||||
fullSlug: {
|
||||
ownerSlug: "openai",
|
||||
packageSlug: "gpt-5",
|
||||
versionSlug: "latest",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ global.fetch = mockFetch;
|
|||
|
||||
// Mock JSZip
|
||||
vi.mock("jszip", () => ({
|
||||
default: vi.fn()
|
||||
default: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockedJSZip = vi.fn();
|
||||
|
|
@ -45,7 +45,9 @@ describe("hubLoader", () => {
|
|||
|
||||
await expect(
|
||||
loadPackageFromHub("owner/package", ruleProcessor),
|
||||
).rejects.toThrow('Failed to load rule from hub "owner/package": HTTP 404: Not Found');
|
||||
).rejects.toThrow(
|
||||
'Failed to load rule from hub "owner/package": HTTP 404: Not Found',
|
||||
);
|
||||
});
|
||||
|
||||
it("should load rule content", async () => {
|
||||
|
|
@ -54,9 +56,9 @@ describe("hubLoader", () => {
|
|||
// Check if JSZip is mocked
|
||||
const JSZipModule = await import("jszip");
|
||||
const JSZip = JSZipModule.default;
|
||||
|
||||
|
||||
// Since JSZip is mocked, it should be a mock function
|
||||
if (typeof (JSZip as any).mockImplementation === 'function') {
|
||||
if (typeof (JSZip as any).mockImplementation === "function") {
|
||||
(JSZip as any).mockImplementation(() => ({
|
||||
loadAsync: vi.fn().mockResolvedValueOnce({
|
||||
files: {
|
||||
|
|
@ -65,7 +67,7 @@ describe("hubLoader", () => {
|
|||
async: vi.fn().mockResolvedValue(ruleContent),
|
||||
},
|
||||
},
|
||||
})
|
||||
}),
|
||||
}));
|
||||
} else {
|
||||
// If mock doesn't work, skip this test
|
||||
|
|
@ -84,7 +86,7 @@ describe("hubLoader", () => {
|
|||
|
||||
it("should load MCP configuration", async () => {
|
||||
const mcpConfig = {
|
||||
content: "name: test-mcp\nversion: 1.0.0"
|
||||
content: "name: test-mcp\nversion: 1.0.0",
|
||||
};
|
||||
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
|
|
@ -96,7 +98,7 @@ describe("hubLoader", () => {
|
|||
// Should parse the YAML content, not return the wrapper
|
||||
expect(result).toEqual({
|
||||
name: "test-mcp",
|
||||
version: "1.0.0"
|
||||
version: "1.0.0",
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -104,9 +106,9 @@ describe("hubLoader", () => {
|
|||
// Check if JSZip is mocked
|
||||
const JSZipModule = await import("jszip");
|
||||
const JSZip = JSZipModule.default;
|
||||
|
||||
|
||||
// Since JSZip is mocked, it should be a mock function
|
||||
if (typeof (JSZip as any).mockImplementation === 'function') {
|
||||
if (typeof (JSZip as any).mockImplementation === "function") {
|
||||
(JSZip as any).mockImplementation(() => ({
|
||||
loadAsync: vi.fn().mockResolvedValueOnce({
|
||||
files: {
|
||||
|
|
@ -115,7 +117,7 @@ describe("hubLoader", () => {
|
|||
async: vi.fn().mockResolvedValue("not a rule"),
|
||||
},
|
||||
},
|
||||
})
|
||||
}),
|
||||
}));
|
||||
} else {
|
||||
// If mock doesn't work, skip this test
|
||||
|
|
@ -140,23 +142,35 @@ describe("hubLoader", () => {
|
|||
it("should define rule processor correctly", () => {
|
||||
expect(ruleProcessor.type).toBe("rule");
|
||||
expect(ruleProcessor.expectedFileExtensions).toEqual([".md"]);
|
||||
expect(ruleProcessor.parseContent("test content", "test.md")).toBe("test content");
|
||||
expect(ruleProcessor.parseContent("test content", "test.md")).toBe(
|
||||
"test content",
|
||||
);
|
||||
});
|
||||
|
||||
it("should define MCP processor correctly", () => {
|
||||
expect(mcpProcessor.type).toBe("mcp");
|
||||
expect(mcpProcessor.expectedFileExtensions).toEqual([".json", ".yaml", ".yml"]);
|
||||
expect(mcpProcessor.expectedFileExtensions).toEqual([
|
||||
".json",
|
||||
".yaml",
|
||||
".yml",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should define model processor correctly", () => {
|
||||
expect(modelProcessor.type).toBe("model");
|
||||
expect(modelProcessor.expectedFileExtensions).toEqual([".json", ".yaml", ".yml"]);
|
||||
expect(modelProcessor.expectedFileExtensions).toEqual([
|
||||
".json",
|
||||
".yaml",
|
||||
".yml",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should define prompt processor correctly", () => {
|
||||
expect(promptProcessor.type).toBe("prompt");
|
||||
expect(promptProcessor.expectedFileExtensions).toEqual([".md", ".txt"]);
|
||||
expect(promptProcessor.parseContent("test content", "test.md")).toBe("test content");
|
||||
expect(promptProcessor.parseContent("test content", "test.md")).toBe(
|
||||
"test content",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -171,8 +185,11 @@ describe("hubLoader", () => {
|
|||
});
|
||||
|
||||
it("should load rule from real hub: sanity/sanity-opinionated", async () => {
|
||||
const result = await loadPackageFromHub("sanity/sanity-opinionated", ruleProcessor);
|
||||
|
||||
const result = await loadPackageFromHub(
|
||||
"sanity/sanity-opinionated",
|
||||
ruleProcessor,
|
||||
);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(typeof result).toBe("string");
|
||||
expect(result.length).toBeGreaterThan(0);
|
||||
|
|
@ -184,10 +201,10 @@ describe("hubLoader", () => {
|
|||
// Restore real fetch and JSZip for this test
|
||||
global.fetch = originalFetch;
|
||||
vi.unmock("jszip");
|
||||
|
||||
|
||||
const testSlug = "upstash/context7-mcp";
|
||||
const result = await loadPackageFromHub(testSlug, mcpProcessor);
|
||||
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(typeof result).toBe("object");
|
||||
// Should now return the parsed MCP configuration
|
||||
|
|
@ -202,10 +219,10 @@ describe("hubLoader", () => {
|
|||
// Restore real fetch and JSZip for this test
|
||||
global.fetch = originalFetch;
|
||||
vi.unmock("jszip");
|
||||
|
||||
|
||||
const testSlug = "openai/gpt-5";
|
||||
const result = await loadPackageFromHub(testSlug, modelProcessor);
|
||||
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(typeof result).toBe("object");
|
||||
// Should now return the extracted model from the models array
|
||||
|
|
@ -219,11 +236,14 @@ describe("hubLoader", () => {
|
|||
}, 30000);
|
||||
|
||||
it("should load prompt from real hub: launchdarkly/using-flags", async () => {
|
||||
const result = await loadPackageFromHub("launchdarkly/using-flags", promptProcessor);
|
||||
|
||||
const result = await loadPackageFromHub(
|
||||
"launchdarkly/using-flags",
|
||||
promptProcessor,
|
||||
);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(typeof result).toBe("string");
|
||||
expect(result.length).toBeGreaterThan(0);
|
||||
}, 30000);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -41,13 +41,17 @@ export const mcpProcessor: HubPackageProcessor<any> = {
|
|||
const yaml = await import("yaml");
|
||||
parsed = yaml.parse(content);
|
||||
}
|
||||
|
||||
|
||||
// If the parsed content has an 'mcpServers' array, extract the first MCP server
|
||||
// This handles hub packages that return a full config block
|
||||
if (parsed.mcpServers && Array.isArray(parsed.mcpServers) && parsed.mcpServers.length > 0) {
|
||||
if (
|
||||
parsed.mcpServers &&
|
||||
Array.isArray(parsed.mcpServers) &&
|
||||
parsed.mcpServers.length > 0
|
||||
) {
|
||||
return parsed.mcpServers[0];
|
||||
}
|
||||
|
||||
|
||||
return parsed;
|
||||
},
|
||||
};
|
||||
|
|
@ -66,13 +70,17 @@ export const modelProcessor: HubPackageProcessor<any> = {
|
|||
const yaml = await import("yaml");
|
||||
parsed = yaml.parse(content);
|
||||
}
|
||||
|
||||
|
||||
// If the parsed content has a 'models' array, extract the first model
|
||||
// This handles hub packages that return a full config block
|
||||
if (parsed.models && Array.isArray(parsed.models) && parsed.models.length > 0) {
|
||||
if (
|
||||
parsed.models &&
|
||||
Array.isArray(parsed.models) &&
|
||||
parsed.models.length > 0
|
||||
) {
|
||||
return parsed.models[0];
|
||||
}
|
||||
|
||||
|
||||
return parsed;
|
||||
},
|
||||
};
|
||||
|
|
@ -101,7 +109,7 @@ export async function loadPackageFromHub<T>(
|
|||
}
|
||||
|
||||
const [ownerSlug, packageSlug] = parts;
|
||||
|
||||
|
||||
// Use different endpoints based on package type
|
||||
let downloadUrl: URL;
|
||||
if (processor.type === "mcp" || processor.type === "model") {
|
||||
|
|
@ -129,7 +137,7 @@ export async function loadPackageFromHub<T>(
|
|||
if (processor.type === "mcp" || processor.type === "model") {
|
||||
// Registry endpoints return JSON with a 'content' field containing YAML/JSON
|
||||
const jsonResponse = await response.json();
|
||||
|
||||
|
||||
// Extract and parse the content field
|
||||
if (jsonResponse.content) {
|
||||
// Parse the YAML/JSON content
|
||||
|
|
@ -149,12 +157,14 @@ export async function loadPackageFromHub<T>(
|
|||
const zipContents = await zip.loadAsync(arrayBuffer);
|
||||
|
||||
// Find files matching expected extensions
|
||||
const matchingFiles = Object.keys(zipContents.files).filter((filename) => {
|
||||
if (zipContents.files[filename].dir) return false;
|
||||
return processor.expectedFileExtensions.some((ext) =>
|
||||
filename.endsWith(ext),
|
||||
);
|
||||
});
|
||||
const matchingFiles = Object.keys(zipContents.files).filter(
|
||||
(filename) => {
|
||||
if (zipContents.files[filename].dir) return false;
|
||||
return processor.expectedFileExtensions.some((ext) =>
|
||||
filename.endsWith(ext),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
if (matchingFiles.length === 0) {
|
||||
throw new Error(
|
||||
|
|
@ -173,8 +183,13 @@ export async function loadPackageFromHub<T>(
|
|||
);
|
||||
|
||||
// Validate if processor has validation
|
||||
if (processor.validateContent && !processor.validateContent(parsedContent)) {
|
||||
throw new Error(`Invalid ${processor.type} content in ${matchingFiles[0]}`);
|
||||
if (
|
||||
processor.validateContent &&
|
||||
!processor.validateContent(parsedContent)
|
||||
) {
|
||||
throw new Error(
|
||||
`Invalid ${processor.type} content in ${matchingFiles[0]}`,
|
||||
);
|
||||
}
|
||||
|
||||
return parsedContent;
|
||||
|
|
@ -222,7 +237,7 @@ export async function processRule(ruleSpec: string): Promise<string> {
|
|||
) {
|
||||
const fs = await import("fs");
|
||||
const path = await import("path");
|
||||
|
||||
|
||||
try {
|
||||
const absolutePath = path.resolve(ruleSpec);
|
||||
if (!fs.existsSync(absolutePath)) {
|
||||
|
|
@ -230,7 +245,9 @@ export async function processRule(ruleSpec: string): Promise<string> {
|
|||
}
|
||||
return fs.readFileSync(absolutePath, "utf-8");
|
||||
} catch (error: any) {
|
||||
throw new Error(`Failed to read rule file "${ruleSpec}": ${error.message}`);
|
||||
throw new Error(
|
||||
`Failed to read rule file "${ruleSpec}": ${error.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -252,9 +269,11 @@ export async function loadPackagesFromHub<T>(
|
|||
const content = await loadPackageFromHub(slug, processor);
|
||||
results.push(content);
|
||||
} catch (error: any) {
|
||||
logger.warn(`Failed to load ${processor.type} "${slug}": ${error.message}`);
|
||||
logger.warn(
|
||||
`Failed to load ${processor.type} "${slug}": ${error.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { AssistantUnrolled } from "@continuedev/config-yaml";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { BaseCommandOptions } from "../commands/BaseCommandOptions.js";
|
||||
import { ConfigEnhancer } from "../configEnhancer.js";
|
||||
|
|
@ -22,7 +22,7 @@ vi.mock("../hubLoader.js", () => ({
|
|||
describe("Rule duplication integration test", () => {
|
||||
it("should not duplicate rules when using --rule flag", async () => {
|
||||
const enhancer = new ConfigEnhancer();
|
||||
|
||||
|
||||
// Initial config without any rules
|
||||
const initialConfig: AssistantUnrolled = {
|
||||
name: "Test Assistant",
|
||||
|
|
@ -40,13 +40,13 @@ describe("Rule duplication integration test", () => {
|
|||
// Verify the rule was added exactly once as a RuleObject
|
||||
expect(enhancedConfig.rules).toHaveLength(1);
|
||||
expect(enhancedConfig.rules).toEqual([
|
||||
{ name: "nate/spanish", rule: "Content for nate/spanish" }
|
||||
{ name: "nate/spanish", rule: "Content for nate/spanish" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should merge command-line rules with existing config rules", async () => {
|
||||
const enhancer = new ConfigEnhancer();
|
||||
|
||||
|
||||
// Initial config with existing rules
|
||||
const initialConfig: AssistantUnrolled = {
|
||||
name: "Test Assistant",
|
||||
|
|
@ -72,7 +72,7 @@ describe("Rule duplication integration test", () => {
|
|||
|
||||
it("should handle rule content with frontmatter", async () => {
|
||||
const enhancer = new ConfigEnhancer();
|
||||
|
||||
|
||||
// Mock processRule to return content with frontmatter
|
||||
const { processRule } = await import("../hubLoader.js");
|
||||
(processRule as any).mockImplementation((rule: string) => {
|
||||
|
|
@ -104,4 +104,4 @@ Always respond in Spanish.`);
|
|||
expect(ruleObj.rule).toContain("Always respond in Spanish.");
|
||||
expect(ruleObj.rule).toContain("alwaysApply: true");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ describe("loadMcpFromHub", () => {
|
|||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
|
||||
// Get the mocked JSZip constructor
|
||||
const JSZip = (await import("jszip")).default;
|
||||
mockJSZip = new JSZip();
|
||||
|
|
@ -52,13 +52,14 @@ describe("loadMcpFromHub", () => {
|
|||
|
||||
it("should parse JSON configuration files", async () => {
|
||||
const mockConfig = {
|
||||
content: "name: test-mcp\ncommand: npx test-mcp\nargs:\n - --port\n - 3000"
|
||||
content:
|
||||
"name: test-mcp\ncommand: npx test-mcp\nargs:\n - --port\n - 3000",
|
||||
};
|
||||
|
||||
// MCP packages now use the registry endpoint and return JSON directly
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue(mockConfig)
|
||||
json: vi.fn().mockResolvedValue(mockConfig),
|
||||
});
|
||||
|
||||
const result = await loadMcpFromHub("continuedev/test-mcp");
|
||||
|
|
@ -66,7 +67,7 @@ describe("loadMcpFromHub", () => {
|
|||
expect(result).toEqual({
|
||||
name: "test-mcp",
|
||||
command: "npx test-mcp",
|
||||
args: ["--port", 3000]
|
||||
args: ["--port", 3000],
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -75,7 +76,7 @@ describe("loadMcpFromHub", () => {
|
|||
// If the content field is missing or empty, it should fail
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue({})
|
||||
json: vi.fn().mockResolvedValue({}),
|
||||
});
|
||||
|
||||
const result = await loadMcpFromHub("continuedev/no-config");
|
||||
|
|
@ -88,11 +89,11 @@ describe("loadMcpFromHub", () => {
|
|||
// If the registry returns invalid JSON, it should fail at the fetch level
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: vi.fn().mockRejectedValue(new Error("Invalid JSON"))
|
||||
json: vi.fn().mockRejectedValue(new Error("Invalid JSON")),
|
||||
});
|
||||
|
||||
await expect(loadMcpFromHub("continuedev/invalid-json")).rejects.toThrow(
|
||||
'Failed to load mcp from hub "continuedev/invalid-json": Invalid JSON',
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -13,23 +13,26 @@ describe("--mcp flag integration", () => {
|
|||
it("should demonstrate the complete --mcp flag functionality", () => {
|
||||
// Test command line parsing
|
||||
process.argv = [
|
||||
"node",
|
||||
"node",
|
||||
"test",
|
||||
"--config", "my-config.yaml",
|
||||
"--mcp", "continuedev/filesystem",
|
||||
"--mcp", "continuedev/github",
|
||||
"hello world"
|
||||
"--config",
|
||||
"my-config.yaml",
|
||||
"--mcp",
|
||||
"continuedev/filesystem",
|
||||
"--mcp",
|
||||
"continuedev/github",
|
||||
"hello world",
|
||||
];
|
||||
|
||||
const args = parseArgs();
|
||||
|
||||
|
||||
// Verify the parsed command line arguments
|
||||
expect(args).toEqual({
|
||||
configPath: "my-config.yaml",
|
||||
mcps: ["continuedev/filesystem", "continuedev/github"],
|
||||
prompt: "hello world"
|
||||
prompt: "hello world",
|
||||
});
|
||||
|
||||
|
||||
// Verify MCP slugs are properly captured
|
||||
expect(args.mcps).toHaveLength(2);
|
||||
expect(args.mcps).toContain("continuedev/filesystem");
|
||||
|
|
@ -39,34 +42,39 @@ describe("--mcp flag integration", () => {
|
|||
it("should validate MCP slug format", async () => {
|
||||
// Test that invalid slug formats are rejected
|
||||
await expect(loadMcpFromHub("invalid-slug")).rejects.toThrow(
|
||||
'Invalid hub slug format. Expected "owner/package", got: invalid-slug'
|
||||
'Invalid hub slug format. Expected "owner/package", got: invalid-slug',
|
||||
);
|
||||
|
||||
// Valid format should not throw during validation step
|
||||
const mockFetch = vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 404,
|
||||
statusText: "Not Found"
|
||||
statusText: "Not Found",
|
||||
});
|
||||
global.fetch = mockFetch;
|
||||
|
||||
// This will fail at the HTTP level, not validation level
|
||||
await expect(loadMcpFromHub("valid/slug")).rejects.toThrow(
|
||||
'Failed to load mcp from hub "valid/slug": HTTP 404: Not Found'
|
||||
'Failed to load mcp from hub "valid/slug": HTTP 404: Not Found',
|
||||
);
|
||||
});
|
||||
|
||||
it("should demonstrate MCP flag with other command line options", () => {
|
||||
process.argv = [
|
||||
"node",
|
||||
"test",
|
||||
"--config", "test-config.yaml",
|
||||
"--org", "my-org",
|
||||
"--rule", "my-rule",
|
||||
"--mcp", "continuedev/filesystem",
|
||||
"--allow", "readFile",
|
||||
"test",
|
||||
"--config",
|
||||
"test-config.yaml",
|
||||
"--org",
|
||||
"my-org",
|
||||
"--rule",
|
||||
"my-rule",
|
||||
"--mcp",
|
||||
"continuedev/filesystem",
|
||||
"--allow",
|
||||
"readFile",
|
||||
"--readonly",
|
||||
"analyze this code"
|
||||
"analyze this code",
|
||||
];
|
||||
|
||||
const args = parseArgs();
|
||||
|
|
@ -74,11 +82,11 @@ describe("--mcp flag integration", () => {
|
|||
// Verify all flags are parsed correctly together
|
||||
expect(args).toEqual({
|
||||
configPath: "test-config.yaml",
|
||||
organizationSlug: "my-org",
|
||||
organizationSlug: "my-org",
|
||||
rules: ["my-rule"],
|
||||
mcps: ["continuedev/filesystem"],
|
||||
readonly: true,
|
||||
prompt: "analyze this code"
|
||||
prompt: "analyze this code",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -27,14 +27,20 @@ export abstract class BaseService<TState> extends EventEmitter {
|
|||
* Public initialization method that wraps the implementation
|
||||
*/
|
||||
async initialize(...args: any[]): Promise<TState> {
|
||||
logger.debug(`Initializing ${this.serviceName}`);
|
||||
logger.debug(`Initializing ${this.serviceName}`, {
|
||||
wasInitialized: this.isInitialized,
|
||||
hadPreviousState: !!this.currentState,
|
||||
});
|
||||
this.emit("initializing");
|
||||
|
||||
try {
|
||||
const state = await this.doInitialize(...args);
|
||||
this.currentState = state;
|
||||
this.isInitialized = true;
|
||||
logger.debug(`${this.serviceName} initialized successfully`);
|
||||
logger.debug(`${this.serviceName} initialized successfully`, {
|
||||
stateKeys: state ? Object.keys(state as any) : [],
|
||||
isNowInitialized: this.isInitialized,
|
||||
});
|
||||
this.emit("initialized", state);
|
||||
return state;
|
||||
} catch (error: any) {
|
||||
|
|
|
|||
|
|
@ -74,13 +74,13 @@ describe("ConfigService", () => {
|
|||
config: mockConfig as any,
|
||||
source: { type: "cli-flag", path: "/config.yaml" } as any,
|
||||
});
|
||||
|
||||
|
||||
const expectedConfig = {
|
||||
...mockConfig,
|
||||
systemMessage:
|
||||
"Test system message\n\nProcessed: rule1\n\nProcessed: rule2",
|
||||
};
|
||||
|
||||
|
||||
vi.mocked(configEnhancer.enhanceConfig).mockResolvedValue(expectedConfig);
|
||||
|
||||
const state = await service.initialize(
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
|
||||
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
|
||||
|
||||
import { AuthConfig, loadAuthConfig } from "../auth/workos.js";
|
||||
|
|
@ -53,7 +52,10 @@ export class ConfigService
|
|||
let config = result.config;
|
||||
|
||||
// Apply injected config if provided
|
||||
if (injectedConfigOptions && this.hasInjectedConfig(injectedConfigOptions)) {
|
||||
if (
|
||||
injectedConfigOptions &&
|
||||
this.hasInjectedConfig(injectedConfigOptions)
|
||||
) {
|
||||
config = await configEnhancer.enhanceConfig(
|
||||
config,
|
||||
injectedConfigOptions,
|
||||
|
|
@ -99,7 +101,10 @@ export class ConfigService
|
|||
let config = result.config;
|
||||
|
||||
// Apply injected config if provided
|
||||
if (injectedConfigOptions && this.hasInjectedConfig(injectedConfigOptions)) {
|
||||
if (
|
||||
injectedConfigOptions &&
|
||||
this.hasInjectedConfig(injectedConfigOptions)
|
||||
) {
|
||||
config = await configEnhancer.enhanceConfig(
|
||||
config,
|
||||
injectedConfigOptions,
|
||||
|
|
|
|||
207
extensions/cli/src/services/ModelService.direct.test.ts
Normal file
207
extensions/cli/src/services/ModelService.direct.test.ts
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
|
||||
import { ModelService } from "./ModelService.js";
|
||||
|
||||
describe("ModelService - Direct Testing", () => {
|
||||
let modelService: ModelService;
|
||||
|
||||
beforeEach(() => {
|
||||
modelService = new ModelService();
|
||||
});
|
||||
|
||||
it("should throw 'ModelService not initialized' when switching without initialization", async () => {
|
||||
// The service is created but not initialized (no assistant or authConfig)
|
||||
expect(modelService.getCurrentModelIndex()).toBe(-1);
|
||||
|
||||
// Try to switch model without initialization
|
||||
try {
|
||||
await modelService.switchModel(0);
|
||||
// Should not reach here
|
||||
expect(true).toBe(false);
|
||||
} catch (error: any) {
|
||||
// Should throw the specific error
|
||||
expect(error.message).toBe(
|
||||
"ModelService not initialized - assistant data missing",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("should handle model switching with null authConfig for non-proxy models", async () => {
|
||||
// Initialize the service properly
|
||||
const mockAssistant = {
|
||||
name: "Test Assistant",
|
||||
version: "1.0.0",
|
||||
models: [
|
||||
{
|
||||
name: "claude-3.5-sonnet",
|
||||
provider: "anthropic",
|
||||
model: "claude-3.5-sonnet",
|
||||
apiKey: "test-anthropic-key",
|
||||
roles: ["chat"],
|
||||
},
|
||||
{
|
||||
name: "GPT-4",
|
||||
provider: "openai",
|
||||
model: "gpt-4",
|
||||
apiKey: "test-openai-key",
|
||||
roles: ["chat"],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// Initialize with null authConfig - valid for non-proxy models
|
||||
const initialState = await modelService.initialize(
|
||||
mockAssistant as any,
|
||||
null as any,
|
||||
);
|
||||
|
||||
// Verify initialization succeeded with null authConfig
|
||||
expect(initialState.assistant).toBe(mockAssistant);
|
||||
expect(initialState.authConfig).toBe(null);
|
||||
expect(initialState.model).toBeDefined();
|
||||
expect((initialState.model as any).name).toBe("claude-3.5-sonnet");
|
||||
|
||||
// Should be able to switch models even with null authConfig
|
||||
const switchedState = await modelService.switchModel(1);
|
||||
expect(switchedState.model).toBeDefined();
|
||||
expect((switchedState.model as any).name).toBe("GPT-4");
|
||||
expect(switchedState.assistant).toBe(mockAssistant);
|
||||
expect(switchedState.authConfig).toBe(null);
|
||||
|
||||
// Verify the model info
|
||||
const modelInfo = modelService.getModelInfo();
|
||||
expect(modelInfo?.name).toBe("GPT-4");
|
||||
expect(modelInfo?.provider).toBe("openai");
|
||||
});
|
||||
|
||||
it("should successfully switch model after proper initialization", async () => {
|
||||
// Initialize the service properly
|
||||
const mockAssistant = {
|
||||
name: "Test Assistant",
|
||||
version: "1.0.0",
|
||||
models: [
|
||||
{
|
||||
name: "GPT-4",
|
||||
provider: "openai",
|
||||
model: "gpt-4",
|
||||
apiKey: "test-key-1",
|
||||
roles: ["chat"],
|
||||
},
|
||||
{
|
||||
name: "GPT-3.5",
|
||||
provider: "openai",
|
||||
model: "gpt-3.5-turbo",
|
||||
apiKey: "test-key-2",
|
||||
roles: ["chat"],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const mockAuthConfig = {
|
||||
token: "test-token",
|
||||
};
|
||||
|
||||
// Initialize the service (note: initialize calls doInitialize and sets the state)
|
||||
const initialState = await modelService.initialize(
|
||||
mockAssistant as any,
|
||||
mockAuthConfig as any,
|
||||
);
|
||||
|
||||
// Verify we have models and the first one is selected
|
||||
const availableModels = modelService.getAvailableChatModels();
|
||||
expect(availableModels.length).toBe(2);
|
||||
expect(initialState.model).toBeDefined();
|
||||
expect((initialState.model as any).name).toBe("GPT-4");
|
||||
|
||||
// Now switch should work
|
||||
await modelService.switchModel(1);
|
||||
expect(modelService.getCurrentModelIndex()).toBe(1);
|
||||
|
||||
const modelInfo = modelService.getModelInfo();
|
||||
expect(modelInfo?.name).toBe("GPT-3.5");
|
||||
});
|
||||
|
||||
it("should handle switching to invalid model index", async () => {
|
||||
// Initialize properly first
|
||||
const mockAssistant = {
|
||||
name: "Test Assistant",
|
||||
version: "1.0.0",
|
||||
models: [
|
||||
{
|
||||
name: "GPT-4",
|
||||
provider: "openai",
|
||||
model: "gpt-4",
|
||||
apiKey: "test-key",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const mockAuthConfig = {
|
||||
token: "test-token",
|
||||
};
|
||||
|
||||
await modelService.initialize(mockAssistant as any, mockAuthConfig as any);
|
||||
|
||||
// Try to switch to invalid index
|
||||
try {
|
||||
await modelService.switchModel(5); // Only have 1 model at index 0
|
||||
expect(true).toBe(false);
|
||||
} catch (error: any) {
|
||||
expect(error.message).toContain("Invalid model index");
|
||||
}
|
||||
});
|
||||
|
||||
it("should successfully switch model when service is properly initialized via container", async () => {
|
||||
// This test simulates the fix where we ensure service is initialized before switching
|
||||
const mockAssistant = {
|
||||
name: "Test Assistant",
|
||||
version: "1.0.0",
|
||||
models: [
|
||||
{
|
||||
name: "GPT-4",
|
||||
provider: "openai",
|
||||
model: "gpt-4",
|
||||
apiKey: "test-key-1",
|
||||
roles: ["chat"],
|
||||
},
|
||||
{
|
||||
name: "GPT-3.5",
|
||||
provider: "openai",
|
||||
model: "gpt-3.5-turbo",
|
||||
apiKey: "test-key-2",
|
||||
roles: ["chat"],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const mockAuthConfig = {
|
||||
token: "test-token",
|
||||
};
|
||||
|
||||
// Initialize the service properly through initialize method (which sets isInitialized)
|
||||
await modelService.initialize(mockAssistant as any, mockAuthConfig as any);
|
||||
|
||||
// Verify initialization
|
||||
expect(modelService.isReady()).toBe(true);
|
||||
expect(modelService.getCurrentModelIndex()).toBe(0);
|
||||
|
||||
// Now switch should work and return success
|
||||
const newState = await modelService.switchModel(1);
|
||||
|
||||
// Verify switch was successful
|
||||
expect(modelService.getCurrentModelIndex()).toBe(1);
|
||||
expect(newState.model).toBeDefined();
|
||||
expect((newState.model as any).name).toBe("GPT-3.5");
|
||||
|
||||
// Get model info to verify success message data
|
||||
const modelInfo = modelService.getModelInfo();
|
||||
expect(modelInfo).toEqual({
|
||||
provider: "openai",
|
||||
name: "GPT-3.5",
|
||||
});
|
||||
|
||||
// This is what the success message would use
|
||||
const successMessage = `Switched to model: ${modelInfo?.provider}/${modelInfo?.name}`;
|
||||
expect(successMessage).toBe("Switched to model: openai/GPT-3.5");
|
||||
});
|
||||
});
|
||||
|
|
@ -1,260 +0,0 @@
|
|||
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
||||
import { constructLlmApi, LLMConfig } from "@continuedev/openai-adapters";
|
||||
|
||||
import {
|
||||
AuthConfig,
|
||||
getAccessToken,
|
||||
getOrganizationId,
|
||||
getModelName,
|
||||
} from "../auth/workos.js";
|
||||
import { getLlmApi } from "../config.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { BaseService, ServiceWithDependencies } from "./BaseService.js";
|
||||
import { ModelServiceState } from "./types.js";
|
||||
|
||||
/**
|
||||
* Service for managing LLM and model state
|
||||
* Extends BaseService and implements ServiceWithDependencies
|
||||
*/
|
||||
export class ModelService
|
||||
extends BaseService<ModelServiceState>
|
||||
implements ServiceWithDependencies
|
||||
{
|
||||
private availableModels: ModelConfig[] = [];
|
||||
private assistant: AssistantUnrolled | null = null;
|
||||
private authConfig: AuthConfig | null = null;
|
||||
|
||||
constructor() {
|
||||
super("ModelService", {
|
||||
llmApi: null,
|
||||
model: null,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare dependencies on other services
|
||||
*/
|
||||
getDependencies(): string[] {
|
||||
return ["auth", "config"];
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the model service
|
||||
*/
|
||||
async doInitialize(
|
||||
assistant: AssistantUnrolled,
|
||||
authConfig: AuthConfig,
|
||||
): Promise<ModelServiceState> {
|
||||
this.assistant = assistant;
|
||||
this.authConfig = authConfig;
|
||||
this.availableModels = (assistant.models?.filter(
|
||||
(model) =>
|
||||
model && (model.roles?.includes("chat") || model.roles === undefined),
|
||||
) || []) as ModelConfig[];
|
||||
|
||||
// Check if we have a persisted model name and use it if valid
|
||||
const persistedModelName = getModelName(authConfig);
|
||||
if (persistedModelName) {
|
||||
const modelIndex = this.getModelIndexByName(persistedModelName);
|
||||
if (modelIndex === -1) {
|
||||
// Model name not found, use default model selection
|
||||
const [llmApi, model] = getLlmApi(assistant, authConfig);
|
||||
return {
|
||||
llmApi,
|
||||
model,
|
||||
};
|
||||
} else {
|
||||
// Use the persisted model
|
||||
const state = await this.switchModel(modelIndex);
|
||||
return state;
|
||||
}
|
||||
} else {
|
||||
// Use default model selection
|
||||
const [llmApi, model] = getLlmApi(assistant, authConfig);
|
||||
return {
|
||||
llmApi,
|
||||
model,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the model based on new config or auth changes
|
||||
*/
|
||||
async update(
|
||||
assistant: AssistantUnrolled,
|
||||
authConfig: AuthConfig,
|
||||
): Promise<ModelServiceState> {
|
||||
logger.debug("Updating ModelService");
|
||||
|
||||
try {
|
||||
this.assistant = assistant;
|
||||
this.authConfig = authConfig;
|
||||
this.availableModels = (assistant.models?.filter(
|
||||
(model) =>
|
||||
model && (model.roles?.includes("chat") || model.roles === undefined),
|
||||
) || []) as ModelConfig[];
|
||||
|
||||
const [llmApi, model] = getLlmApi(assistant, authConfig);
|
||||
|
||||
this.setState({
|
||||
llmApi,
|
||||
model,
|
||||
});
|
||||
|
||||
logger.debug("ModelService updated successfully", {
|
||||
modelProvider: model.provider,
|
||||
modelName: (model as any).name || "unnamed",
|
||||
availableModels: this.availableModels.length,
|
||||
});
|
||||
|
||||
return this.getState();
|
||||
} catch (error: any) {
|
||||
logger.error("Failed to update ModelService:", error);
|
||||
this.emit("error", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Override isReady to check for required state
|
||||
*/
|
||||
override isReady(): boolean {
|
||||
return (
|
||||
super.isReady() &&
|
||||
this.currentState.llmApi !== null &&
|
||||
this.currentState.model !== null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get model information for display
|
||||
*/
|
||||
getModelInfo(): { provider: string; name: string } | null {
|
||||
if (!this.currentState.model) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
provider: this.currentState.model.provider,
|
||||
name: (this.currentState.model as any).name || "unnamed",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of available chat models
|
||||
*/
|
||||
getAvailableChatModels(): Array<{
|
||||
provider: string;
|
||||
name: string;
|
||||
index: number;
|
||||
}> {
|
||||
return this.availableModels.map((model, index) => ({
|
||||
provider: model.provider,
|
||||
name: (model as any).name || (model as any).model || "unnamed",
|
||||
index,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch to a different chat model by index
|
||||
*/
|
||||
async switchModel(modelIndex: number): Promise<ModelServiceState> {
|
||||
if (!this.assistant || !this.authConfig) {
|
||||
throw new Error("ModelService not initialized");
|
||||
}
|
||||
|
||||
if (modelIndex < 0 || modelIndex >= this.availableModels.length) {
|
||||
throw new Error(
|
||||
`Invalid model index: ${modelIndex}. Available models: 0-${this.availableModels.length - 1}`,
|
||||
);
|
||||
}
|
||||
|
||||
const selectedModel = this.availableModels[modelIndex];
|
||||
logger.debug("Switching to model", {
|
||||
modelIndex,
|
||||
provider: selectedModel.provider,
|
||||
name: (selectedModel as any).name || "unnamed",
|
||||
});
|
||||
|
||||
try {
|
||||
const accessToken = getAccessToken(this.authConfig);
|
||||
const organizationId = getOrganizationId(this.authConfig);
|
||||
|
||||
const config: LLMConfig =
|
||||
selectedModel.provider === "continue-proxy"
|
||||
? {
|
||||
provider: selectedModel.provider,
|
||||
requestOptions: selectedModel.requestOptions,
|
||||
apiBase: selectedModel.apiBase,
|
||||
apiKey: accessToken ?? undefined,
|
||||
env: {
|
||||
apiKeyLocation: (selectedModel as any).apiKeyLocation,
|
||||
orgScopeId: organizationId,
|
||||
proxyUrl: undefined,
|
||||
},
|
||||
}
|
||||
: {
|
||||
provider: selectedModel.provider as any,
|
||||
apiKey: selectedModel.apiKey,
|
||||
apiBase: selectedModel.apiBase,
|
||||
requestOptions: selectedModel.requestOptions,
|
||||
env: selectedModel.env,
|
||||
};
|
||||
|
||||
const llmApi = constructLlmApi(config);
|
||||
|
||||
if (!llmApi) {
|
||||
throw new Error("Failed to initialize LLM with selected model");
|
||||
}
|
||||
|
||||
this.setState({
|
||||
llmApi,
|
||||
model: selectedModel,
|
||||
});
|
||||
|
||||
logger.debug("Model switched successfully", {
|
||||
modelProvider: selectedModel.provider,
|
||||
modelName: (selectedModel as any).name || "unnamed",
|
||||
});
|
||||
|
||||
return this.getState();
|
||||
} catch (error: any) {
|
||||
logger.error("Failed to switch model:", error);
|
||||
this.emit("error", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current model index
|
||||
*/
|
||||
getCurrentModelIndex(): number {
|
||||
if (!this.currentState.model) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return this.availableModels.findIndex(
|
||||
(model) =>
|
||||
model.provider === this.currentState.model?.provider &&
|
||||
(model as any).name === (this.currentState.model as any).name,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get model index by name and provider
|
||||
*/
|
||||
getModelIndexByName(modelName: string, provider?: string): number {
|
||||
return this.availableModels.findIndex((model) => {
|
||||
const name = (model as any).name || (model as any).model;
|
||||
const nameMatches = name === modelName;
|
||||
|
||||
if (provider) {
|
||||
return nameMatches && model.provider === provider;
|
||||
}
|
||||
|
||||
return nameMatches;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -74,6 +74,8 @@ describe("ModelService", () => {
|
|||
expect(state).toEqual({
|
||||
llmApi: mockLlmApi,
|
||||
model: mockAssistant.models![0],
|
||||
assistant: mockAssistant,
|
||||
authConfig: mockAuthConfig,
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -135,6 +137,8 @@ describe("ModelService", () => {
|
|||
expect(state).toEqual({
|
||||
llmApi: newLlmApi,
|
||||
model: newAssistant.models![0],
|
||||
assistant: newAssistant,
|
||||
authConfig: mockAuthConfig,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -157,6 +161,8 @@ describe("ModelService", () => {
|
|||
expect(state).toEqual({
|
||||
llmApi: newLlmApi,
|
||||
model: mockAssistant.models![1],
|
||||
assistant: mockAssistant,
|
||||
authConfig: mockAuthConfig,
|
||||
});
|
||||
expect(service.getState()).toEqual(state);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -29,6 +29,8 @@ export class ModelService
|
|||
super("ModelService", {
|
||||
llmApi: null,
|
||||
model: null,
|
||||
assistant: null,
|
||||
authConfig: null,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -46,6 +48,12 @@ export class ModelService
|
|||
assistant: AssistantUnrolled,
|
||||
authConfig: AuthConfig,
|
||||
): Promise<ModelServiceState> {
|
||||
logger.debug("ModelService.doInitialize called", {
|
||||
hasAssistant: !!assistant,
|
||||
hasAuthConfig: !!authConfig,
|
||||
assistantModelsCount: assistant?.models?.length || 0,
|
||||
});
|
||||
|
||||
this.assistant = assistant;
|
||||
this.authConfig = authConfig;
|
||||
this.availableModels = (assistant.models?.filter(
|
||||
|
|
@ -56,18 +64,67 @@ export class ModelService
|
|||
// Check if we have a persisted model name and use it if valid
|
||||
const persistedModelName = getModelName(authConfig);
|
||||
if (persistedModelName) {
|
||||
const modelIndex = this.getModelIndexByName(persistedModelName);
|
||||
// During initialization, we need to check against availableModels directly
|
||||
const modelIndex = this.availableModels.findIndex((model) => {
|
||||
const name = (model as any).name || (model as any).model;
|
||||
return name === persistedModelName;
|
||||
});
|
||||
if (modelIndex === -1) {
|
||||
// Model name not found, use default model selection
|
||||
const [llmApi, model] = getLlmApi(assistant, authConfig);
|
||||
return {
|
||||
llmApi,
|
||||
model,
|
||||
assistant,
|
||||
authConfig,
|
||||
};
|
||||
} else {
|
||||
// Use the persisted model
|
||||
const state = await this.switchModel(modelIndex);
|
||||
return state;
|
||||
// Use the persisted model - but we need to handle initialization specially
|
||||
// During init, currentState isn't set yet, so switchModel would fail
|
||||
// Instead, we'll manually switch here
|
||||
const selectedModel = this.availableModels[modelIndex];
|
||||
logger.debug("Using persisted model during initialization", {
|
||||
modelIndex,
|
||||
provider: selectedModel.provider,
|
||||
name: (selectedModel as any).name || "unnamed",
|
||||
});
|
||||
|
||||
const accessToken = getAccessToken(authConfig);
|
||||
const organizationId = getOrganizationId(authConfig);
|
||||
|
||||
const config: LLMConfig =
|
||||
selectedModel.provider === "continue-proxy"
|
||||
? {
|
||||
provider: selectedModel.provider,
|
||||
requestOptions: selectedModel.requestOptions,
|
||||
apiBase: selectedModel.apiBase,
|
||||
apiKey: accessToken ?? undefined,
|
||||
env: {
|
||||
apiKeyLocation: (selectedModel as any).apiKeyLocation,
|
||||
orgScopeId: organizationId,
|
||||
proxyUrl: undefined,
|
||||
},
|
||||
}
|
||||
: {
|
||||
provider: selectedModel.provider as any,
|
||||
apiKey: selectedModel.apiKey,
|
||||
apiBase: selectedModel.apiBase,
|
||||
requestOptions: selectedModel.requestOptions,
|
||||
env: selectedModel.env,
|
||||
};
|
||||
|
||||
const llmApi = constructLlmApi(config);
|
||||
|
||||
if (!llmApi) {
|
||||
throw new Error("Failed to initialize LLM with persisted model");
|
||||
}
|
||||
|
||||
return {
|
||||
llmApi,
|
||||
model: selectedModel,
|
||||
assistant,
|
||||
authConfig,
|
||||
};
|
||||
}
|
||||
} else {
|
||||
// Use default model selection
|
||||
|
|
@ -75,6 +132,8 @@ export class ModelService
|
|||
return {
|
||||
llmApi,
|
||||
model,
|
||||
assistant,
|
||||
authConfig,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -89,6 +148,7 @@ export class ModelService
|
|||
logger.debug("Updating ModelService");
|
||||
|
||||
try {
|
||||
// Update instance properties for backward compatibility
|
||||
this.assistant = assistant;
|
||||
this.authConfig = authConfig;
|
||||
this.availableModels = (assistant.models?.filter(
|
||||
|
|
@ -98,9 +158,12 @@ export class ModelService
|
|||
|
||||
const [llmApi, model] = getLlmApi(assistant, authConfig);
|
||||
|
||||
// Ensure state has all necessary data
|
||||
this.setState({
|
||||
llmApi,
|
||||
model,
|
||||
assistant,
|
||||
authConfig,
|
||||
});
|
||||
|
||||
logger.debug("ModelService updated successfully", {
|
||||
|
|
@ -150,7 +213,19 @@ export class ModelService
|
|||
name: string;
|
||||
index: number;
|
||||
}> {
|
||||
return this.availableModels.map((model, index) => ({
|
||||
// Get assistant from state to ensure we have the latest data
|
||||
const { assistant } = this.getState();
|
||||
if (!assistant || !assistant.models) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Filter for chat models
|
||||
const chatModels = (assistant.models.filter(
|
||||
(model) =>
|
||||
model && (model.roles?.includes("chat") || model.roles === undefined),
|
||||
) || []) as ModelConfig[];
|
||||
|
||||
return chatModels.map((model, index) => ({
|
||||
provider: model.provider,
|
||||
name: (model as any).name || (model as any).model || "unnamed",
|
||||
index,
|
||||
|
|
@ -161,17 +236,51 @@ export class ModelService
|
|||
* Switch to a different chat model by index
|
||||
*/
|
||||
async switchModel(modelIndex: number): Promise<ModelServiceState> {
|
||||
if (!this.assistant || !this.authConfig) {
|
||||
throw new Error("ModelService not initialized");
|
||||
// Get assistant and authConfig from state, but fall back to instance properties
|
||||
// This is needed during initialization when state isn't set yet
|
||||
const stateValues = this.getState();
|
||||
const assistant = stateValues.assistant || this.assistant;
|
||||
const authConfig = stateValues.authConfig || this.authConfig;
|
||||
|
||||
// Debug logging to understand the state
|
||||
logger.debug("switchModel: Checking state", {
|
||||
hasStateAssistant: !!stateValues.assistant,
|
||||
hasStateAuthConfig: !!stateValues.authConfig,
|
||||
hasInstanceAssistant: !!this.assistant,
|
||||
hasInstanceAuthConfig: !!this.authConfig,
|
||||
isInitialized: this.isReady(),
|
||||
isReady: this.isReady(),
|
||||
modelIndex,
|
||||
});
|
||||
|
||||
if (!assistant) {
|
||||
logger.error("switchModel: Missing assistant data", {
|
||||
assistant: !!assistant,
|
||||
authConfig: !!authConfig,
|
||||
stateKeys: Object.keys(stateValues),
|
||||
currentState: {
|
||||
hasLlmApi: !!stateValues.llmApi,
|
||||
hasModel: !!stateValues.model,
|
||||
hasAssistant: !!stateValues.assistant,
|
||||
hasAuthConfig: !!stateValues.authConfig,
|
||||
},
|
||||
});
|
||||
throw new Error("ModelService not initialized - assistant data missing");
|
||||
}
|
||||
|
||||
if (modelIndex < 0 || modelIndex >= this.availableModels.length) {
|
||||
// Get available models from assistant in state
|
||||
const availableModels = (assistant.models?.filter(
|
||||
(model) =>
|
||||
model && (model.roles?.includes("chat") || model.roles === undefined),
|
||||
) || []) as ModelConfig[];
|
||||
|
||||
if (modelIndex < 0 || modelIndex >= availableModels.length) {
|
||||
throw new Error(
|
||||
`Invalid model index: ${modelIndex}. Available models: 0-${this.availableModels.length - 1}`,
|
||||
`Invalid model index: ${modelIndex}. Available models: 0-${availableModels.length - 1}`,
|
||||
);
|
||||
}
|
||||
|
||||
const selectedModel = this.availableModels[modelIndex];
|
||||
const selectedModel = availableModels[modelIndex];
|
||||
logger.debug("Switching to model", {
|
||||
modelIndex,
|
||||
provider: selectedModel.provider,
|
||||
|
|
@ -179,8 +288,8 @@ export class ModelService
|
|||
});
|
||||
|
||||
try {
|
||||
const accessToken = getAccessToken(this.authConfig);
|
||||
const organizationId = getOrganizationId(this.authConfig);
|
||||
const accessToken = getAccessToken(authConfig);
|
||||
const organizationId = getOrganizationId(authConfig);
|
||||
|
||||
const config: LLMConfig =
|
||||
selectedModel.provider === "continue-proxy"
|
||||
|
|
@ -212,6 +321,8 @@ export class ModelService
|
|||
this.setState({
|
||||
llmApi,
|
||||
model: selectedModel,
|
||||
assistant,
|
||||
authConfig,
|
||||
});
|
||||
|
||||
logger.debug("Model switched successfully", {
|
||||
|
|
@ -231,14 +342,21 @@ export class ModelService
|
|||
* Get current model index
|
||||
*/
|
||||
getCurrentModelIndex(): number {
|
||||
if (!this.currentState.model) {
|
||||
const state = this.getState();
|
||||
if (!state.model || !state.assistant) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return this.availableModels.findIndex(
|
||||
// Get available models from state
|
||||
const availableModels = (state.assistant.models?.filter(
|
||||
(model) =>
|
||||
model.provider === this.currentState.model?.provider &&
|
||||
(model as any).name === (this.currentState.model as any).name,
|
||||
model && (model.roles?.includes("chat") || model.roles === undefined),
|
||||
) || []) as ModelConfig[];
|
||||
|
||||
return availableModels.findIndex(
|
||||
(model) =>
|
||||
model.provider === state.model?.provider &&
|
||||
(model as any).name === (state.model as any).name,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -246,7 +364,18 @@ export class ModelService
|
|||
* Get model index by name and provider
|
||||
*/
|
||||
getModelIndexByName(modelName: string, provider?: string): number {
|
||||
return this.availableModels.findIndex((model) => {
|
||||
const state = this.getState();
|
||||
if (!state.assistant) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Get available models from state
|
||||
const availableModels = (state.assistant.models?.filter(
|
||||
(model) =>
|
||||
model && (model.roles?.includes("chat") || model.roles === undefined),
|
||||
) || []) as ModelConfig[];
|
||||
|
||||
return availableModels.findIndex((model) => {
|
||||
const name = (model as any).name || (model as any).model;
|
||||
const nameMatches = name === modelName;
|
||||
|
||||
|
|
|
|||
|
|
@ -52,6 +52,8 @@ export interface ConfigServiceState {
|
|||
export interface ModelServiceState {
|
||||
llmApi: BaseLlmApi | null;
|
||||
model: ModelConfig | null;
|
||||
assistant: AssistantUnrolled | null;
|
||||
authConfig: AuthConfig | null;
|
||||
}
|
||||
|
||||
export type MCPServerStatus = "idle" | "connecting" | "connected" | "error";
|
||||
|
|
|
|||
|
|
@ -51,14 +51,14 @@ describe("IntroMessage", () => {
|
|||
|
||||
// Count occurrences of "nate/spanish" in the output
|
||||
const matches = output?.match(/nate\/spanish/g) || [];
|
||||
|
||||
|
||||
// Should appear exactly once, not twice
|
||||
expect(matches.length).toBe(1);
|
||||
|
||||
|
||||
// Verify the slug is shown, not the content
|
||||
expect(output).toContain("nate/spanish");
|
||||
expect(output).not.toContain("Always respond in Spanish");
|
||||
|
||||
|
||||
// Verify plain string rule is shown as-is
|
||||
expect(output).toContain("Always be helpful");
|
||||
});
|
||||
|
|
@ -66,11 +66,7 @@ describe("IntroMessage", () => {
|
|||
it("should display rules from config correctly", () => {
|
||||
const config: AssistantUnrolled = {
|
||||
name: "Test Assistant",
|
||||
rules: [
|
||||
"Rule 1",
|
||||
{ name: "Rule 2" },
|
||||
"Rule 3",
|
||||
],
|
||||
rules: ["Rule 1", { name: "Rule 2" }, "Rule 3"],
|
||||
} as any;
|
||||
|
||||
const { lastFrame } = render(
|
||||
|
|
@ -134,15 +130,15 @@ describe("IntroMessage", () => {
|
|||
const config: AssistantUnrolled = {
|
||||
name: "Test Assistant",
|
||||
rules: [
|
||||
{
|
||||
name: "org/complex-rule",
|
||||
{
|
||||
name: "org/complex-rule",
|
||||
rule: `---
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
This is a very long rule content that should not be displayed.
|
||||
It contains multiple lines and complex formatting.
|
||||
The UI should only show the slug 'org/complex-rule'.`
|
||||
The UI should only show the slug 'org/complex-rule'.`,
|
||||
},
|
||||
{ name: "another/rule", rule: "Short content" },
|
||||
],
|
||||
|
|
@ -161,10 +157,10 @@ The UI should only show the slug 'org/complex-rule'.`
|
|||
// Should show slugs only
|
||||
expect(output).toContain("org/complex-rule");
|
||||
expect(output).toContain("another/rule");
|
||||
|
||||
|
||||
// Should NOT show the rule content
|
||||
expect(output).not.toContain("This is a very long rule");
|
||||
expect(output).not.toContain("alwaysApply");
|
||||
expect(output).not.toContain("Short content");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
18
extensions/cli/test-fixtures/model-switch-test-config.yaml
Normal file
18
extensions/cli/test-fixtures/model-switch-test-config.yaml
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
name: Model Switch Test Config
|
||||
version: 1.0.0
|
||||
|
||||
models:
|
||||
- name: GPT-4
|
||||
provider: openai
|
||||
model: gpt-4
|
||||
apiKey: test-api-key-1
|
||||
|
||||
- name: GPT-3.5
|
||||
provider: openai
|
||||
model: gpt-3.5-turbo
|
||||
apiKey: test-api-key-2
|
||||
|
||||
- name: Claude 3
|
||||
provider: anthropic
|
||||
model: claude-3-opus
|
||||
apiKey: test-api-key-3
|
||||
2
package-lock.json
generated
2
package-lock.json
generated
|
|
@ -1,5 +1,5 @@
|
|||
{
|
||||
"name": "wt-nate-4",
|
||||
"name": "wt-mcp-flag",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue