fix: multiple cn nitpicks (#8049)

* fix: refresh ui on model change

* feat: handle cmd+backspace as only single line

* fix: model selection persistence

* fx: test

* fix: tests

* fix: tests
This commit is contained in:
Nate Sesti 2025-10-01 00:06:15 -07:00 • committed by GitHub
parent a1d1fc599f
commit 9cb27661b1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 979 additions and 28 deletions

View file

@ -30,6 +30,7 @@ export type GlobalContextType = {
selectedModelsByProfileId: {
[profileId: string]: GlobalContextModelSelections;
};
cliSelectedModel?: string; // CLI-specific model selection for unauthenticated users
/**
* This is needed to handle the case where a JetBrains user has created

View file

@ -8,6 +8,7 @@ import nodeFetch from "node-fetch";
import open from "open";
import { getApiClient } from "../config.js";
// eslint-disable-next-line import/order
import { env } from "../env.js";
if (!globalThis.fetch) {
globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch;
@ -96,13 +97,24 @@ export function getConfigUri(config: AuthConfig): string | null {
/**
* Gets the model name from any auth config type
* For unauthenticated users or when auth config has no modelName, checks GlobalContext
*/
export function getModelName(config: AuthConfig): string | null {
if (config === null) return null;
return config.modelName || null;
// Priority 1: Logged-in users with modelName in auth config
if (config !== null && config.modelName) {
return config.modelName;
}
// Priority 2: Fall back to GlobalContext (for logged-out users or logged-in without modelName)
return getPersistedModelName();
}
// URI utility functions have been moved to ./uriUtils.ts
import {
getPersistedModelName,
persistModelName,
} from "../util/modelPersistence.js";
import { autoSelectOrganizationAndConfig } from "./orgSelection.js";
import { pathToUri, slugToUri, uriToPath, uriToSlug } from "./uriUtils.js";
import {
@ -214,21 +226,30 @@ export function updateConfigUri(configUri: string | null): void {
/**
* Updates the model name in the authentication configuration
* Returns the updated config so the caller can update in-memory state
* For unauthenticated users, saves to GlobalContext
*/
export function updateModelName(modelName: string | null): void {
export function updateModelName(modelName: string | null): AuthConfig {
// If using CONTINUE_API_KEY environment variable, don't save anything
if (process.env.CONTINUE_API_KEY) {
return;
return loadAuthConfig();
}
const config = loadAuthConfig();
// If logged in, save to auth.json
if (config && isAuthenticatedConfig(config)) {
const updatedConfig: AuthenticatedConfig = {
...config,
modelName: modelName || undefined,
};
saveAuthConfig(updatedConfig);
return updatedConfig;
}
// If logged out, save to GlobalContext
persistModelName(modelName);
return config;
}
/**

View file

@ -115,7 +115,7 @@ models:
if (configExists) {
const configContent = await fs.readFile(configPath, "utf-8");
expect(configContent).toContain("anthropic/claude-4-sonnet");
expect(configContent).toContain("anthropic/claude-sonnet-4-5");
expect(configContent).toContain(
"ANTHROPIC_API_KEY: TEST-test-invalid-key-format",
);

View file

@ -0,0 +1,205 @@
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import {
AuthenticatedConfig,
getModelName,
loadAuthConfig,
saveAuthConfig,
updateModelName,
} from "../auth/workos.js";
import * as config from "../config.js";
import { ModelService } from "../services/ModelService.js";
import { persistModelName } from "../util/modelPersistence.js";
// Mock the config module
vi.mock("../config.js");
describe("Model Persistence End-to-End", () => {
let testDir: string;
let originalContinueHome: string | undefined;
let mockAssistant: AssistantUnrolled;
let mockAuthConfig: AuthenticatedConfig;
const mockLlmApi = { complete: vi.fn(), stream: vi.fn() };
beforeEach(() => {
vi.clearAllMocks();
// Create a temporary directory for testing
testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-"));
originalContinueHome = process.env.CONTINUE_GLOBAL_DIR;
process.env.CONTINUE_GLOBAL_DIR = testDir;
// Clear GlobalContext for clean test state
persistModelName(null);
mockAssistant = {
name: "test-assistant",
version: "1.0.0",
models: [
{
provider: "openai",
model: "gpt-4",
name: "GPT-4",
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
{
provider: "anthropic",
model: "claude-3-5-sonnet-20241022",
name: "Claude 3.5 Sonnet",
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
{
provider: "anthropic",
model: "claude-3-opus-20240229",
name: "Claude 3 Opus",
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
],
} as AssistantUnrolled;
mockAuthConfig = {
userId: "test-user",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh",
expiresAt: Date.now() + 3600000, // 1 hour from now
organizationId: "test-org",
};
// Setup default mock behavior
vi.mocked(config.getLlmApi).mockReturnValue([
mockLlmApi as any,
mockAssistant.models![0] as ModelConfig,
]);
vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any);
});
afterEach(() => {
// Cleanup
if (fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true });
}
if (originalContinueHome) {
process.env.CONTINUE_GLOBAL_DIR = originalContinueHome;
} else {
delete process.env.CONTINUE_GLOBAL_DIR;
}
});
test("should restore model selection after restart", async () => {
// Step 1: Initial session - user starts with default model (GPT-4)
saveAuthConfig(mockAuthConfig);
let service = new ModelService();
let state = await service.initialize(mockAssistant, mockAuthConfig);
console.log("Initial model:", state.model?.name);
expect(state.model?.name).toBe("GPT-4");
// Step 2: User switches to Claude 3.5 Sonnet (index 1)
await service.switchModel(1);
state = service.getState();
console.log("After switch:", state.model?.name);
expect(state.model?.name).toBe("Claude 3.5 Sonnet");
// Step 3: Persist the model choice (this should happen in useModelSelector)
updateModelName("Claude 3.5 Sonnet");
// Verify it was saved to auth.json
const savedConfig = loadAuthConfig();
console.log("Saved model name:", getModelName(savedConfig));
expect(getModelName(savedConfig)).toBe("Claude 3.5 Sonnet");
// Step 4: Simulate restart - create new service instance
// Load fresh auth config from disk (this is what the real code does)
const freshAuthConfig = loadAuthConfig();
console.log("Fresh auth config model name:", getModelName(freshAuthConfig));
service = new ModelService();
state = await service.initialize(mockAssistant, freshAuthConfig);
// Step 5: Verify the persisted model is restored
console.log("After restart:", state.model?.name);
expect(state.model?.name).toBe("Claude 3.5 Sonnet");
expect(state.model?.provider).toBe("anthropic");
});
test("should handle model name mismatch gracefully", async () => {
// Save auth config with a model that doesn't exist
mockAuthConfig.modelName = "Non-existent Model";
saveAuthConfig(mockAuthConfig);
const service = new ModelService();
const state = await service.initialize(mockAssistant, mockAuthConfig);
// Should fall back to first available model (GPT-4)
expect(state.model?.name).toBe("GPT-4");
});
test("should check both name and model fields when matching", async () => {
// Some configs might have model field instead of name
const assistantWithModelField = {
...mockAssistant,
models: [
{
provider: "openai",
model: "gpt-4",
// No name field, just model
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
{
provider: "anthropic",
model: "claude-3-5-sonnet-20241022",
// No name field, just model
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
],
} as AssistantUnrolled;
mockAuthConfig.modelName = "claude-3-5-sonnet-20241022";
saveAuthConfig(mockAuthConfig);
const service = new ModelService();
const state = await service.initialize(
assistantWithModelField,
mockAuthConfig,
);
// Should match by model field
expect(state.model?.model).toBe("claude-3-5-sonnet-20241022");
});
test("should persist model through multiple switches", async () => {
saveAuthConfig(mockAuthConfig);
const service = new ModelService();
await service.initialize(mockAssistant, mockAuthConfig);
// Switch to Claude 3.5 Sonnet
await service.switchModel(1);
updateModelName("Claude 3.5 Sonnet");
expect(getModelName(loadAuthConfig())).toBe("Claude 3.5 Sonnet");
// Switch to Claude 3 Opus
await service.switchModel(2);
updateModelName("Claude 3 Opus");
expect(getModelName(loadAuthConfig())).toBe("Claude 3 Opus");
// Restart and verify last selection
const freshAuthConfig = loadAuthConfig();
console.log("Fresh auth config model name:", getModelName(freshAuthConfig));
const newService = new ModelService();
const state = await newService.initialize(mockAssistant, freshAuthConfig);
expect(state.model?.name).toBe("Claude 3 Opus");
});
});

View file

@ -0,0 +1,245 @@
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import {
getModelName,
loadAuthConfig,
updateModelName,
} from "../auth/workos.js";
import * as config from "../config.js";
import { ModelService } from "../services/ModelService.js";
import {
getPersistedModelName,
persistModelName,
} from "../util/modelPersistence.js";
// Mock the config module
vi.mock("../config.js");
describe("Model Persistence for Unauthenticated Users", () => {
let testDir: string;
let originalContinueHome: string | undefined;
let mockAssistant: AssistantUnrolled;
const mockLlmApi = { complete: vi.fn(), stream: vi.fn() };
beforeEach(() => {
vi.clearAllMocks();
// Create a temporary directory for testing
testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-"));
originalContinueHome = process.env.CONTINUE_GLOBAL_DIR;
process.env.CONTINUE_GLOBAL_DIR = testDir;
// Clear GlobalContext for clean test state
persistModelName(null);
mockAssistant = {
name: "test-assistant",
version: "1.0.0",
models: [
{
provider: "openai",
model: "gpt-4",
name: "GPT-4",
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
{
provider: "anthropic",
model: "claude-3-5-sonnet-20241022",
name: "Claude 3.5 Sonnet",
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
{
provider: "anthropic",
model: "claude-3-opus-20240229",
name: "Claude 3 Opus",
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
],
} as AssistantUnrolled;
// Setup default mock behavior
vi.mocked(config.getLlmApi).mockReturnValue([
mockLlmApi as any,
mockAssistant.models![0] as ModelConfig,
]);
vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any);
});
afterEach(() => {
// Cleanup
if (fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true });
}
if (originalContinueHome) {
process.env.CONTINUE_GLOBAL_DIR = originalContinueHome;
} else {
delete process.env.CONTINUE_GLOBAL_DIR;
}
});
test("should persist model selection for logged-out users", () => {
// User is logged out (no auth config)
const authConfig = loadAuthConfig();
expect(authConfig).toBeNull();
// User switches model
updateModelName("Claude 3.5 Sonnet");
// Verify it was saved to GlobalContext
const persistedModel = getPersistedModelName();
expect(persistedModel).toBe("Claude 3.5 Sonnet");
// Verify getModelName returns it for null config
expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
});
test("should restore model selection on next session for logged-out users", async () => {
// Session 1: User is logged out and switches model
const authConfig = loadAuthConfig();
expect(authConfig).toBeNull();
const modelService = new ModelService();
await modelService.initialize(mockAssistant, authConfig);
await modelService.switchModel(1);
updateModelName("Claude 3.5 Sonnet");
// Session 2: User reopens CLI (still logged out)
const newAuthConfig = loadAuthConfig();
expect(newAuthConfig).toBeNull();
const newModelService = new ModelService();
const state = await newModelService.initialize(
mockAssistant,
newAuthConfig,
);
// Should restore Claude 3.5 Sonnet
expect(state.model?.name).toBe("Claude 3.5 Sonnet");
});
test("should handle multiple model switches for logged-out users", () => {
updateModelName("GPT-4");
expect(getModelName(null)).toBe("GPT-4");
updateModelName("Claude 3.5 Sonnet");
expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
updateModelName("Claude 3 Opus");
expect(getModelName(null)).toBe("Claude 3 Opus");
});
test("should clear model selection when set to null", () => {
updateModelName("Claude 3.5 Sonnet");
expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
updateModelName(null);
expect(getModelName(null)).toBeNull();
});
test("should preserve GlobalContext model when user logs in", () => {
// User is logged out with a persisted model
updateModelName("Claude 3.5 Sonnet");
expect(getPersistedModelName()).toBe("Claude 3.5 Sonnet");
// User logs in (simulated by having auth.json)
const authPath = path.join(testDir, "auth.json");
fs.writeFileSync(
authPath,
JSON.stringify({
userId: "test-user",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh",
expiresAt: Date.now() + 3600000,
organizationId: "test-org",
}),
);
const authConfig = loadAuthConfig();
expect(authConfig).not.toBeNull();
// GlobalContext model should still exist
expect(getPersistedModelName()).toBe("Claude 3.5 Sonnet");
// When auth config has no modelName, it should fall back to GlobalContext
expect(getModelName(authConfig)).toBe("Claude 3.5 Sonnet");
});
test("should use auth config model when both exist", () => {
// Clear previous state
updateModelName(null);
// Set GlobalContext model
updateModelName("GPT-4");
expect(getPersistedModelName()).toBe("GPT-4");
// Create auth config with different model
const authPath = path.join(testDir, "auth.json");
fs.writeFileSync(
authPath,
JSON.stringify({
userId: "test-user",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh",
expiresAt: Date.now() + 3600000,
organizationId: "test-org",
modelName: "Claude 3.5 Sonnet",
}),
);
const authConfig = loadAuthConfig();
// Auth config should take precedence
expect(getModelName(authConfig)).toBe("Claude 3.5 Sonnet");
});
test("should not save to GlobalContext when using CONTINUE_API_KEY", () => {
// Clear any existing model
updateModelName(null);
expect(getPersistedModelName()).toBeNull();
// Capture original value to restore after test
const originalApiKey = process.env.CONTINUE_API_KEY;
process.env.CONTINUE_API_KEY = "test-api-key";
updateModelName("Claude 3.5 Sonnet");
// Should not be saved to GlobalContext
expect(getPersistedModelName()).toBeNull();
// Restore original value
if (originalApiKey === undefined) {
delete process.env.CONTINUE_API_KEY;
} else {
process.env.CONTINUE_API_KEY = originalApiKey;
}
});
test("should work across config changes for logged-out users", async () => {
// User switches model with one config
updateModelName("Claude 3.5 Sonnet");
const modelService = new ModelService();
let state = await modelService.initialize(mockAssistant, null);
expect(state.model?.name).toBe("Claude 3.5 Sonnet");
// User switches to a different model
await modelService.switchModel(2);
updateModelName("Claude 3 Opus");
// Create new service (simulating restart)
const newModelService = new ModelService();
state = await newModelService.initialize(mockAssistant, null);
expect(state.model?.name).toBe("Claude 3 Opus");
});
});

View file

@ -0,0 +1,153 @@
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import {
AuthenticatedConfig,
getModelName,
loadAuthConfig,
saveAuthConfig,
} from "../auth/workos.js";
import * as config from "../config.js";
import { AuthService } from "../services/AuthService.js";
import { ModelService } from "../services/ModelService.js";
// Mock the config module
vi.mock("../config.js");
describe("Model Persistence User Flow", () => {
let testDir: string;
let originalContinueHome: string | undefined;
let mockAssistant: AssistantUnrolled;
let mockAuthConfig: AuthenticatedConfig;
const mockLlmApi = { complete: vi.fn(), stream: vi.fn() };
beforeEach(() => {
vi.clearAllMocks();
// Create a temporary directory for testing
testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-"));
originalContinueHome = process.env.CONTINUE_GLOBAL_DIR;
process.env.CONTINUE_GLOBAL_DIR = testDir;
mockAssistant = {
name: "test-assistant",
version: "1.0.0",
models: [
{
provider: "openai",
model: "gpt-4",
name: "GPT-4",
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
{
provider: "anthropic",
model: "claude-3-5-sonnet-20241022",
name: "Claude 3.5 Sonnet",
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
{
provider: "anthropic",
model: "claude-3-opus-20240229",
name: "Claude 3 Opus",
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
],
} as AssistantUnrolled;
mockAuthConfig = {
userId: "test-user",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh",
expiresAt: Date.now() + 3600000, // 1 hour from now
organizationId: "test-org",
};
// Setup default mock behavior
vi.mocked(config.getLlmApi).mockReturnValue([
mockLlmApi as any,
mockAssistant.models![0] as ModelConfig,
]);
vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any);
});
afterEach(() => {
// Cleanup
if (fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true });
}
if (originalContinueHome) {
process.env.CONTINUE_GLOBAL_DIR = originalContinueHome;
} else {
delete process.env.CONTINUE_GLOBAL_DIR;
}
});
test("should persist model choice exactly as user experiences it", async () => {
console.log("\n=== SESSION 1: User opens cn and switches model ===");
// Session 1: User starts CLI
// Save initial auth config (what happens after login)
saveAuthConfig(mockAuthConfig);
console.log("1. Initial auth.json saved");
// Initialize ModelService (what happens on CLI start)
const modelService = new ModelService();
const state = await modelService.initialize(mockAssistant, mockAuthConfig);
console.log("2. Initial model:", state.model?.name);
expect(state.model?.name).toBe("GPT-4");
// User switches to Claude 3.5 Sonnet via UI
await modelService.switchModel(1);
const modelInfo = modelService.getModelInfo();
console.log("3. User switched to:", modelInfo?.name);
expect(modelInfo?.name).toBe("Claude 3.5 Sonnet");
// useModelSelector calls updateModelName
const { updateModelName } = await import("../auth/workos.js");
const updatedAuthConfig = updateModelName("Claude 3.5 Sonnet");
console.log("4. Model name persisted to disk");
// Verify it was saved
const savedConfig = loadAuthConfig();
console.log("5. Read back from disk:", getModelName(savedConfig));
expect(getModelName(savedConfig)).toBe("Claude 3.5 Sonnet");
// User closes CLI
console.log("6. User exits CLI\n");
console.log("=== SESSION 2: User reopens cn ===");
// Session 2: User restarts CLI
// Initialize AuthService (loads from disk)
const authService = new AuthService();
const authState = await authService.initialize();
console.log(
"7. AuthService loaded, modelName in auth:",
getModelName(authState.authConfig),
);
// Initialize ModelService with fresh auth state
const newModelService = new ModelService();
const newState = await newModelService.initialize(
mockAssistant,
authState.authConfig,
);
console.log(
"8. ModelService initialized with model:",
newState.model?.name,
);
// EXPECTATION: Should restore Claude 3.5 Sonnet
expect(newState.model?.name).toBe("Claude 3.5 Sonnet");
expect(newState.model?.provider).toBe("anthropic");
console.log("✅ Model persisted correctly!\n");
});
});

View file

@ -0,0 +1,194 @@
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import {
AuthenticatedConfig,
getModelName,
loadAuthConfig,
saveAuthConfig,
updateModelName,
} from "../auth/workos.js";
import { persistModelName } from "../util/modelPersistence.js";
describe("Model Persistence Integration", () => {
let testDir: string;
let originalContinueHome: string | undefined;
beforeEach(() => {
// Create a temporary directory for testing
testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-"));
originalContinueHome = process.env.CONTINUE_GLOBAL_DIR;
process.env.CONTINUE_GLOBAL_DIR = testDir;
// Clear GlobalContext for clean test state
persistModelName(null);
});
afterEach(() => {
// Cleanup
if (fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true });
}
if (originalContinueHome) {
process.env.CONTINUE_GLOBAL_DIR = originalContinueHome;
} else {
delete process.env.CONTINUE_GLOBAL_DIR;
}
});
test("should persist model name when user selects a model", () => {
// Create initial auth config without model name
const authConfig: AuthenticatedConfig = {
userId: "test-user",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh",
expiresAt: Date.now() + 3600000,
organizationId: "test-org",
};
saveAuthConfig(authConfig);
// User selects a model
updateModelName("Claude 3.5 Sonnet");
// Load config and verify model name is persisted
const loadedConfig = loadAuthConfig();
expect(getModelName(loadedConfig)).toBe("Claude 3.5 Sonnet");
});
test("should update model name when user switches models", () => {
// Create initial auth config with a model
const authConfig: AuthenticatedConfig = {
userId: "test-user",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh",
expiresAt: Date.now() + 3600000,
organizationId: "test-org",
modelName: "GPT-4",
};
saveAuthConfig(authConfig);
// User switches to a different model
updateModelName("Claude 3.5 Sonnet");
// Load config and verify new model name
const loadedConfig = loadAuthConfig();
expect(getModelName(loadedConfig)).toBe("Claude 3.5 Sonnet");
});
test("should preserve other auth config fields when updating model", () => {
// Create initial auth config
const authConfig: AuthenticatedConfig = {
userId: "test-user",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh",
expiresAt: Date.now() + 3600000,
organizationId: "test-org",
configUri: "slug://owner/my-config",
};
saveAuthConfig(authConfig);
// Update model name
updateModelName("Claude 3.5 Sonnet");
// Load config and verify all fields are preserved
const loadedConfig = loadAuthConfig();
expect(loadedConfig).toMatchObject({
userId: "test-user",
userEmail: "test@example.com",
organizationId: "test-org",
configUri: "slug://owner/my-config",
modelName: "Claude 3.5 Sonnet",
});
});
test("should clear model name when set to null", () => {
// Create initial auth config with a model
const authConfig: AuthenticatedConfig = {
userId: "test-user",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh",
expiresAt: Date.now() + 3600000,
organizationId: "test-org",
modelName: "GPT-4",
};
saveAuthConfig(authConfig);
// Clear model name
updateModelName(null);
// Load config and verify model name is cleared
const loadedConfig = loadAuthConfig();
expect(getModelName(loadedConfig)).toBeNull();
});
test("should return null for model name when not authenticated and no GlobalContext", () => {
// No auth config exists and no GlobalContext model
persistModelName(null); // Ensure GlobalContext is clear
const loadedConfig = loadAuthConfig();
expect(getModelName(loadedConfig)).toBeNull();
});
test("should not persist model name when using CONTINUE_API_KEY", () => {
// Clear GlobalContext first
persistModelName(null);
// Capture original value to restore after test
const originalApiKey = process.env.CONTINUE_API_KEY;
// Set environment variable
process.env.CONTINUE_API_KEY = "test-api-key";
// Try to update model name
updateModelName("Claude 3.5 Sonnet");
// Load config - should be environment auth config without model name
const loadedConfig = loadAuthConfig();
expect(getModelName(loadedConfig)).toBeNull();
// Restore original value
if (originalApiKey === undefined) {
delete process.env.CONTINUE_API_KEY;
} else {
process.env.CONTINUE_API_KEY = originalApiKey;
}
});
test("should persist model name in auth.json file with correct format", () => {
// Create and save auth config
const authConfig: AuthenticatedConfig = {
userId: "test-user",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh",
expiresAt: Date.now() + 3600000,
organizationId: "test-org",
};
saveAuthConfig(authConfig);
updateModelName("Claude 3.5 Sonnet");
// Read the raw file content
const authPath = path.join(testDir, "auth.json");
const rawContent = fs.readFileSync(authPath, "utf8");
const parsedContent = JSON.parse(rawContent);
// Verify the file structure
expect(parsedContent).toHaveProperty("userId", "test-user");
expect(parsedContent).toHaveProperty("userEmail", "test@example.com");
expect(parsedContent).toHaveProperty("organizationId", "test-org");
expect(parsedContent).toHaveProperty("modelName", "Claude 3.5 Sonnet");
// Verify it's pretty-printed (has indentation)
expect(rawContent).toContain("\n ");
});
});

View file

@ -264,6 +264,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
configPath,
setChatHistory,
handleClear,
setStaticRefreshTrigger,
);
// Session selection handler

View file

@ -611,6 +611,30 @@ describe("TextBuffer", () => {
expect(buffer.cursor).toBe(2);
});
it("should limit ctrl+u deletion to current line", () => {
const text = "first line\nsecond line\nthird";
buffer.setText(text);
buffer.setCursor(text.indexOf("second line") + "second line".length);
const result = buffer.handleInput("u", { ctrl: true } as any);
expect(result).toBe(true);
expect(buffer.text).toBe("first line\n\nthird");
expect(buffer.cursor).toBe("first line\n".length);
});
it("should limit ctrl+k deletion to current line", () => {
const text = "first line\nsecond line\nthird";
buffer.setText(text);
buffer.setCursor(text.indexOf("second line"));
const result = buffer.handleInput("k", { ctrl: true } as any);
expect(result).toBe(true);
expect(buffer.text).toBe("first line\n\nthird");
expect(buffer.cursor).toBe(text.indexOf("second line"));
});
it("should handle arrow keys", () => {
let result = buffer.handleInput("", { leftArrow: true } as any);
expect(result).toBe(true);
@ -644,6 +668,38 @@ describe("TextBuffer", () => {
expect(buffer.cursor).toBe(0);
});
it("should delete to start of line with meta+backspace", () => {
const text = "first line\nsecond line\nthird line";
buffer.setText(text);
const cursorPosition = text.indexOf("second line") + "second line".length;
buffer.setCursor(cursorPosition);
const result = buffer.handleInput("", {
meta: true,
backspace: true,
} as any);
expect(result).toBe(true);
expect(buffer.text).toBe("first line\n\nthird line");
expect(buffer.cursor).toBe("first line\n".length);
});
it("should delete to end of line with meta+delete", () => {
const text = "first line\nsecond line\nthird line";
buffer.setText(text);
const cursorPosition = text.indexOf("second line");
buffer.setCursor(cursorPosition);
const result = buffer.handleInput("", {
meta: true,
delete: true,
} as any);
expect(result).toBe(true);
expect(buffer.text).toBe("first line\n\nthird line");
expect(buffer.cursor).toBe(cursorPosition);
});
it("should handle option key sequences", () => {
const result = buffer.handleInput("\u001b\u007f", {} as any);
expect(result).toBe(true);

View file

@ -137,6 +137,38 @@ export class TextBuffer {
}
}
private deleteLineBackward(): void {
if (this._cursor === 0) {
return;
}
const lastNewline = this._text.lastIndexOf("\n", this._cursor - 1);
const lineStart = lastNewline === -1 ? 0 : lastNewline + 1;
if (lineStart === this._cursor) {
return;
}
this._text =
this._text.slice(0, lineStart) + this._text.slice(this._cursor);
this._cursor = lineStart;
}
private deleteLineForward(): void {
if (this._cursor >= this._text.length) {
return;
}
const nextNewline = this._text.indexOf("\n", this._cursor);
const lineEnd = nextNewline === -1 ? this._text.length : nextNewline;
if (lineEnd === this._cursor) {
return;
}
this._text = this._text.slice(0, this._cursor) + this._text.slice(lineEnd);
}
moveToStart(): void {
this._cursor = 0;
}
@ -402,13 +434,10 @@ export class TextBuffer {
this.moveToEnd();
return true;
case "u":
// Delete from cursor to start of line
this._text = this._text.slice(this._cursor);
this._cursor = 0;
this.deleteLineBackward();
return true;
case "k":
// Delete from cursor to end of line
this._text = this._text.slice(0, this._cursor);
this.deleteLineForward();
return true;
case "w":
this.deleteWordBackward();
@ -422,8 +451,12 @@ export class TextBuffer {
}
private handleMetaKey(input: string, key: Key): boolean {
if (key.backspace || key.delete) {
this.deleteWordBackward();
if (key.backspace) {
this.deleteLineBackward();
return true;
}
if (key.delete) {
this.deleteLineForward();
return true;
}
if (key.leftArrow) {

View file

@ -4,7 +4,7 @@ import {
serviceContainer,
services,
} from "../../services/index.js";
import { ModelServiceState } from "../../services/types.js";
import { AuthServiceState, ModelServiceState } from "../../services/types.js";
import { useNavigation } from "../context/NavigationContext.js";
interface ModelOption {
@ -21,11 +21,13 @@ interface UseModelSelectorProps {
messageType: "system";
}) => void;
onModelSwitch?: () => void;
onRefreshUI?: () => void;
}
export function useModelSelector({
onMessage,
onModelSwitch,
onRefreshUI,
}: UseModelSelectorProps) {
const { closeCurrentScreen } = useNavigation();
@ -44,8 +46,17 @@ export function useModelSelector({
);
// Persist the model choice using the actual model name
// and update the auth service state to reflect the change
if (modelInfo?.name) {
updateModelName(modelInfo.name);
const updatedAuthConfig = updateModelName(modelInfo.name);
// Update the AUTH service state in the container with the new config
// This ensures that when MODEL service is reloaded, it gets the updated auth config
const currentAuthState = services.auth.getState();
serviceContainer.set<AuthServiceState>(SERVICE_NAMES.AUTH, {
...currentAuthState,
authConfig: updatedAuthConfig,
});
}
onMessage({
@ -58,6 +69,11 @@ export function useModelSelector({
if (onModelSwitch) {
onModelSwitch();
}
// Force UI refresh to update the IntroMessage with new model
if (onRefreshUI) {
onRefreshUI();
}
} catch (error: any) {
onMessage({
role: "system",

View file

@ -175,6 +175,7 @@ export function useSelectors(
configPath: string | undefined,
setChatHistory: React.Dispatch<React.SetStateAction<any[]>>,
handleClear: () => void,
setStaticRefreshTrigger?: React.Dispatch<React.SetStateAction<number>>,
): {
handleConfigSelect: (config: ConfigOption) => Promise<void>;
handleModelSelect: (model: ModelOption) => Promise<void>;
@ -205,6 +206,12 @@ export function useSelectors(
},
]);
},
onRefreshUI: () => {
// Force a UI refresh to update the IntroMessage with new model
if (setStaticRefreshTrigger) {
setStaticRefreshTrigger((prev) => prev + 1);
}
},
});
return {

View file

@ -0,0 +1,19 @@
import { GlobalContext } from "core/util/GlobalContext.js";
/**
* Get the persisted model name for CLI from GlobalContext
* Used for unauthenticated users
*/
export function getPersistedModelName(): string | null {
const globalContext = new GlobalContext();
return globalContext.get("cliSelectedModel") ?? null;
}
/**
* Persist the model name for CLI to GlobalContext
* Used for unauthenticated users
*/
export function persistModelName(modelName: string | null): void {
const globalContext = new GlobalContext();
globalContext.update("cliSelectedModel", modelName ?? undefined);
}

View file

@ -12,7 +12,7 @@ describe("updateAnthropicModelInYaml", () => {
expect(result).toContain("name: Local Config");
expect(result).toContain("version: 1.0.0");
expect(result).toContain("schema: v1");
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
});
@ -21,7 +21,7 @@ describe("updateAnthropicModelInYaml", () => {
const result = updateAnthropicModelInYaml(invalidYaml, testApiKey);
expect(result).toContain("name: Local Config");
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
});
});
@ -44,7 +44,7 @@ models:
expect(result).toContain("# My Continue config");
expect(result).toContain("# List of available models");
expect(result).toContain("uses: openai/gpt-4");
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
});
@ -55,7 +55,7 @@ version: 1.0.0
schema: v1
# List of available models
models:
- uses: anthropic/claude-4-sonnet
- uses: anthropic/claude-sonnet-4-5
with:
ANTHROPIC_API_KEY: old-key
`;
@ -64,7 +64,7 @@ models:
expect(result).toContain("# My Continue config");
expect(result).toContain("# List of available models");
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
expect(result).not.toContain("old-key");
});
@ -84,7 +84,7 @@ models:
const result = updateAnthropicModelInYaml(existingConfig, testApiKey);
expect(result).toContain("uses: openai/gpt-4");
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
expect(result).toContain("OPENAI_API_KEY: TEST-openai-test");
});
@ -94,7 +94,7 @@ models:
version: 1.0.0
schema: v1
models:
- uses: anthropic/claude-4-sonnet
- uses: anthropic/claude-sonnet-4-5
with:
ANTHROPIC_API_KEY: old-anthropic-key
- uses: openai/gpt-4
@ -104,7 +104,7 @@ models:
const result = updateAnthropicModelInYaml(existingConfig, testApiKey);
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
expect(result).toContain("uses: openai/gpt-4");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
expect(result).toContain("OPENAI_API_KEY: TEST-openai-test");
@ -112,7 +112,7 @@ models:
// Should only have one anthropic model
const anthropicMatches = result.match(
/uses: anthropic\/claude-4-sonnet/g,
/uses: anthropic\/claude-sonnet-4-5/g,
);
expect(anthropicMatches).toHaveLength(1);
});
@ -130,7 +130,7 @@ schema: v1
expect(result).toContain("name: Local Config");
expect(result).toContain("models:");
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
});
@ -147,7 +147,7 @@ models: []
);
expect(result).toContain("name: Local Config");
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
});
});
@ -189,7 +189,7 @@ models: "not an array"
const result = updateAnthropicModelInYaml(malformedConfig, testApiKey);
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
});

View file

@ -27,7 +27,7 @@ export function updateAnthropicModelInYaml(
apiKey: string,
): string {
const newModel: ModelConfig = {
uses: "anthropic/claude-4-sonnet",
uses: "anthropic/claude-sonnet-4-5",
with: {
ANTHROPIC_API_KEY: apiKey,
},
@ -62,7 +62,7 @@ export function updateAnthropicModelInYaml(
// Filter out existing anthropic models
config.models = config.models.filter(
(model: any) => !model || model.uses !== "anthropic/claude-4-sonnet",
(model: any) => !model || model.uses !== "anthropic/claude-sonnet-4-5",
);
// Add the new anthropic model