diff --git a/src/auth/workos.test.ts b/src/auth/workos.test.ts index 7347124ab..3a3fd72f8 100644 --- a/src/auth/workos.test.ts +++ b/src/auth/workos.test.ts @@ -1,187 +1,187 @@ -import { - isAuthenticatedConfig, - isEnvironmentAuthConfig, - getAccessToken, - getOrganizationId, - getAssistantSlug, - AuthConfig, +import { AuthenticatedConfig, - EnvironmentAuthConfig -} from './workos.js'; + EnvironmentAuthConfig, + getAccessToken, + getAssistantSlug, + getOrganizationId, + isAuthenticatedConfig, + isEnvironmentAuthConfig, + slugToUri, +} from "./workos.js"; -describe('workos utility functions', () => { - describe('isAuthenticatedConfig', () => { - it('should return true for authenticated config', () => { +describe("workos utility functions", () => { + describe("isAuthenticatedConfig", () => { + it("should return true for authenticated config", () => { const config: AuthenticatedConfig = { - userId: 'user123', - userEmail: 'user@example.com', - accessToken: 'token123', - refreshToken: 'refresh123', + userId: "user123", + userEmail: "user@example.com", + accessToken: "token123", + refreshToken: "refresh123", expiresAt: Date.now() + 3600000, - organizationId: 'org123', - assistantSlug: 'assistant123' + organizationId: "org123", + configUri: slugToUri("assistant123"), }; expect(isAuthenticatedConfig(config)).toBe(true); }); - it('should return false for environment auth config', () => { + it("should return false for environment auth config", () => { const config: EnvironmentAuthConfig = { - accessToken: 'token123', + accessToken: "token123", organizationId: null, - assistantSlug: 'assistant123' + configUri: slugToUri("assistant123"), }; expect(isAuthenticatedConfig(config)).toBe(false); }); - it('should return false for null config', () => { + it("should return false for null config", () => { expect(isAuthenticatedConfig(null)).toBe(false); }); }); - describe('isEnvironmentAuthConfig', () => { - it('should return true for environment auth config', () => { + describe("isEnvironmentAuthConfig", () => { + it("should return true for environment auth config", () => { const config: EnvironmentAuthConfig = { - accessToken: 'token123', + accessToken: "token123", organizationId: null, - assistantSlug: 'assistant123' + configUri: slugToUri("assistant123"), }; expect(isEnvironmentAuthConfig(config)).toBe(true); }); - it('should return false for authenticated config', () => { + it("should return false for authenticated config", () => { const config: AuthenticatedConfig = { - userId: 'user123', - userEmail: 'user@example.com', - accessToken: 'token123', - refreshToken: 'refresh123', + userId: "user123", + userEmail: "user@example.com", + accessToken: "token123", + refreshToken: "refresh123", expiresAt: Date.now() + 3600000, - organizationId: 'org123', - assistantSlug: 'assistant123' + organizationId: "org123", + configUri: slugToUri("assistant123"), }; expect(isEnvironmentAuthConfig(config)).toBe(false); }); - it('should return false for null config', () => { + it("should return false for null config", () => { expect(isEnvironmentAuthConfig(null)).toBe(false); }); }); - describe('getAccessToken', () => { - it('should return access token from authenticated config', () => { + describe("getAccessToken", () => { + it("should return access token from authenticated config", () => { const config: AuthenticatedConfig = { - userId: 'user123', - userEmail: 'user@example.com', - accessToken: 'token123', - refreshToken: 'refresh123', + userId: "user123", + userEmail: "user@example.com", + accessToken: "token123", + refreshToken: "refresh123", expiresAt: Date.now() + 3600000, - organizationId: 'org123', - assistantSlug: 'assistant123' + organizationId: "org123", + configUri: slugToUri("assistant123"), }; - expect(getAccessToken(config)).toBe('token123'); + expect(getAccessToken(config)).toBe("token123"); }); - it('should return access token from environment auth config', () => { + it("should return access token from environment auth config", () => { const config: EnvironmentAuthConfig = { - accessToken: 'env-token123', + accessToken: "env-token123", organizationId: null, - assistantSlug: 'assistant123' + configUri: slugToUri("assistant123"), }; - expect(getAccessToken(config)).toBe('env-token123'); + expect(getAccessToken(config)).toBe("env-token123"); }); - it('should return null for null config', () => { + it("should return null for null config", () => { expect(getAccessToken(null)).toBe(null); }); }); - describe('getOrganizationId', () => { - it('should return organization ID from authenticated config', () => { + describe("getOrganizationId", () => { + it("should return organization ID from authenticated config", () => { const config: AuthenticatedConfig = { - userId: 'user123', - userEmail: 'user@example.com', - accessToken: 'token123', - refreshToken: 'refresh123', + userId: "user123", + userEmail: "user@example.com", + accessToken: "token123", + refreshToken: "refresh123", expiresAt: Date.now() + 3600000, - organizationId: 'org123', - assistantSlug: 'assistant123' + organizationId: "org123", + configUri: slugToUri("assistant123"), }; - expect(getOrganizationId(config)).toBe('org123'); + expect(getOrganizationId(config)).toBe("org123"); }); - it('should return null organization ID from authenticated config', () => { + it("should return null organization ID from authenticated config", () => { const config: AuthenticatedConfig = { - userId: 'user123', - userEmail: 'user@example.com', - accessToken: 'token123', - refreshToken: 'refresh123', + userId: "user123", + userEmail: "user@example.com", + accessToken: "token123", + refreshToken: "refresh123", expiresAt: Date.now() + 3600000, organizationId: null, - assistantSlug: 'assistant123' + configUri: slugToUri("assistant123"), }; expect(getOrganizationId(config)).toBe(null); }); - it('should return null from environment auth config', () => { + it("should return null from environment auth config", () => { const config: EnvironmentAuthConfig = { - accessToken: 'env-token123', + accessToken: "env-token123", organizationId: null, - assistantSlug: 'assistant123' + configUri: slugToUri("assistant123"), }; expect(getOrganizationId(config)).toBe(null); }); - it('should return null for null config', () => { + it("should return null for null config", () => { expect(getOrganizationId(null)).toBe(null); }); }); - describe('getAssistantSlug', () => { - it('should return assistant slug from authenticated config', () => { + describe("getAssistantSlug", () => { + it("should return assistant slug from authenticated config", () => { const config: AuthenticatedConfig = { - userId: 'user123', - userEmail: 'user@example.com', - accessToken: 'token123', - refreshToken: 'refresh123', + userId: "user123", + userEmail: "user@example.com", + accessToken: "token123", + refreshToken: "refresh123", expiresAt: Date.now() + 3600000, - organizationId: 'org123', - assistantSlug: 'assistant123' + organizationId: "org123", + configUri: slugToUri("assistant123"), }; - expect(getAssistantSlug(config)).toBe('assistant123'); + expect(getAssistantSlug(config)).toBe("assistant123"); }); - it('should return null when assistant slug is undefined in authenticated config', () => { + it("should return null when assistant slug is undefined in authenticated config", () => { const config: AuthenticatedConfig = { - userId: 'user123', - userEmail: 'user@example.com', - accessToken: 'token123', - refreshToken: 'refresh123', + userId: "user123", + userEmail: "user@example.com", + accessToken: "token123", + refreshToken: "refresh123", expiresAt: Date.now() + 3600000, - organizationId: 'org123', - assistantSlug: undefined + organizationId: "org123", + configUri: undefined, }; expect(getAssistantSlug(config)).toBe(null); }); - it('should return assistant slug from environment auth config', () => { + it("should return assistant slug from environment auth config", () => { const config: EnvironmentAuthConfig = { - accessToken: 'env-token123', + accessToken: "env-token123", organizationId: null, - assistantSlug: 'env-assistant123' + configUri: slugToUri("env-assistant123"), }; - expect(getAssistantSlug(config)).toBe('env-assistant123'); + expect(getAssistantSlug(config)).toBe("env-assistant123"); }); - it('should return null when assistant slug is undefined in environment auth config', () => { + it("should return null when assistant slug is undefined in environment auth config", () => { const config: EnvironmentAuthConfig = { - accessToken: 'env-token123', + accessToken: "env-token123", organizationId: null, - assistantSlug: undefined + configUri: undefined, }; expect(getAssistantSlug(config)).toBe(null); }); - it('should return null for null config', () => { + it("should return null for null config", () => { expect(getAssistantSlug(null)).toBe(null); }); }); -}); \ No newline at end of file +}); diff --git a/src/auth/workos.ts b/src/auth/workos.ts index 2cfda8ea7..8fa496fe5 100644 --- a/src/auth/workos.ts +++ b/src/auth/workos.ts @@ -24,14 +24,14 @@ export interface AuthenticatedConfig { refreshToken: string; expiresAt: number; organizationId: string | null; // null means personal organization - assistantSlug?: string; // Optional assistant slug + configUri?: string; // Optional config URI (file:// or slug://owner/slug) } // Represents configuration when using environment variable auth export interface EnvironmentAuthConfig { accessToken: string; organizationId: null; // Environment auth always uses personal organization - assistantSlug?: string; // Optional assistant slug + configUri?: string; // Optional config URI (file:// or slug://owner/slug) } // Union type representing the possible authentication states @@ -72,11 +72,49 @@ export function getOrganizationId(config: AuthConfig): string | null { } /** - * Gets the assistant slug from any auth config type + * Gets the config URI from any auth config type + */ +export function getConfigUri(config: AuthConfig): string | null { + if (config === null) return null; + return config.configUri || null; +} + +/** + * Utility functions for config URI conversion + */ +export function pathToUri(path: string): string { + return `file://${path}`; +} + +export function slugToUri(slug: string): string { + return `slug://${slug}`; +} + +export function uriToPath(uri: string): string | null { + if (uri.startsWith("file://")) { + return uri.slice(7); + } + return null; +} + +export function uriToSlug(uri: string): string | null { + if (uri.startsWith("slug://")) { + return uri.slice(7); // Remove 'slug://' prefix + } + return null; +} + +/** + * Legacy functions for backward compatibility */ export function getAssistantSlug(config: AuthConfig): string | null { - if (config === null) return null; - return config.assistantSlug || null; + const uri = getConfigUri(config); + return uri ? uriToSlug(uri) : null; +} + +export function getLocalConfigPath(config: AuthConfig): string | null { + const uri = getConfigUri(config); + return uri ? uriToPath(uri) : null; } /** @@ -110,7 +148,7 @@ export function loadAuthConfig(): AuthConfig { refreshToken: data.refreshToken, expiresAt: data.expiresAt, organizationId: data.organizationId || null, - assistantSlug: data.assistantSlug || undefined, + configUri: data.configUri, }; } else { console.warn("Invalid auth config found, ignoring."); @@ -147,9 +185,9 @@ export function saveAuthConfig(config: AuthenticatedConfig): void { } /** - * Updates the assistant slug in the authentication configuration + * Updates the config URI in the authentication configuration */ -export function updateAssistantSlug(assistantSlug: string | null): void { +export function updateConfigUri(configUri: string | null): void { // If using CONTINUE_API_KEY environment variable, don't save anything if (process.env.CONTINUE_API_KEY) { return; @@ -159,12 +197,23 @@ export function updateAssistantSlug(assistantSlug: string | null): void { if (config && isAuthenticatedConfig(config)) { const updatedConfig: AuthenticatedConfig = { ...config, - assistantSlug: assistantSlug || undefined, + configUri: configUri || undefined, }; saveAuthConfig(updatedConfig); } } +/** + * Legacy functions for backward compatibility + */ +export function updateAssistantSlug(assistantSlug: string | null): void { + updateConfigUri(assistantSlug ? slugToUri(assistantSlug) : null); +} + +export function updateLocalConfigPath(localConfigPath: string | null): void { + updateConfigUri(localConfigPath ? pathToUri(localConfigPath) : null); +} + /** * Checks if the user is authenticated and the token is valid */ @@ -393,9 +442,9 @@ async function refreshToken( organizationId: isAuthenticatedConfig(existingConfig) ? existingConfig.organizationId : null, - // Preserve existing assistantSlug if it exists - assistantSlug: isAuthenticatedConfig(existingConfig) - ? existingConfig.assistantSlug + // Preserve existing configUri if it exists + configUri: isAuthenticatedConfig(existingConfig) + ? existingConfig.configUri : undefined, }; @@ -493,7 +542,7 @@ export async function ensureOrganization( refreshToken: authenticatedConfig.refreshToken, expiresAt: authenticatedConfig.expiresAt, organizationId: null, // Default to personal organization - assistantSlug: authenticatedConfig.assistantSlug, + configUri: authenticatedConfig.configUri, }; saveAuthConfig(updatedConfig); return updatedConfig; @@ -514,7 +563,7 @@ export async function ensureOrganization( refreshToken: authenticatedConfig.refreshToken, expiresAt: authenticatedConfig.expiresAt, organizationId: null, - assistantSlug: authenticatedConfig.assistantSlug, + configUri: authenticatedConfig.configUri, }; saveAuthConfig(updatedConfig); return updatedConfig; @@ -531,7 +580,7 @@ export async function ensureOrganization( refreshToken: authenticatedConfig.refreshToken, expiresAt: authenticatedConfig.expiresAt, organizationId: selectedOrgId, - assistantSlug: authenticatedConfig.assistantSlug, + configUri: authenticatedConfig.configUri, }; saveAuthConfig(updatedConfig); @@ -549,7 +598,7 @@ export async function ensureOrganization( refreshToken: authenticatedConfig.refreshToken, expiresAt: authenticatedConfig.expiresAt, organizationId: null, - assistantSlug: authenticatedConfig.assistantSlug, + configUri: authenticatedConfig.configUri, }; saveAuthConfig(updatedConfig); return updatedConfig; diff --git a/src/config.ts b/src/config.ts index 88e530845..2e473fe1e 100644 --- a/src/config.ts +++ b/src/config.ts @@ -19,7 +19,6 @@ import { dirname } from "node:path"; import { AuthConfig, getAccessToken, - getAssistantSlug, getOrganizationId, } from "./auth/workos.js"; import { CLIPlatformClient } from "./CLIPlatformClient.js"; @@ -69,7 +68,7 @@ export function getLlmApi( if (!llmApi) { throw new Error( - "Failed to initialized LLM. Please check your configuration." + "Failed to initialize LLM. Please check your configuration." ); } @@ -135,42 +134,33 @@ export async function loadConfig( } if (!config) { - // Check if there's a saved assistant slug in auth config - const assistantSlug = getAssistantSlug(authConfig); - if (assistantSlug) { - // Use the saved assistant slug - config = assistantSlug; - } else { - // Fall back to listing assistants and taking the first one - const assistants = await apiClient.listAssistants({ - alwaysUseProxy: "false", + // Fall back to listing assistants and taking the first one + const assistants = await apiClient.listAssistants({ + alwaysUseProxy: "false", + organizationId: organizationId ?? undefined, + }); + + if (assistants.length === 0) { + // In case the user doesn't have any assistants, we fall back to a default - TODO + const resp = await apiClient.getAssistant({ + ownerSlug: "continuedev", + packageSlug: "default-agent", organizationId: organizationId ?? undefined, }); - if (assistants.length === 0) { - // In case the user doesn't have any assistants, we fall back to a default - TODO - const resp = await apiClient.getAssistant({ - ownerSlug: "continuedev", - packageSlug: "default-agent", - organizationId: organizationId ?? undefined, - }); - - if (!resp.configResult.config) { - throw new Error("Failed to load default agent."); - } - return resp.configResult.config as AssistantUnrolled; + if (!resp.configResult.config) { + throw new Error("Failed to load default agent."); } - - const result = assistants[0].configResult; - - if (result.errors?.length || !result.config) { - throw new Error( - result.errors?.join("\n") ?? "Failed to load assistant." - ); - } - - return result.config as AssistantUnrolled; + return resp.configResult.config as AssistantUnrolled; } + + const result = assistants[0].configResult; + + if (result.errors?.length || !result.config) { + throw new Error(result.errors?.join("\n") ?? "Failed to load assistant."); + } + + return result.config as AssistantUnrolled; } if ( diff --git a/src/e2e/local-config-switching.test.tsx b/src/e2e/local-config-switching.test.tsx new file mode 100644 index 000000000..10b98008b --- /dev/null +++ b/src/e2e/local-config-switching.test.tsx @@ -0,0 +1,153 @@ +import { describe, expect, test } from '@jest/globals'; + +describe('Local Config Switching Investigation', () => { + test('understands local vs remote config paths', () => { + // Document the different types of config paths: + + const configTypes = { + localFilePaths: [ + '~/.continue/config.yaml', + './config.yaml', + '/absolute/path/to/config.yaml' + ], + remoteAssistantSlugs: [ + 'continuedev/default-agent', + 'myorg/custom-assistant', + 'user/my-assistant' + ], + undefinedMeansDefault: undefined // Uses saved assistant slug or first assistant + }; + + // The isFilePath method checks for these patterns: + const isFilePath = (configPath: string) => { + return ( + configPath.startsWith(".") || + configPath.startsWith("/") || + configPath.startsWith("~") + ); + }; + + // Verify our understanding + configTypes.localFilePaths.forEach(path => { + expect(isFilePath(path)).toBe(true); + }); + + configTypes.remoteAssistantSlugs.forEach(slug => { + expect(isFilePath(slug)).toBe(false); + }); + }); + + test('documents the local config switching problem', () => { + // User reported issue: "Switching configs always works except when I'm using a local config" + + const problemScenarios = [ + { + name: 'Remote to Remote switching', + from: 'continuedev/default-agent', + to: 'myorg/custom-assistant', + works: true, + reason: 'Both are assistant slugs, normal flow works' + }, + { + name: 'Remote to Local switching', + from: 'continuedev/default-agent', + to: '~/.continue/config.yaml', + works: false, // This is the reported issue + reason: 'UNKNOWN - this is what we need to debug' + }, + { + name: 'Local to Remote switching', + from: '~/.continue/config.yaml', + to: 'continuedev/default-agent', + works: false, // Likely also broken + reason: 'UNKNOWN - probably same root cause' + }, + { + name: 'Local to Local switching', + from: '~/.continue/config.yaml', + to: './other-config.yaml', + works: false, // Likely also broken + reason: 'UNKNOWN - probably same root cause' + } + ]; + + // The problem is specifically with local configs + const brokenScenarios = problemScenarios.filter(s => !s.works); + expect(brokenScenarios.length).toBeGreaterThan(0); + + // All broken scenarios involve local configs + const allInvolveLocalConfigs = brokenScenarios.every(scenario => + scenario.from.includes('/') || scenario.from.includes('~') || scenario.from.includes('.') || + scenario.to.includes('/') || scenario.to.includes('~') || scenario.to.includes('.') + ); + expect(allInvolveLocalConfigs).toBe(true); + }); + + test('hypothesis: local config loading has different behavior', async () => { + // The loadConfig function has two different code paths: + + const { loadConfig } = await import('../config.js'); + + // Path 1: Local file loading (lines 176-189 in config.ts) + // if (config.startsWith(".") || config.startsWith("/") || config.startsWith("~")) { + // const configYaml = await loadConfigYaml(authConfig?.accessToken ?? null, config, organizationId, apiClient); + // return configYaml; + // } + + // Path 2: Remote assistant slug loading (lines 190-203 in config.ts) + // else { + // const [ownerSlug, packageSlug] = config.split("/"); + // const resp = await apiClient.getAssistant({ ownerSlug, packageSlug, ... }); + // return result.config; + // } + + // Hypothesis: The loadConfig function works correctly, but something else is different + // about how local configs are handled in the ConfigService or service container + + expect(typeof loadConfig).toBe('function'); + + // The issue might be: + // 1. Different state management for local vs remote configs + // 2. Assistant slug handling interfering with local configs + // 3. Service container reload behavior differs for local configs + // 4. Some caching or memoization issue specific to file paths + }); + + test('investigates assistant slug handling for local configs', async () => { + // When switching to a local config, we call updateAssistantSlug(null) + // When switching to a remote config, we call updateAssistantSlug(configPath) + + const { updateAssistantSlug, getAssistantSlug } = await import('../auth/workos.js'); + + expect(typeof updateAssistantSlug).toBe('function'); + expect(typeof getAssistantSlug).toBe('function'); + + // Question: Could the assistant slug clearing/setting be interfering + // with the config loading process? + + // In loadConfig, when config is undefined, it checks for saved assistant slug: + // const assistantSlug = getAssistantSlug(authConfig); + // if (assistantSlug) { config = assistantSlug; } + + // Potential issue: If we're switching TO a local config but the assistant slug + // is still set from a previous remote config, could that interfere? + }); + + test('checks if ConfigService state management differs for local configs', async () => { + const { ConfigService } = await import('../services/ConfigService.js'); + + // The ConfigService.updateConfigPath method should work the same for both types: + // 1. Load new config via loadConfig(authConfig, newConfigPath, ...) + // 2. Update this.currentState = { config, configPath: newConfigPath } + // 3. Call serviceContainer.set(CONFIG, this.currentState) + // 4. Call serviceContainer.reload(MODEL) and serviceContainer.reload(MCP) + + // But maybe there's a subtle difference in how the state is managed? + + const configService = new ConfigService(); + expect(typeof configService.getState).toBe('function'); + + // The state should be: { config: AssistantUnrolled, configPath: string | undefined } + // This should be the same regardless of whether configPath is a file or slug + }); +}); \ No newline at end of file diff --git a/src/services/ConfigService.ts b/src/services/ConfigService.ts index 4f51f2f99..915e9130e 100644 --- a/src/services/ConfigService.ts +++ b/src/services/ConfigService.ts @@ -1,11 +1,22 @@ import { AssistantUnrolled } from "@continuedev/config-yaml"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; -import { processRule } from '../args.js'; -import { loadConfig } from '../config.js'; -import { AuthConfig, updateAssistantSlug, loadAuthConfig } from '../auth/workos.js'; -import logger from '../util/logger.js'; -import { ConfigServiceState, SERVICE_NAMES, AuthServiceState, ApiClientServiceState } from './types.js'; -import { serviceContainer } from './ServiceContainer.js'; +import { processRule } from "../args.js"; +import { + AuthConfig, + loadAuthConfig, + pathToUri, + slugToUri, + updateConfigUri, +} from "../auth/workos.js"; +import { loadConfig } from "../config.js"; +import logger from "../util/logger.js"; +import { serviceContainer } from "./ServiceContainer.js"; +import { + ApiClientServiceState, + AuthServiceState, + ConfigServiceState, + SERVICE_NAMES, +} from "./types.js"; /** * Service for managing configuration state and operations @@ -14,7 +25,7 @@ import { serviceContainer } from './ServiceContainer.js'; export class ConfigService { private currentState: ConfigServiceState = { config: null, - configPath: undefined + configPath: undefined, }; /** @@ -27,11 +38,14 @@ export class ConfigService { apiClient: DefaultApiInterface, rules?: string[] ): Promise { - logger.debug('Initializing ConfigService', { configPath, organizationId }); - try { - let config = await loadConfig(authConfig, configPath, organizationId, apiClient); - + let config = await loadConfig( + authConfig, + configPath, + organizationId, + apiClient + ); + // Inject rules if provided if (rules && rules.length > 0) { config = await this.injectRulesIntoConfig(config, rules); @@ -39,18 +53,23 @@ export class ConfigService { this.currentState = { config, - configPath + configPath, }; - // Save assistant slug to auth config if loading by slug - if (configPath && !this.isFilePath(configPath)) { - updateAssistantSlug(configPath); + // Save config URI to auth config + if (configPath) { + const configUri = this.isFilePath(configPath) + ? pathToUri(configPath) + : slugToUri(configPath); + updateConfigUri(configUri); + } else { + updateConfigUri(null); } - logger.debug('ConfigService initialized successfully'); + logger.debug("ConfigService initialized successfully"); return this.currentState; } catch (error: any) { - logger.error('Failed to initialize ConfigService:', error); + logger.error("Failed to initialize ConfigService:", error); throw error; } } @@ -72,14 +91,19 @@ export class ConfigService { apiClient: DefaultApiInterface, rules?: string[] ): Promise { - logger.debug('Switching configuration', { + logger.debug("Switching configuration", { from: this.currentState.configPath, - to: newConfigPath + to: newConfigPath, }); try { - let config = await loadConfig(authConfig, newConfigPath, organizationId, apiClient); - + let config = await loadConfig( + authConfig, + newConfigPath, + organizationId, + apiClient + ); + // Inject rules if provided if (rules && rules.length > 0) { config = await this.injectRulesIntoConfig(config, rules); @@ -87,21 +111,22 @@ export class ConfigService { this.currentState = { config, - configPath: newConfigPath + configPath: newConfigPath, }; - // Save assistant slug to auth config if loading by slug - if (!this.isFilePath(newConfigPath)) { - updateAssistantSlug(newConfigPath); - } + // Save config URI to auth config + const configUri = this.isFilePath(newConfigPath) + ? pathToUri(newConfigPath) + : slugToUri(newConfigPath); + updateConfigUri(configUri); - logger.debug('Configuration switched successfully', { - newConfigPath + logger.debug("Configuration switched successfully", { + newConfigPath, }); return this.currentState; } catch (error: any) { - logger.error('Failed to switch configuration:', error); + logger.error("Failed to switch configuration:", error); throw error; } } @@ -116,11 +141,11 @@ export class ConfigService { rules?: string[] ): Promise { if (!this.currentState.configPath) { - throw new Error('No configuration path available for reload'); + throw new Error("No configuration path available for reload"); } - logger.debug('Reloading current configuration'); - + logger.debug("Reloading current configuration"); + return this.switchConfig( this.currentState.configPath, authConfig, @@ -142,7 +167,7 @@ export class ConfigService { } let processedRules: string[] = []; - + for (const ruleSpec of rules) { try { const processedRule = await processRule(ruleSpec); @@ -164,7 +189,9 @@ export class ConfigService { const rulesSection = processedRules.join("\n\n"); if (existingSystemMessage) { - (modifiedConfig as any).systemMessage = `${existingSystemMessage}\n\n${rulesSection}`; + ( + modifiedConfig as any + ).systemMessage = `${existingSystemMessage}\n\n${rulesSection}`; } else { (modifiedConfig as any).systemMessage = rulesSection; } @@ -177,56 +204,63 @@ export class ConfigService { * This triggers automatic dependent service reloads via the reactive system */ async updateConfigPath(newConfigPath: string | undefined): Promise { - logger.debug('Updating config path', { + logger.debug("Updating config path", { from: this.currentState.configPath, - to: newConfigPath + to: newConfigPath, }); try { // Get current auth and API client state needed for config loading const authConfig = loadAuthConfig(); - const authState = await serviceContainer.get(SERVICE_NAMES.AUTH); - const apiClientState = await serviceContainer.get(SERVICE_NAMES.API_CLIENT); + const authState = await serviceContainer.get( + SERVICE_NAMES.AUTH + ); + const apiClientState = await serviceContainer.get( + SERVICE_NAMES.API_CLIENT + ); if (!apiClientState.apiClient) { - throw new Error('API client not available'); + throw new Error("API client not available"); } // Load the new configuration let config = await loadConfig( - authConfig, - newConfigPath, - authState.organizationId || null, + authConfig, + newConfigPath, + authState.organizationId || null, apiClientState.apiClient ); // Update internal state this.currentState = { config, - configPath: newConfigPath + configPath: newConfigPath, }; - // Save assistant slug to auth config if loading by slug - if (newConfigPath && !this.isFilePath(newConfigPath)) { - updateAssistantSlug(newConfigPath); - } else if (!newConfigPath) { - // Clear assistant slug when switching to local config or undefined - updateAssistantSlug(null); + // Save config URI to auth config + if (newConfigPath) { + const configUri = this.isFilePath(newConfigPath) + ? pathToUri(newConfigPath) + : slugToUri(newConfigPath); + updateConfigUri(configUri); + } else { + // Clear config URI when switching to undefined + updateConfigUri(null); } // Update the CONFIG service in the container serviceContainer.set(SERVICE_NAMES.CONFIG, this.currentState); - + // Manually reload dependent services (MODEL, MCP) to pick up the new config await serviceContainer.reload(SERVICE_NAMES.MODEL); await serviceContainer.reload(SERVICE_NAMES.MCP); - logger.debug('Configuration path updated successfully', { + logger.debug("Configuration path updated successfully", { newConfigPath, - configName: config.name + configName: config.name, }); } catch (error: any) { - logger.error('Failed to update configuration path:', error); + logger.error("Failed to update configuration path:", error); throw error; } } @@ -241,4 +275,4 @@ export class ConfigService { configPath.startsWith("~") ); } -} \ No newline at end of file +} diff --git a/src/services/index.ts b/src/services/index.ts index 285913bdc..b1aaa28e0 100644 --- a/src/services/index.ts +++ b/src/services/index.ts @@ -1,11 +1,17 @@ -import { serviceContainer } from './ServiceContainer.js'; -import { AuthService } from './AuthService.js'; -import { ConfigService } from './ConfigService.js'; -import { ModelService } from './ModelService.js'; -import { ApiClientService } from './ApiClientService.js'; -import { MCPServiceWrapper } from './MCPServiceWrapper.js'; -import { SERVICE_NAMES, ServiceInitOptions, AuthServiceState, ApiClientServiceState, ConfigServiceState } from './types.js'; -import logger from '../util/logger.js'; +import logger from "../util/logger.js"; +import { ApiClientService } from "./ApiClientService.js"; +import { AuthService } from "./AuthService.js"; +import { ConfigService } from "./ConfigService.js"; +import { MCPServiceWrapper } from "./MCPServiceWrapper.js"; +import { ModelService } from "./ModelService.js"; +import { serviceContainer } from "./ServiceContainer.js"; +import { + ApiClientServiceState, + AuthServiceState, + ConfigServiceState, + SERVICE_NAMES, + ServiceInitOptions, +} from "./types.js"; // Service instances const authService = new AuthService(); @@ -18,7 +24,7 @@ const mcpServiceWrapper = new MCPServiceWrapper(); * Initialize all services and register them with the service container */ export async function initializeServices(options: ServiceInitOptions = {}) { - logger.debug('Initializing service registry'); + logger.debug("Initializing service registry"); // Register service factories with dependencies serviceContainer.register( @@ -30,7 +36,9 @@ export async function initializeServices(options: ServiceInitOptions = {}) { serviceContainer.register( SERVICE_NAMES.API_CLIENT, async () => { - const authState = await serviceContainer.get(SERVICE_NAMES.AUTH); + const authState = await serviceContainer.get( + SERVICE_NAMES.AUTH + ); return apiClientService.initialize(authState.authConfig); }, [SERVICE_NAMES.AUTH] // Depends on auth @@ -41,24 +49,47 @@ export async function initializeServices(options: ServiceInitOptions = {}) { async () => { const [authState, apiClientState] = await Promise.all([ serviceContainer.get(SERVICE_NAMES.AUTH), - serviceContainer.get(SERVICE_NAMES.API_CLIENT) + serviceContainer.get(SERVICE_NAMES.API_CLIENT), ]); - + // Ensure organization is selected if authenticated and not headless let finalAuthState = authState; if (authState.authConfig && !options.headless) { - finalAuthState = await authService.ensureOrganization(options.headless ?? false); + finalAuthState = await authService.ensureOrganization( + options.headless ?? false + ); // Update the auth service state in container serviceContainer.set(SERVICE_NAMES.AUTH, finalAuthState); } if (!apiClientState.apiClient) { - throw new Error('API client not available'); + throw new Error("API client not available"); + } + + // Use current config path from ConfigService state if available (for reloads), + // otherwise use initial options.configPath (for first initialization) + const currentState = configService.getState(); + let configPath = + currentState.configPath !== undefined + ? currentState.configPath + : options.configPath; + + // If no config path is available, check for saved config URI in auth config + if (!configPath) { + const { getConfigUri, uriToPath, uriToSlug } = await import( + "../auth/workos.js" + ); + const configUri = getConfigUri(finalAuthState.authConfig); + if (configUri) { + const filePath = uriToPath(configUri); + const slug = uriToSlug(configUri); + configPath = filePath || slug || undefined; + } } return configService.initialize( finalAuthState.authConfig, - options.configPath, + configPath, finalAuthState.organizationId || null, apiClientState.apiClient, options.rules @@ -72,13 +103,13 @@ export async function initializeServices(options: ServiceInitOptions = {}) { async () => { const [configState, authState] = await Promise.all([ serviceContainer.get(SERVICE_NAMES.CONFIG), - serviceContainer.get(SERVICE_NAMES.AUTH) + serviceContainer.get(SERVICE_NAMES.AUTH), ]); - + if (!configState.config) { - throw new Error('Config not available'); + throw new Error("Config not available"); } - + return modelService.initialize(configState.config, authState.authConfig); }, [SERVICE_NAMES.CONFIG, SERVICE_NAMES.AUTH] // Depends on config and auth @@ -87,18 +118,20 @@ export async function initializeServices(options: ServiceInitOptions = {}) { serviceContainer.register( SERVICE_NAMES.MCP, async () => { - const configState = await serviceContainer.get(SERVICE_NAMES.CONFIG); - + const configState = await serviceContainer.get( + SERVICE_NAMES.CONFIG + ); + if (!configState.config) { - throw new Error('Config not available for MCP service'); + throw new Error("Config not available for MCP service"); } - + return mcpServiceWrapper.initialize(configState.config); }, [SERVICE_NAMES.CONFIG] // Depends on config ); - logger.debug('Service registry initialized'); + logger.debug("Service registry initialized"); } /** @@ -128,11 +161,11 @@ export function reloadService(serviceName: string) { export function areServicesReady(): boolean { return [ SERVICE_NAMES.AUTH, - SERVICE_NAMES.API_CLIENT, + SERVICE_NAMES.API_CLIENT, SERVICE_NAMES.CONFIG, SERVICE_NAMES.MODEL, - SERVICE_NAMES.MCP - ].every(name => serviceContainer.isReady(name)); + SERVICE_NAMES.MCP, + ].every((name) => serviceContainer.isReady(name)); } /** @@ -150,12 +183,12 @@ export const services = { config: configService, model: modelService, apiClient: apiClientService, - mcp: mcpServiceWrapper + mcp: mcpServiceWrapper, } as const; // Export the service container for advanced usage export { serviceContainer }; // Export service names and types -export { SERVICE_NAMES } from './types.js'; -export type * from './types.js'; \ No newline at end of file +export type * from "./types.js"; +export { SERVICE_NAMES } from "./types.js"; diff --git a/src/ui/IntroMessage.tsx b/src/ui/IntroMessage.tsx index cc37294bb..a97578e8e 100644 --- a/src/ui/IntroMessage.tsx +++ b/src/ui/IntroMessage.tsx @@ -11,20 +11,25 @@ interface IntroMessageProps { mcpService: MCPService; } -const IntroMessage: React.FC = ({ config, model, mcpService }) => { +const IntroMessage: React.FC = ({ + config, + model, + mcpService, +}) => { const mcpTools = mcpService.getTools() ?? []; const mcpPrompts = mcpService.getPrompts() ?? []; - + // Get all slash commands from central definition const allCommands = getAllSlashCommands(config); - + // Show all rules in a single section const args = parseArgs(); const commandLineRules = args.rules || []; - const configRules = config.rules?.map((rule: any) => - typeof rule === "string" ? rule : rule?.name || "Unknown" - ) || []; - + const configRules = + config.rules?.map((rule: any) => + typeof rule === "string" ? rule : rule?.name || "Unknown" + ) || []; + const allRules = [...commandLineRules, ...configRules]; return ( @@ -33,31 +38,33 @@ const IntroMessage: React.FC = ({ config, model, mcpService } Agent: {config.name} - + {/* Model */} Model: {model.name.split("/").pop()} - + - + {/* Slash commands */} Slash commands: {allCommands.map((command, index) => ( - - /{command.name}: {command.description} + - /{command.name}:{" "} + {command.description} ))} - + {/* MCP prompts */} {mcpPrompts.map((prompt, index) => ( - - /{prompt.name}: {prompt.description} + - /{prompt.name}:{" "} + {prompt.description} ))} - + - + {/* Rules */} {allRules.length > 0 && ( <> @@ -70,7 +77,7 @@ const IntroMessage: React.FC = ({ config, model, mcpService } )} - + {/* MCP Servers */} {config.mcpServers?.length && ( <> @@ -87,4 +94,4 @@ const IntroMessage: React.FC = ({ config, model, mcpService } ); }; -export default IntroMessage; \ No newline at end of file +export default IntroMessage;