diff --git a/extensions/cli/spec/modes.md b/extensions/cli/spec/modes.md index 7296a19eb..49838a3b3 100644 --- a/extensions/cli/spec/modes.md +++ b/extensions/cli/spec/modes.md @@ -57,8 +57,7 @@ Users can switch modes during chat sessions using: Modes are implemented through the permission system: -- **ModeService**: Singleton service managing the current mode and initialization -- **ToolPermissionService**: Extended to support mode-specific policies with highest priority +- **ToolPermissionService**: Rectifies current mode and tool policies - **ModeIndicator**: UI component showing current mode (hidden for normal mode) - **Keyboard shortcuts**: Shift+Tab cycles through modes instantly - **Backward compatibility**: Existing `--readonly` flag maps to plan mode diff --git a/extensions/cli/src/__mocks__/services/index.ts b/extensions/cli/src/__mocks__/services/index.ts index 7ea28d99b..a062ef2a4 100644 --- a/extensions/cli/src/__mocks__/services/index.ts +++ b/extensions/cli/src/__mocks__/services/index.ts @@ -1,3 +1,4 @@ +import { ToolPermissionService } from "src/services/ToolPermissionService.js"; import { vi } from "vitest"; export const services = { @@ -7,14 +8,23 @@ export const services = { switchOrganization: vi.fn(() => Promise.resolve({})), getAvailableOrganizations: vi.fn(() => Promise.resolve([])), }, + toolPermissions: vi.mocked(new ToolPermissionService()), }; export const reloadService = vi.fn(() => Promise.resolve(undefined)); export const SERVICE_NAMES = { AUTH: "auth", - API_CLIENT: "apiClient", CONFIG: "config", MODEL: "model", MCP: "mcp", -}; + API_CLIENT: "apiClient", + TOOL_PERMISSIONS: "toolPermissions", + FILE_INDEX: "fileIndex", + RESOURCE_MONITORING: "resourceMonitoring", + SYSTEM_MESSAGE: "systemMessage", + CHAT_HISTORY: "chatHistory", + UPDATE: "update", + STORAGE_SYNC: "storageSync", + WORKFLOW: "workflow", +} as const; diff --git a/extensions/cli/src/hooks/useService.ts b/extensions/cli/src/hooks/useService.ts index dcbbd57b8..2703c8676 100644 --- a/extensions/cli/src/hooks/useService.ts +++ b/extensions/cli/src/hooks/useService.ts @@ -1,4 +1,4 @@ -import { useEffect, useState } from "react"; +import { useCallback, useEffect, useState } from "react"; import { useServiceContainer } from "../services/ServiceContainerContext.js"; import { ServiceResult } from "../services/types.js"; @@ -96,47 +96,54 @@ export function useServices>( allReady: boolean; } { const container = useServiceContainer(); - const [services, setServices] = useState>({}); + + const getServiceStates = useCallback(() => { + const services: Partial = {}; + let hasLoading = false; + let hasError: Error | null = null; + + for (const serviceName of serviceNames) { + const result = container.getSync(serviceName as string); + + if (result.state === "loading") { + hasLoading = true; + } else if (result.state === "error") { + hasError = result.error; + } else if (result.state === "idle") { + // Auto-load idle services + container.load(serviceName as string).catch(() => {}); + } else if (result.state === "ready" && result.value !== null) { + services[serviceName] = result.value as T[keyof T]; + } else { + } + } + + return { + hasLoading, + hasError, + services, + }; + }, [serviceNames]); + const [loading, setLoading] = useState(true); const [error, setError] = useState(null); + const [services, setServices] = useState>( + getServiceStates().services, + ); useEffect(() => { - const updateState = () => { - const newServices: Partial = {}; - let hasLoading = false; - let hasError: Error | null = null; - - for (const serviceName of serviceNames) { - const result = container.getSync(serviceName as string); - - if (result.state === "loading") { - hasLoading = true; - } else if (result.state === "error") { - hasError = result.error; - } else if (result.state === "idle") { - // Auto-load idle services - container.load(serviceName as string).catch(() => {}); - } else if (result.state === "ready" && result.value !== null) { - newServices[serviceName] = result.value as T[keyof T]; - } else { - } - } - - setServices(newServices); - setLoading(hasLoading); - setError(hasError); - }; - - // Initial state - updateState(); - // Set up listeners for all services const listeners: Array<() => void> = []; for (const serviceName of serviceNames) { const name = serviceName as string; - const onAnyChange = () => updateState(); + const onAnyChange = () => { + const { hasLoading, hasError, services } = getServiceStates(); + setLoading(hasLoading); + setError(hasError); + setServices(services); + }; container.on(`${name}:loading`, onAnyChange); container.on(`${name}:ready`, onAnyChange); @@ -155,7 +162,7 @@ export function useServices>( return () => { listeners.forEach((cleanup) => cleanup()); }; - }, [serviceNames.join(","), container]); + }, [serviceNames.join(","), container, getServiceStates]); const allReady = serviceNames.every((name) => container.isReady(name as string), diff --git a/extensions/cli/src/integration/model-persistence-user-flow.test.ts b/extensions/cli/src/integration/model-persistence-user-flow.test.ts index 35f9eb544..966e69ccb 100644 --- a/extensions/cli/src/integration/model-persistence-user-flow.test.ts +++ b/extensions/cli/src/integration/model-persistence-user-flow.test.ts @@ -5,6 +5,7 @@ import * as path from "path"; import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { AuthService } from "src/services/AuthService.js"; import { AuthenticatedConfig, getModelName, @@ -12,7 +13,6 @@ import { 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 @@ -25,7 +25,7 @@ describe("Model Persistence User Flow", () => { let mockAuthConfig: AuthenticatedConfig; const mockLlmApi = { complete: vi.fn(), stream: vi.fn() }; - beforeEach(() => { + beforeEach(async () => { vi.clearAllMocks(); // Create a temporary directory for testing @@ -68,6 +68,7 @@ describe("Model Persistence User Flow", () => { refreshToken: "test-refresh", expiresAt: Date.now() + 3600000, // 1 hour from now organizationId: "test-org", + modelName: "GPT-4", }; // Setup default mock behavior diff --git a/extensions/cli/src/permissions/permissionChecker.ts b/extensions/cli/src/permissions/permissionChecker.ts index 55a4fbfab..faa52870b 100644 --- a/extensions/cli/src/permissions/permissionChecker.ts +++ b/extensions/cli/src/permissions/permissionChecker.ts @@ -1,10 +1,10 @@ import type { ToolPolicy } from "@continuedev/terminal-security"; import { getServiceSync } from "../services/index.js"; -import type { ToolPermissionServiceState } from "../services/types.js"; import { SERVICE_NAMES } from "../services/types.js"; import { getAllBuiltinTools } from "../tools/index.js"; +import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; import { PermissionCheckResult, diff --git a/extensions/cli/src/services/AuthService.refactored.ts b/extensions/cli/src/services/AuthService.refactored.ts index 0a3a79653..c79d563d2 100644 --- a/extensions/cli/src/services/AuthService.refactored.ts +++ b/extensions/cli/src/services/AuthService.refactored.ts @@ -1,205 +1,206 @@ -import { - AuthenticatedConfig, - login as doLogin, - logout as doLogout, - ensureOrganization, - isAuthenticated, - listUserOrganizations, - loadAuthConfig, - saveAuthConfig, -} from "../auth/workos.js"; -import { logger } from "../util/logger.js"; +// import { +// AuthenticatedConfig, +// login as doLogin, +// logout as doLogout, +// ensureOrganization, +// isAuthenticated, +// listUserOrganizations, +// loadAuthConfig, +// saveAuthConfig, +// } from "../auth/workos.js"; +// import { logger } from "../util/logger.js"; -import { BaseService } from "./BaseService.js"; -import { AuthServiceState } from "./types.js"; +// import { BaseService } from "./BaseService.js"; +// import { AuthServiceState } from "./types.js"; -/** - * Service for managing authentication state and operations - * Now extends BaseService for common functionality - */ -export class AuthService extends BaseService { - constructor() { - super("AuthService", { - authConfig: null, - isAuthenticated: false, - }); - } +// /** +// * Service for managing authentication state and operations +// * Now extends BaseService for common functionality +// */ +// export class AuthService extends BaseService { +// constructor() { +// super("AuthService", { +// authConfig: null, +// isAuthenticated: false, +// }); +// } - /** - * Initialize the auth service by loading current config - */ - async doInitialize(): Promise { - const authConfig = loadAuthConfig(); - const authenticated = isAuthenticated(); +// /** +// * Initialize the auth service by loading current config +// */ +// async doInitialize(): Promise { +// const authConfig = loadAuthConfig(); +// const authenticated = isAuthenticated(); - const state: AuthServiceState = { - authConfig, - isAuthenticated: authenticated, - organizationId: authConfig?.organizationId || undefined, - }; +// const state: AuthServiceState = { +// authConfig, +// isAuthenticated: authenticated, +// organizationId: authConfig?.organizationId || undefined, +// }; - logger.debug("AuthService initialized", { - authenticated, - hasConfig: !!authConfig, - orgId: state.organizationId, - }); +// logger.debug("AuthService initialized", { +// authenticated, +// hasConfig: !!authConfig, +// orgId: state.organizationId, +// }); - return state; - } +// return state; +// } - /** - * Perform login flow - */ - async login(): Promise { - logger.debug("Starting login flow"); +// /** +// * Perform login flow +// */ +// async login(): Promise { +// logger.debug("Starting login flow"); - try { - const newAuthConfig = await doLogin(); +// try { +// const newAuthConfig = await doLogin(); - this.setState({ - authConfig: newAuthConfig, - isAuthenticated: true, - organizationId: newAuthConfig?.organizationId || undefined, - }); +// this.setState({ +// authConfig: newAuthConfig, +// isAuthenticated: true, +// organizationId: newAuthConfig?.organizationId || undefined, +// }); - logger.debug("Login successful", { - orgId: this.currentState.organizationId, - }); +// logger.debug("Login successful", { +// orgId: this.currentState.organizationId, +// }); - return this.getState(); - } catch (error: any) { - logger.error("Login failed:", error); - this.emit("error", error); - throw error; - } - } +// return this.getState(); +// } catch (error: any) { +// logger.error("Login failed:", error); +// this.emit("error", error); +// throw error; +// } +// } - /** - * Perform logout - */ - async logout(): Promise { - logger.debug("Logging out"); +// /** +// * Perform logout +// */ +// async logout(): Promise { +// logger.debug("Logging out"); - doLogout(); +// doLogout(); - this.setState({ - authConfig: null, - isAuthenticated: false, - organizationId: undefined, - }); +// this.setState({ +// authConfig: null, +// isAuthenticated: false, +// organizationId: undefined, +// }); - logger.debug("Logout complete"); - return this.getState(); - } +// logger.debug("Logout complete"); +// return this.getState(); +// } - /** - * Ensure organization is selected, prompting if necessary - */ - async ensureOrganization( - isHeadless: boolean = false, - ): Promise { - if (!this.currentState.authConfig) { - throw new Error("Not authenticated - cannot ensure organization"); - } +// /** +// * Ensure organization is selected, prompting if necessary +// */ +// async ensureOrganization( +// isHeadless: boolean = false, +// ): Promise { +// if (!this.currentState.authConfig) { +// throw new Error("Not authenticated - cannot ensure organization"); +// } - logger.debug("Ensuring organization is selected", { - currentOrgId: this.currentState.organizationId, - isHeadless, - }); +// logger.debug("Ensuring organization is selected", { +// currentOrgId: this.currentState.organizationId, +// isHeadless, +// }); - const updatedConfig = await ensureOrganization( - this.currentState.authConfig, - isHeadless, - ); +// const updatedConfig = await ensureOrganization( +// this.currentState.authConfig, +// isHeadless, +// ); - this.setState({ - authConfig: updatedConfig, - isAuthenticated: true, - organizationId: updatedConfig?.organizationId || undefined, - }); +// this.setState({ +// authConfig: updatedConfig, +// isAuthenticated: true, +// organizationId: updatedConfig?.organizationId || undefined, +// }); - logger.debug("Organization ensured", { - orgId: this.currentState.organizationId, - }); +// logger.debug("Organization ensured", { +// orgId: this.currentState.organizationId, +// }); - return this.getState(); - } +// return this.getState(); +// } - /** - * Switch to a different organization - */ - async switchOrganization( - organizationId: string | null, - ): Promise { - if ( - !this.currentState.authConfig || - !("userId" in this.currentState.authConfig) - ) { - throw new Error( - "Not authenticated with file-based auth - cannot switch organizations", - ); - } +// /** +// * Switch to a different organization +// */ +// async switchOrganization( +// organizationId: string | null, +// ): Promise { +// if ( +// !this.currentState.authConfig || +// !("userId" in this.currentState.authConfig) +// ) { +// throw new Error( +// "Not authenticated with file-based auth - cannot switch organizations", +// ); +// } - logger.debug("Switching organization", { - from: this.currentState.organizationId, - to: organizationId, - }); +// logger.debug("Switching organization", { +// from: this.currentState.organizationId, +// to: organizationId, +// }); - const authenticatedConfig = this.currentState - .authConfig as AuthenticatedConfig; +// const authenticatedConfig = this.currentState +// .authConfig as AuthenticatedConfig; - const updatedConfig: AuthenticatedConfig = { - ...authenticatedConfig, - organizationId, - }; +// const updatedConfig: AuthenticatedConfig = { +// ...authenticatedConfig, +// organizationId, +// }; - saveAuthConfig(updatedConfig); +// saveAuthConfig(updatedConfig); - this.setState({ - authConfig: updatedConfig, - isAuthenticated: true, - organizationId: organizationId || undefined, - }); +// this.setState({ +// authConfig: updatedConfig, +// isAuthenticated: true, +// organizationId: organizationId || undefined, +// }); - logger.debug("Organization switched", { - newOrgId: this.currentState.organizationId, - }); +// logger.debug("Organization switched", { +// newOrgId: this.currentState.organizationId, +// }); - return this.getState(); - } +// return this.getState(); +// } - /** - * Get available organizations for the current user - */ - async getAvailableOrganizations(): Promise< - { id: string; name: string }[] | null - > { - if (!this.currentState.isAuthenticated) { - return null; - } +// /** +// * Get available organizations for the current user +// */ +// async getAvailableOrganizations(): Promise< +// { id: string; name: string }[] | null +// > { +// if (!this.currentState.isAuthenticated) { +// return null; +// } - try { - return await listUserOrganizations(); - } catch (error: any) { - logger.error("Failed to list organizations:", error); - this.emit("error", error); - return null; - } - } +// try { +// return await listUserOrganizations(); +// } catch (error: any) { +// logger.error("Failed to list organizations:", error); +// this.emit("error", error); +// return null; +// } +// } - /** - * Check if the current user has multiple organizations available - */ - async hasMultipleOrganizations(): Promise { - const orgs = await this.getAvailableOrganizations(); - return orgs !== null && orgs.length > 0; - } +// /** +// * Check if the current user has multiple organizations available +// */ +// async hasMultipleOrganizations(): Promise { +// const orgs = await this.getAvailableOrganizations(); +// return orgs !== null && orgs.length > 0; +// } - /** - * Refresh auth state from disk (useful after external changes) - */ - async refresh(): Promise { - logger.debug("Refreshing auth state from disk"); - return this.reload(); - } -} +// /** +// * Refresh auth state from disk (useful after external changes) +// */ +// async refresh(): Promise { +// logger.debug("Refreshing auth state from disk"); +// return this.reload(); +// } +// } +export {}; diff --git a/extensions/cli/src/services/ConfigService.test.ts b/extensions/cli/src/services/ConfigService.test.ts index 84d2ba5ae..e230b1bde 100644 --- a/extensions/cli/src/services/ConfigService.test.ts +++ b/extensions/cli/src/services/ConfigService.test.ts @@ -286,7 +286,11 @@ describe("ConfigService", () => { describe("getDependencies()", () => { test("should declare auth and apiClient dependencies", () => { - expect(service.getDependencies()).toEqual(["auth", "apiClient"]); + expect(service.getDependencies()).toEqual([ + "auth", + "apiClient", + "workflow", + ]); }); }); diff --git a/extensions/cli/src/services/ConfigService.ts b/extensions/cli/src/services/ConfigService.ts index 149977edb..66a3289b6 100644 --- a/extensions/cli/src/services/ConfigService.ts +++ b/extensions/cli/src/services/ConfigService.ts @@ -32,7 +32,11 @@ export class ConfigService * Declare dependencies on other services */ getDependencies(): string[] { - return [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT]; + return [ + SERVICE_NAMES.AUTH, + SERVICE_NAMES.API_CLIENT, + SERVICE_NAMES.WORKFLOW, + ]; } /** diff --git a/extensions/cli/src/services/ModeService.test.ts b/extensions/cli/src/services/ModeService.test.ts deleted file mode 100644 index 974826377..000000000 --- a/extensions/cli/src/services/ModeService.test.ts +++ /dev/null @@ -1,259 +0,0 @@ -import { beforeEach, afterEach, describe, expect, vi, test } from "vitest"; - -import { ModeService } from "./ModeService.js"; - -describe("ModeService", () => { - let modeService: ModeService; - - beforeEach(() => { - // Reset singleton instance for each test - (ModeService as any).instance = undefined; - modeService = ModeService.getInstance(); - }); - - afterEach(() => { - // Clean up singleton instance - (ModeService as any).instance = undefined; - }); - - describe("State Management", () => { - test("should initialize with normal mode by default", async () => { - const state = await modeService.initialize({}); - - expect(state).toEqual({ - mode: "normal", - toolPermissionService: expect.any(Object), - }); - expect(modeService.getCurrentMode()).toBe("normal"); - }); - - test("should convert readonly flag to plan mode", async () => { - const state = await modeService.initialize({ readonly: true }); - - expect(state.mode).toBe("plan"); - expect(modeService.getCurrentMode()).toBe("plan"); - }); - - test("should convert auto flag to auto mode", async () => { - const state = await modeService.initialize({ auto: true }); - - expect(state.mode).toBe("auto"); - expect(modeService.getCurrentMode()).toBe("auto"); - }); - - test("should initialize tool permission service with flags", async () => { - const state = await modeService.initialize({ - allow: ["testTool"], - exclude: ["badTool"], - }); - - const toolPermissionService = state.toolPermissionService; - expect(toolPermissionService).toBeDefined(); - expect(toolPermissionService.getState()).toBeDefined(); - expect(toolPermissionService.getCurrentMode()).toBe("normal"); - }); - }); - - describe("switchMode()", () => { - beforeEach(async () => { - await modeService.initialize({}); - }); - - test("should switch from normal to plan mode", () => { - expect(modeService.getCurrentMode()).toBe("normal"); - - modeService.switchMode("plan"); - - expect(modeService.getCurrentMode()).toBe("plan"); - expect(modeService.getState().mode).toBe("plan"); - }); - - test("should switch from plan to auto mode", () => { - modeService.switchMode("plan"); - expect(modeService.getCurrentMode()).toBe("plan"); - - modeService.switchMode("auto"); - - expect(modeService.getCurrentMode()).toBe("auto"); - expect(modeService.getState().mode).toBe("auto"); - }); - - test("should switch back to normal mode", () => { - modeService.switchMode("plan"); - modeService.switchMode("normal"); - - expect(modeService.getCurrentMode()).toBe("normal"); - expect(modeService.getState().mode).toBe("normal"); - }); - - test("should update tool permission service when switching modes", () => { - const toolPermissionService = modeService.getToolPermissionService(); - const initialState = toolPermissionService.getState(); - - modeService.switchMode("auto"); - const newState = toolPermissionService.getState(); - - expect(newState.currentMode).toBe("auto"); - expect(newState.permissions.policies.length).toBeGreaterThan(0); - expect(newState.permissions.policies[0]).toEqual({ - tool: "*", - permission: "allow", - }); - }); - - test("should handle multiple mode switches correctly", () => { - // Start in normal - expect(modeService.getCurrentMode()).toBe("normal"); - - // Switch to plan - modeService.switchMode("plan"); - const planState = modeService.getToolPermissionService().getState(); - expect(planState.permissions.policies).toContainEqual({ - tool: "Write", - permission: "exclude", - }); - - // Switch to auto - modeService.switchMode("auto"); - const autoState = modeService.getToolPermissionService().getState(); - expect(autoState.permissions.policies).toHaveLength(1); - expect(autoState.permissions.policies[0]).toEqual({ - tool: "*", - permission: "allow", - }); - - // Back to normal - modeService.switchMode("normal"); - const normalState = modeService.getToolPermissionService().getState(); - expect(normalState.currentMode).toBe("normal"); - }); - }); - - describe("getAvailableModes()", () => { - beforeEach(async () => { - await modeService.initialize({}); - }); - - test("should return all available modes with descriptions", () => { - const modes = modeService.getAvailableModes(); - expect(modes).toHaveLength(3); - - const modeNames = modes.map((m) => m.mode); - expect(modeNames).toContain("normal"); - expect(modeNames).toContain("plan"); - expect(modeNames).toContain("auto"); - - // Check that all modes have descriptions - modes.forEach((mode) => { - expect(mode.description).toBeDefined(); - expect(mode.description.length).toBeGreaterThan(0); - }); - }); - }); - - describe("Singleton Behavior", () => { - test("should return the same instance", () => { - const instance1 = ModeService.getInstance(); - const instance2 = ModeService.getInstance(); - expect(instance1).toBe(instance2); - }); - - test("should maintain state across getInstance calls", async () => { - const instance1 = ModeService.getInstance(); - await instance1.initialize({}); - instance1.switchMode("plan"); - - const instance2 = ModeService.getInstance(); - expect(instance2.getCurrentMode()).toBe("plan"); - }); - }); - - describe("isReady()", () => { - test("should always return true for ModeService", () => { - // ModeService is always ready since it's a singleton - expect(modeService.isReady()).toBe(true); - }); - }); - - describe("Event Emission", () => { - let modeChangeListener: ReturnType; - let stateChangeListener: ReturnType; - - beforeEach(async () => { - await modeService.initialize({}); - modeChangeListener = vi.fn(); - stateChangeListener = vi.fn(); - modeService.on("modeChanged", modeChangeListener); - modeService.on("stateChanged", stateChangeListener); - }); - - afterEach(() => { - modeService.off("modeChanged", modeChangeListener); - modeService.off("stateChanged", stateChangeListener); - }); - - test("should emit modeChanged event when mode switches", () => { - modeService.switchMode("plan"); - - expect(modeChangeListener).toHaveBeenCalledWith("plan", "normal"); - expect(modeChangeListener).toHaveBeenCalledTimes(1); - }); - - test("should emit stateChanged event when mode switches", () => { - modeService.switchMode("plan"); - - expect(stateChangeListener).toHaveBeenCalledWith( - expect.objectContaining({ mode: "plan" }), - expect.objectContaining({ mode: "normal" }), - ); - }); - - test("should emit event with correct previous and new modes", () => { - modeService.switchMode("plan"); - modeChangeListener.mockClear(); - stateChangeListener.mockClear(); - - modeService.switchMode("auto"); - - expect(modeChangeListener).toHaveBeenCalledWith("auto", "plan"); - expect(modeChangeListener).toHaveBeenCalledTimes(1); - expect(stateChangeListener).toHaveBeenCalledTimes(1); - }); - - test("should not emit event when switching to same mode", () => { - modeService.switchMode("plan"); - modeChangeListener.mockClear(); - stateChangeListener.mockClear(); - - modeService.switchMode("plan"); - - expect(modeChangeListener).not.toHaveBeenCalled(); - // stateChanged might still be called due to setState, but modeChanged should not - }); - }); - - describe("Integration with ToolPermissionService", () => { - beforeEach(async () => { - await modeService.initialize({ - allow: ["Read"], - exclude: ["dangerous_tool"], - }); - }); - - test("should pass initialization args to ToolPermissionService", () => { - const toolService = modeService.getToolPermissionService(); - const state = toolService.getState(); - - // The state should have processed the allow/exclude rules - expect(state.permissions.policies).toBeDefined(); - expect(state.currentMode).toBe("normal"); - }); - - test("should maintain ToolPermissionService reference", () => { - const toolService1 = modeService.getToolPermissionService(); - const toolService2 = modeService.getToolPermissionService(); - - expect(toolService1).toBe(toolService2); - }); - }); -}); diff --git a/extensions/cli/src/services/ModeService.ts b/extensions/cli/src/services/ModeService.ts deleted file mode 100644 index b066af870..000000000 --- a/extensions/cli/src/services/ModeService.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { PermissionMode } from "../permissions/types.js"; -import { logger } from "../util/logger.js"; - -import { BaseService } from "./BaseService.js"; -import { ToolPermissionService } from "./ToolPermissionService.js"; - -export interface ModeServiceState { - mode: PermissionMode; - toolPermissionService: ToolPermissionService; -} - -/** - * Global service for managing permission modes - * Provides a singleton interface for mode switching - */ -export class ModeService extends BaseService { - private static instance: ModeService; - - private constructor() { - const toolPermissionService = new ToolPermissionService(); - super("ModeService", { - mode: "normal", - toolPermissionService, - }); - - // Increase max listeners since ModeService is a singleton that can have - // multiple subscribers (UI components, tests, etc.) - this.setMaxListeners(100); - } - - public static getInstance(): ModeService { - if (!ModeService.instance) { - ModeService.instance = new ModeService(); - } - return ModeService.instance; - } - - /** - * Initialize the mode service with command line arguments - */ - async doInitialize(args: { - readonly?: boolean; - auto?: boolean; - allow?: string[]; - ask?: string[]; - exclude?: string[]; - isHeadless?: boolean; - }): Promise { - // Convert legacy flags to mode - let mode: PermissionMode = "normal"; - if (args.readonly) { - mode = "plan"; // Legacy flag maps directly to plan mode - } else if (args.auto) { - mode = "auto"; // Auto flag maps to auto mode - } - - this.currentState.toolPermissionService.initializeSync({ - allow: args.allow, - ask: args.ask, - exclude: args.exclude, - mode, - isHeadless: args.isHeadless, - }); - - logger.debug(`ModeService initialized with mode: ${mode}`); - - return { - mode, - toolPermissionService: this.currentState.toolPermissionService, - }; - } - - /** - * Switch to a different mode - */ - public switchMode(mode: PermissionMode): void { - const previousMode = this.currentState.mode; - this.currentState.toolPermissionService.switchMode(mode); - - this.setState({ mode }); - - logger.info(`Switched to ${mode} mode`); - - // Emit mode change event for immediate UI updates - if (previousMode !== mode) { - this.emit("modeChanged", mode, previousMode); - } - } - - /** - * Get the current mode - */ - public getCurrentMode(): PermissionMode { - return this.currentState.mode; - } - - /** - * Get the tool permission service instance - */ - public getToolPermissionService(): ToolPermissionService { - return this.currentState.toolPermissionService; - } - - /** - * Get available modes with descriptions - */ - public getAvailableModes(): Array<{ - mode: PermissionMode; - description: string; - }> { - return [ - { - mode: "normal", - description: "Default mode - follows configured permission policies", - }, - { - mode: "plan", - description: "Planning mode - only allow read-only tools for analysis", - }, - { - mode: "auto", - description: "Automatically allow all tools without asking", - }, - ]; - } - - /** - * Override cleanup to properly clean up nested ToolPermissionService - */ - override async cleanup(): Promise { - await this.currentState.toolPermissionService.cleanup(); - await super.cleanup(); - } - - /** - * Override isReady since this is a singleton with immediate availability - */ - override isReady(): boolean { - return true; - } -} - -// Export singleton instance -export const modeService = ModeService.getInstance(); diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index c4da9e331..e09c65d49 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -99,7 +99,6 @@ export class ModelService }); const llmApi = createLlmApi(selectedModel, authConfig); - if (!llmApi) { throw new Error(`Failed to initialize LLM with ${modelSource} model`); } diff --git a/extensions/cli/src/services/ServiceContainer.ts b/extensions/cli/src/services/ServiceContainer.ts index adaaa1072..d12acf351 100644 --- a/extensions/cli/src/services/ServiceContainer.ts +++ b/extensions/cli/src/services/ServiceContainer.ts @@ -2,7 +2,7 @@ import { EventEmitter } from "events"; import { logger } from "../util/logger.js"; -import { ServiceResult, ServiceState } from "./types.js"; +import { type ServiceResult, type ServiceState } from "./types.js"; /** * Central service container that manages service lifecycle and dependencies diff --git a/extensions/cli/src/services/SystemMessageService.test.ts b/extensions/cli/src/services/SystemMessageService.test.ts index a17894ee9..c76bbb8b9 100644 --- a/extensions/cli/src/services/SystemMessageService.test.ts +++ b/extensions/cli/src/services/SystemMessageService.test.ts @@ -1,7 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { modeService } from "./ModeService.js"; import { SystemMessageService } from "./SystemMessageService.js"; +import { services } from "./index.js"; +const toolPermissionService = services.toolPermissions; // Mock the systemMessage module vi.mock("../systemMessage.js", () => ({ @@ -71,7 +72,7 @@ describe("SystemMessageService", () => { constructSystemMessageMock.mockResolvedValue("Test system message"); await service.initialize(config); - const message = await service.getSystemMessage(); + const message = await service.getSystemMessage("normal"); expect(constructSystemMessageMock).toHaveBeenCalledWith( ["rule1"], @@ -81,25 +82,6 @@ describe("SystemMessageService", () => { ); expect(message).toBe("Test system message"); }); - - it("should use updated mode when mode changes", async () => { - constructSystemMessageMock.mockResolvedValue("Updated system message"); - - await service.initialize({}); - - // Simulate mode change - modeService.emit("modeChanged", "plan", "normal"); - - const message = await service.getSystemMessage(); - - expect(constructSystemMessageMock).toHaveBeenCalledWith( - undefined, - undefined, - undefined, - "plan", - ); - expect(message).toBe("Updated system message"); - }); }); describe("updateConfig", () => { @@ -114,7 +96,7 @@ describe("SystemMessageService", () => { }); constructSystemMessageMock.mockResolvedValue("Updated message"); - await service.getSystemMessage(); + await service.getSystemMessage("normal"); expect(constructSystemMessageMock).toHaveBeenCalledWith( ["rule1"], @@ -135,7 +117,7 @@ describe("SystemMessageService", () => { }); constructSystemMessageMock.mockResolvedValue("Updated message"); - await service.getSystemMessage(); + await service.getSystemMessage("normal"); expect(constructSystemMessageMock).toHaveBeenCalledWith( ["rule2", "rule3"], @@ -146,31 +128,6 @@ describe("SystemMessageService", () => { }); }); - describe("mode tracking", () => { - it("should track current mode from ModeService", async () => { - await service.initialize({}); - - expect(service.getCurrentMode()).toBe("normal"); - - // Simulate mode change - modeService.emit("modeChanged", "auto", "normal"); - - expect(service.getCurrentMode()).toBe("auto"); - }); - - it("should initialize with current mode from ModeService", async () => { - // Mock modeService.getCurrentMode - vi.spyOn(modeService, "getCurrentMode").mockReturnValue("plan"); - - const newService = new SystemMessageService(); - await newService.initialize({}); - - expect(newService.getCurrentMode()).toBe("plan"); - - await newService.cleanup(); - }); - }); - describe("error handling", () => { it("should handle constructSystemMessage errors gracefully", async () => { constructSystemMessageMock.mockRejectedValue( @@ -179,7 +136,7 @@ describe("SystemMessageService", () => { await service.initialize({}); - await expect(service.getSystemMessage()).rejects.toThrow( + await expect(service.getSystemMessage("normal")).rejects.toThrow( "Failed to construct", ); }); diff --git a/extensions/cli/src/services/SystemMessageService.ts b/extensions/cli/src/services/SystemMessageService.ts index 2711f6990..1f2bbf2eb 100644 --- a/extensions/cli/src/services/SystemMessageService.ts +++ b/extensions/cli/src/services/SystemMessageService.ts @@ -3,7 +3,7 @@ import { constructSystemMessage } from "../systemMessage.js"; import { logger } from "../util/logger.js"; import { BaseService } from "./BaseService.js"; -import { modeService } from "./ModeService.js"; +import { SERVICE_NAMES } from "./types.js"; export interface SystemMessageServiceState { additionalRules?: string[]; @@ -16,26 +16,8 @@ export interface SystemMessageServiceState { * Provides fresh system messages that reflect current mode and configuration */ export class SystemMessageService extends BaseService { - private currentMode: PermissionMode = "normal"; - constructor() { super("SystemMessageService", {}); - - // Listen to mode changes from ModeService - this.setupModeListener(); - } - - /** - * Set up listener for mode changes - */ - private setupModeListener(): void { - modeService.on("modeChanged", (newMode: PermissionMode) => { - logger.debug(`SystemMessageService: Mode changed to ${newMode}`); - this.currentMode = newMode; - }); - - // Initialize current mode - this.currentMode = modeService.getCurrentMode(); } /** @@ -64,24 +46,28 @@ export class SystemMessageService extends BaseService /** * Get a fresh system message with current mode and configuration */ - public async getSystemMessage(): Promise { + public async getSystemMessage(currentMode: PermissionMode): Promise { const { additionalRules, format, headless } = this.currentState; const systemMessage = await constructSystemMessage( additionalRules, format, headless, - this.currentMode, + currentMode, ); logger.debug("Generated fresh system message", { - mode: this.currentMode, + mode: currentMode, messageLength: systemMessage.length, }); return systemMessage; } + getDependencies(): string[] { + return [SERVICE_NAMES.TOOL_PERMISSIONS]; + } + /** * Update configuration that affects system message */ @@ -93,14 +79,4 @@ export class SystemMessageService extends BaseService logger.debug("SystemMessageService config updated", config); } - - /** - * Get the current mode being used for system messages - */ - public getCurrentMode(): PermissionMode { - return this.currentMode; - } } - -// Export singleton instance -export const systemMessageService = new SystemMessageService(); diff --git a/extensions/cli/src/services/ToolPermissionService.ts b/extensions/cli/src/services/ToolPermissionService.ts index e682bc9dc..dc754aad0 100644 --- a/extensions/cli/src/services/ToolPermissionService.ts +++ b/extensions/cli/src/services/ToolPermissionService.ts @@ -9,10 +9,18 @@ import { } from "../permissions/types.js"; import { logger } from "../util/logger.js"; -import { BaseService } from "./BaseService.js"; +import { BaseService, ServiceWithDependencies } from "./BaseService.js"; import { serviceContainer } from "./ServiceContainer.js"; import { SERVICE_NAMES, WorkflowServiceState } from "./types.js"; +export interface InitializeToolServiceOverrides { + allow?: string[]; + ask?: string[]; + exclude?: string[]; + mode?: PermissionMode; + isHeadless?: boolean; +} + export interface ToolPermissionServiceState { permissions: ToolPermissions; currentMode: PermissionMode; @@ -25,7 +33,10 @@ export interface ToolPermissionServiceState { /** * Service for managing tool permissions with a single source of truth */ -export class ToolPermissionService extends BaseService { +export class ToolPermissionService + extends BaseService + implements ServiceWithDependencies +{ constructor() { super("ToolPermissionService", { permissions: { policies: [] }, @@ -35,19 +46,36 @@ export class ToolPermissionService extends BaseService, + ): void { + super.setState(newState); + serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, this.currentState); + } + + /** + * Declare dependencies on other services + */ + getDependencies(): string[] { + return [SERVICE_NAMES.WORKFLOW]; + } + /** * Generate workflow-specific policies if a workflow is active */ - private generateWorkflowPolicies(): undefined | ToolPermissionPolicy[] { - const workflowResult = serviceContainer.getSync( - SERVICE_NAMES.WORKFLOW, - ); - if (!workflowResult?.value?.workflowFile?.tools) { + private generateWorkflowPolicies( + workflowServiceState?: WorkflowServiceState, + ): undefined | ToolPermissionPolicy[] { + if (!workflowServiceState?.workflowFile?.tools) { return undefined; } const parsedTools = parseWorkflowTools( - workflowResult.value.workflowFile.tools, + workflowServiceState.workflowFile.tools, ); if (parsedTools.tools.length === 0) { return undefined; @@ -134,13 +162,10 @@ export class ToolPermissionService extends BaseService { - // Ensure permissions.yaml exists before loading + async doInitialize( + runtimeOverrides?: InitializeToolServiceOverrides, + workflowServiceState?: WorkflowServiceState, + ): Promise { await ensurePermissionsYamlExists(); // Use the synchronous version after ensuring the file exists - return this.initializeSync(runtimeOverrides); + return this.initializeSync(runtimeOverrides, workflowServiceState); } /** @@ -232,13 +254,12 @@ export class ToolPermissionService extends BaseService { + return [ + { + mode: "normal", + description: "Default mode - follows configured permission policies", + }, + { + mode: "plan", + description: "Planning mode - only allow read-only tools for analysis", + }, + { + mode: "auto", + description: "Automatically allow all tools without asking", + }, + ]; + } } diff --git a/extensions/cli/src/services/index.initialization.test.ts b/extensions/cli/src/services/index.initialization.test.ts index 7aadcc57d..4d480dfcb 100644 --- a/extensions/cli/src/services/index.initialization.test.ts +++ b/extensions/cli/src/services/index.initialization.test.ts @@ -3,21 +3,13 @@ import { beforeEach, describe, expect, it } from "vitest"; import { serviceContainer } from "./ServiceContainer.js"; import type { ToolPermissionServiceState } from "./ToolPermissionService.js"; -import { initializeServices, getServiceSync, SERVICE_NAMES } from "./index.js"; +import { getServiceSync, initializeServices, SERVICE_NAMES } from "./index.js"; describe("Service Initialization", () => { beforeEach(() => { // Clean up service container state - const services = [ - SERVICE_NAMES.TOOL_PERMISSIONS, - SERVICE_NAMES.AUTH, - SERVICE_NAMES.API_CLIENT, - SERVICE_NAMES.CONFIG, - SERVICE_NAMES.MODEL, - SERVICE_NAMES.MCP, - ]; - services.forEach((service) => { + Object.keys(SERVICE_NAMES).forEach((service) => { // Reset service state (serviceContainer as any).services.delete(service); (serviceContainer as any).factories.delete(service); diff --git a/extensions/cli/src/services/index.test.ts b/extensions/cli/src/services/index.test.ts index 6978ced90..7a5cf31b6 100644 --- a/extensions/cli/src/services/index.test.ts +++ b/extensions/cli/src/services/index.test.ts @@ -1,9 +1,7 @@ import { vi } from "vitest"; -import { modeService } from "./ModeService.js"; -import { serviceContainer } from "./ServiceContainer.js"; - -import { initializeServices } from "./index.js"; +import { initializeServices, services } from "./index.js"; +import { WorkflowService } from "./WorkflowService.js"; // Mock the onboarding module vi.mock("../onboarding.js", () => ({ @@ -17,45 +15,11 @@ vi.mock("../auth/workos.js", () => ({ })); describe("initializeServices", () => { - let mockModeService: any; - let mockServiceContainer: any; + // let mockToolPermissionsService: any; beforeEach(() => { // Reset all mocks vi.clearAllMocks(); - - // Create mock mode service - mockModeService = { - initialize: vi.fn(), - getCurrentMode: vi.fn(), - getToolPermissionService: vi.fn().mockReturnValue({ - getState: vi.fn().mockReturnValue({ - currentMode: "normal", - isHeadless: false, - permissions: { policies: [] }, - }), - }), - }; - - // Create mock service container - mockServiceContainer = { - registerValue: vi.fn(), - register: vi.fn(), - initializeAll: vi.fn().mockResolvedValue(undefined), - }; - - // Set up mocks - (modeService as any).initialize = mockModeService.initialize; - (modeService as any).getCurrentMode = mockModeService.getCurrentMode; - (modeService as any).getToolPermissionService = - mockModeService.getToolPermissionService; - - // Mock serviceContainer methods - (serviceContainer as any).registerValue = - mockServiceContainer.registerValue; - (serviceContainer as any).register = mockServiceContainer.register; - (serviceContainer as any).initializeAll = - mockServiceContainer.initializeAll; }); afterEach(() => { @@ -63,28 +27,8 @@ describe("initializeServices", () => { }); describe("mode conversion", () => { - it("should pass only readonly flag for plan mode", async () => { - await initializeServices({ - headless: true, // Skip onboarding - toolPermissionOverrides: { - mode: "plan", - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - }, - }); - - expect(mockModeService.initialize).toHaveBeenCalledWith({ - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - readonly: true, - isHeadless: true, - // auto should NOT be set - }); - }); - it("should pass only auto flag for auto mode", async () => { + const spy = vi.spyOn(services.toolPermissions, "initialize"); await initializeServices({ headless: true, // Skip onboarding toolPermissionOverrides: { @@ -95,63 +39,21 @@ describe("initializeServices", () => { }, }); - expect(mockModeService.initialize).toHaveBeenCalledWith({ - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - auto: true, - isHeadless: true, - // readonly should NOT be set - }); - }); - - it("should pass no mode flags for normal mode", async () => { - await initializeServices({ - headless: true, // Skip onboarding - toolPermissionOverrides: { - mode: "normal", + expect(spy).toHaveBeenCalledWith( + { allow: ["tool1"], ask: ["tool2"], exclude: ["tool3"], + mode: "auto", + isHeadless: true, }, - }); - - expect(mockModeService.initialize).toHaveBeenCalledWith({ - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - isHeadless: true, - // Neither readonly nor auto should be set - }); - }); - - it("should pass no mode flags when mode is undefined", async () => { - await initializeServices({ - headless: true, // Skip onboarding - toolPermissionOverrides: { - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], + { + slug: null, + workflowFile: null, + workflowModelName: null, + workflowService: expect.any(WorkflowService), }, - }); - - expect(mockModeService.initialize).toHaveBeenCalledWith({ - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - isHeadless: true, - // Neither readonly nor auto should be set - }); - }); - - it("should call initialize with defaults when no toolPermissionOverrides provided", async () => { - await initializeServices({ - headless: true, // Skip onboarding - }); - - expect(mockModeService.initialize).toHaveBeenCalledWith({ - isHeadless: true, - }); + ); }); }); }); diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index f75fc1e21..b73164330 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -9,11 +9,14 @@ import { ConfigService } from "./ConfigService.js"; import { FileIndexService } from "./FileIndexService.js"; import { MCPService } from "./MCPService.js"; import { ModelService } from "./ModelService.js"; -import { modeService } from "./ModeService.js"; import { ResourceMonitoringService } from "./ResourceMonitoringService.js"; import { serviceContainer } from "./ServiceContainer.js"; import { StorageSyncService } from "./StorageSyncService.js"; -import { systemMessageService } from "./SystemMessageService.js"; +import { SystemMessageService } from "./SystemMessageService.js"; +import { + InitializeToolServiceOverrides, + ToolPermissionService, +} from "./ToolPermissionService.js"; import { ApiClientServiceState, AuthServiceState, @@ -38,6 +41,8 @@ const chatHistoryService = new ChatHistoryService(); const updateService = new UpdateService(); const storageSyncService = new StorageSyncService(); const workflowService = new WorkflowService(); +const toolPermissionService = new ToolPermissionService(); +const systemMessageService = new SystemMessageService(); /** * Initialize all services and register them with the service container @@ -79,46 +84,48 @@ export async function initializeServices( commandOptions.config = CONFIG_PATH; } - // Initialize mode service with tool permission overrides - if (initOptions.toolPermissionOverrides) { - const overrides = { ...initOptions.toolPermissionOverrides }; + serviceContainer.register( + SERVICE_NAMES.WORKFLOW, + () => workflowService.initialize(commandOptions.workflow), + [], + ); - // Convert mode to boolean flags for ModeService - const initArgs: Parameters[0] = { - allow: overrides.allow, - ask: overrides.ask, - exclude: overrides.exclude, - isHeadless: initOptions.headless, - }; - - // Only set the boolean flag that corresponds to the mode - if (overrides.mode === "plan") { - initArgs.readonly = true; - } else if (overrides.mode === "auto") { - initArgs.auto = true; - } - // If mode is "normal" or undefined, no flags are set - - await modeService.initialize(initArgs); - } else { - // Even if no overrides, we need to initialize with defaults - await modeService.initialize({ - isHeadless: initOptions.headless, - }); - } - - // Register the TOOL_PERMISSIONS service with immediate value - // Since ToolPermissionService is already initialized synchronously in ModeService, - // we can register it as a ready value instead of a factory - const toolPermissionState = modeService.getToolPermissionService().getState(); - logger.debug("Registering TOOL_PERMISSIONS with state:", { - currentMode: toolPermissionState.currentMode, - isHeadless: toolPermissionState.isHeadless, - policyCount: toolPermissionState.permissions.policies.length, - }); - serviceContainer.registerValue( + serviceContainer.register( SERVICE_NAMES.TOOL_PERMISSIONS, - toolPermissionState, + async () => { + const workflowState = await serviceContainer.get( + SERVICE_NAMES.WORKFLOW, + ); + + // Initialize mode service with tool permission overrides + if (initOptions.toolPermissionOverrides) { + const overrides = { ...initOptions.toolPermissionOverrides }; + + // Convert mode to boolean flags for ModeService + const initArgs: InitializeToolServiceOverrides = { + allow: overrides.allow, + ask: overrides.ask, + exclude: overrides.exclude, + isHeadless: initOptions.headless, + }; + + // Only set the boolean flag that corresponds to the mode + if (overrides.mode) { + initArgs.mode = overrides.mode; + } + // If mode is "normal" or undefined, no flags are set + return await toolPermissionService.initialize(initArgs, workflowState); + } else { + // Even if no overrides, we need to initialize with defaults + return await toolPermissionService.initialize( + { + isHeadless: initOptions.headless, + }, + workflowState, + ); + } + }, + [SERVICE_NAMES.WORKFLOW], ); // Initialize SystemMessageService with command options @@ -130,7 +137,7 @@ export async function initializeServices( format: (commandOptions as any).format, // format option from CLI headless: initOptions.headless, }), - [], // No dependencies + [SERVICE_NAMES.TOOL_PERMISSIONS], ); serviceContainer.register( @@ -159,9 +166,10 @@ export async function initializeServices( serviceContainer.register( SERVICE_NAMES.CONFIG, async () => { - const [authState, apiClientState] = await Promise.all([ + const [authState, apiClientState, workflowState] = await Promise.all([ serviceContainer.get(SERVICE_NAMES.AUTH), serviceContainer.get(SERVICE_NAMES.API_CLIENT), + serviceContainer.get(SERVICE_NAMES.WORKFLOW), ]); // Ensure organization is selected if authenticated @@ -207,9 +215,10 @@ export async function initializeServices( finalAuthState.organizationId || null, apiClientState.apiClient, commandOptions, + workflowState, ); }, - [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT], // Depends on auth and API client + [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT, SERVICE_NAMES.WORKFLOW], // Dependencies ); serviceContainer.register( @@ -273,12 +282,6 @@ export async function initializeServices( [], // No dependencies for now, but could depend on SESSION in future ); - serviceContainer.register( - SERVICE_NAMES.WORKFLOW, - () => workflowService.initialize(commandOptions.workflow), - [], - ); - // Eagerly initialize all services to ensure they're ready when needed // This avoids race conditions and "service not ready" errors await serviceContainer.initializeAll(); @@ -335,13 +338,13 @@ export const services = { apiClient: apiClientService, mcp: mcpService, fileIndex: fileIndexService, - mode: modeService, resourceMonitoring: resourceMonitoringService, systemMessage: systemMessageService, chatHistory: chatHistoryService, updateService: updateService, storageSync: storageSyncService, workflow: workflowService, + toolPermissions: toolPermissionService, } as const; // Export the service container for advanced usage diff --git a/extensions/cli/src/services/types.ts b/extensions/cli/src/services/types.ts index 51d0e46a6..9ce7b355b 100644 --- a/extensions/cli/src/services/types.ts +++ b/extensions/cli/src/services/types.ts @@ -10,9 +10,9 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { AuthConfig } from "../auth/workos.js"; import { BaseCommandOptions } from "../commands/BaseCommandOptions.js"; -import { PermissionMode, ToolPermissions } from "../permissions/types.js"; +import { PermissionMode } from "../permissions/types.js"; -import { MCPService } from "./MCPService.js"; +import { type MCPService } from "./MCPService.js"; import { WorkflowService } from "./WorkflowService.js"; /** @@ -109,13 +109,6 @@ export interface ApiClientServiceState { apiClient: DefaultApiInterface | null; } -export interface ToolPermissionServiceState { - permissions: ToolPermissions; - currentMode: PermissionMode; - modePolicyCount?: number; - originalPolicies?: ToolPermissions; -} - export interface StorageSyncServiceState { isEnabled: boolean; storageId?: string; diff --git a/extensions/cli/src/services/workflow-integration.test.ts b/extensions/cli/src/services/workflow-integration.test.ts index 4469dc179..6c2f693a8 100644 --- a/extensions/cli/src/services/workflow-integration.test.ts +++ b/extensions/cli/src/services/workflow-integration.test.ts @@ -4,7 +4,6 @@ import { ConfigEnhancer } from "../configEnhancer.js"; import { ModelService } from "./ModelService.js"; import { serviceContainer } from "./ServiceContainer.js"; -import { ToolPermissionService } from "./ToolPermissionService.js"; import { SERVICE_NAMES } from "./types.js"; import { WorkflowService } from "./WorkflowService.js"; @@ -46,7 +45,6 @@ vi.mock("../auth/workos.js", () => ({ describe("Workflow Integration Tests", () => { let workflowService: WorkflowService; let modelService: ModelService; - let toolPermissionService: ToolPermissionService; let configEnhancer: ConfigEnhancer; let mockLoadPackageFromHub: any; let mockLoadPackagesFromHub: any; @@ -100,7 +98,6 @@ describe("Workflow Integration Tests", () => { // Create service instances workflowService = new WorkflowService(); modelService = new ModelService(); - toolPermissionService = new ToolPermissionService(); configEnhancer = new ConfigEnhancer(); // Mock service container diff --git a/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts index f5a9e74bd..78f9bcc7b 100644 --- a/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts @@ -4,22 +4,16 @@ import { SERVICE_NAMES, initializeServices, serviceContainer, + services, } from "../services/index.js"; -import { modeService } from "../services/ModeService.js"; import { getAllTools } from "./handleToolCalls.js"; describe("streamChatResponse - Mode Switch During Streaming", () => { + const toolPermissionService = services.toolPermissions; beforeEach(async () => { // Clean up service container state before each test - const services = [ - SERVICE_NAMES.TOOL_PERMISSIONS, - SERVICE_NAMES.AUTH, - SERVICE_NAMES.API_CLIENT, - SERVICE_NAMES.CONFIG, - SERVICE_NAMES.MODEL, - SERVICE_NAMES.MCP, - ]; + const services = Object.keys(SERVICE_NAMES); services.forEach((service) => { (serviceContainer as any).services.delete(service); @@ -46,10 +40,10 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { expect(toolNames).toContain("Edit"); // Switch to plan mode (simulating Shift+Tab during streaming) - modeService.switchMode("plan"); + toolPermissionService.switchMode("plan"); // Update the service container (this is what UserInput.tsx does) - const updatedState = modeService.getToolPermissionService().getState(); + const updatedState = toolPermissionService.getState(); serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); // Recompute tools - should now exclude write tools @@ -68,25 +62,25 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { test("getAllTools reflects current mode immediately", async () => { // Start in normal mode - expect(modeService.getCurrentMode()).toBe("normal"); + expect(toolPermissionService.getCurrentMode()).toBe("normal"); let tools = await getAllTools(); expect(tools.map((t) => t.function.name)).toContain("Write"); // Switch to plan mode - modeService.switchMode("plan"); - let updatedState = modeService.getToolPermissionService().getState(); + toolPermissionService.switchMode("plan"); + let updatedState = toolPermissionService.getState(); serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); - expect(modeService.getCurrentMode()).toBe("plan"); + expect(toolPermissionService.getCurrentMode()).toBe("plan"); // getAllTools should immediately reflect the new mode tools = await getAllTools(); expect(tools.map((t) => t.function.name)).not.toContain("Write"); // Switch to auto mode - modeService.switchMode("auto"); - updatedState = modeService.getToolPermissionService().getState(); + toolPermissionService.switchMode("auto"); + updatedState = toolPermissionService.getState(); serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); - expect(modeService.getCurrentMode()).toBe("auto"); + expect(toolPermissionService.getCurrentMode()).toBe("auto"); // getAllTools should immediately reflect auto mode (all tools allowed) tools = await getAllTools(); diff --git a/extensions/cli/src/stream/streamChatResponse.ts b/extensions/cli/src/stream/streamChatResponse.ts index a59fa8cf7..3bcbf43a4 100644 --- a/extensions/cli/src/stream/streamChatResponse.ts +++ b/extensions/cli/src/stream/streamChatResponse.ts @@ -8,9 +8,7 @@ import type { ChatCompletionTool, } from "openai/resources.mjs"; -import { getServiceSync, SERVICE_NAMES, services } from "../services/index.js"; -import { systemMessageService } from "../services/SystemMessageService.js"; -import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; +import { services } from "../services/index.js"; import { posthogService } from "../telemetry/posthogService.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { ToolCall } from "../tools/index.js"; @@ -157,7 +155,9 @@ export async function processStreamingResponse( } // Get fresh system message and inject it - const systemMessage = await systemMessageService.getSystemMessage(); + const systemMessage = await services.systemMessage.getSystemMessage( + services.toolPermissions.getState().currentMode, + ); const openaiChatHistory = convertFromUnifiedHistoryWithSystemMessage( chatHistory, systemMessage, @@ -337,10 +337,7 @@ export async function streamChatResponse( hasCallbacks: !!callbacks, }); - const serviceResult = getServiceSync( - SERVICE_NAMES.TOOL_PERMISSIONS, - ); - const isHeadless = serviceResult.value?.isHeadless ?? false; + const isHeadless = services.toolPermissions.isHeadless(); let fullResponse = ""; let finalResponse = ""; @@ -399,7 +396,6 @@ export async function streamChatResponse( llmApi, abortController, callbacks, - isHeadless, tools, }); diff --git a/extensions/cli/src/systemMessage.test.ts b/extensions/cli/src/systemMessage.test.ts index 4f19c97f6..15f797dfc 100644 --- a/extensions/cli/src/systemMessage.test.ts +++ b/extensions/cli/src/systemMessage.test.ts @@ -8,6 +8,7 @@ const { constructSystemMessage } = await import("./systemMessage.js"); vi.mock("./services/ServiceContainer.js", () => ({ serviceContainer: { get: vi.fn().mockResolvedValue({ config: { rules: [] } }), + set: vi.fn(), }, })); diff --git a/extensions/cli/src/systemMessage.ts b/extensions/cli/src/systemMessage.ts index 96f1e8e97..9acd01085 100644 --- a/extensions/cli/src/systemMessage.ts +++ b/extensions/cli/src/systemMessage.ts @@ -7,11 +7,11 @@ import { Minimatch } from "minimatch"; import { processRule } from "./hubLoader.js"; import { PermissionMode } from "./permissions/types.js"; -import { modeService } from "./services/ModeService.js"; +import { services } from "./services/index.js"; import { serviceContainer } from "./services/ServiceContainer.js"; import { ConfigServiceState, SERVICE_NAMES } from "./services/types.js"; const { WalkerSync } = pkg; - +const toolPermissionService = services.toolPermissions; /** * Check if current directory is a git repository */ @@ -167,7 +167,7 @@ export async function constructSystemMessage( processedRules.push(...configYamlRules); // Get current mode if not provided - const currentMode = mode ?? modeService.getCurrentMode(); + const currentMode = mode ?? toolPermissionService.getCurrentMode(); // Construct the comprehensive system message let systemMessage = baseSystemMessage; diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index 36837f233..c185fa57b 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -8,8 +8,8 @@ import { MCPServiceState, SERVICE_NAMES, serviceContainer, + services, } from "../services/index.js"; -import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; import type { ModelServiceState } from "../services/types.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { logger } from "../util/logger.js"; @@ -58,17 +58,8 @@ export const BUILTIN_TOOLS: Tool[] = BASE_BUILTIN_TOOLS; function getDynamicTools(): Tool[] { const dynamicTools: Tool[] = []; - // Add headless-specific tools if in headless mode - try { - const serviceResult = getServiceSync( - SERVICE_NAMES.TOOL_PERMISSIONS, - ); - const isHeadless = serviceResult.value?.isHeadless ?? false; - if (isHeadless) { - dynamicTools.push(exitTool); - } - } catch { - // Service not ready yet, no dynamic tools + if (services.toolPermissions.isHeadless()) { + dynamicTools.push(exitTool); } // Add beta status tool if --beta-status-tool flag is present diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index 8f8f24226..64982b942 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -18,6 +18,7 @@ import { } from "../services/types.js"; import { logger } from "../util/logger.js"; +import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; import { ActionStatus } from "./components/ActionStatus.js"; import { BottomStatusBar } from "./components/BottomStatusBar.js"; import { ResourceDebugBar } from "./components/ResourceDebugBar.js"; @@ -28,7 +29,6 @@ import { useChat } from "./hooks/useChat.js"; import { useContextPercentage } from "./hooks/useContextPercentage.js"; import { useMessageRenderer } from "./hooks/useMessageRenderer.js"; import { - useCurrentMode, useIntroMessage, useLoginHandlers, useSelectors, @@ -95,7 +95,16 @@ function useTUIChatServices(remoteUrl?: string) { mcp: MCPServiceState; apiClient: ApiClientServiceState; update: UpdateServiceState; - }>(["auth", "config", "model", "mcp", "apiClient", "update"]); + toolPermissions: ToolPermissionServiceState; + }>([ + "auth", + "config", + "model", + "mcp", + "apiClient", + "update", + "toolPermissions", + ]); return { services, allServicesReady, isRemoteMode }; } @@ -162,9 +171,6 @@ const TUIChat: React.FC = ({ allServicesReady, ); - // State for current mode (for hiding cwd in plan/auto modes) - const currentMode = useCurrentMode(); - // Use login handlers const { handleLoginPrompt, handleLoginTokenSubmit } = useLoginHandlers( navigateTo, @@ -379,7 +385,7 @@ const TUIChat: React.FC = ({ {/* Free trial status and Continue CLI info - always show */} { beforeEach(() => { // Reset to normal mode for each test - modeService.initialize({}); + toolPermissionService.initialize({}); }); describe("mode cycling logic", () => { it("should cycle through modes in correct order", () => { // Initially should be normal mode - expect(modeService.getCurrentMode()).toBe("normal"); + expect(toolPermissionService.getCurrentMode()).toBe("normal"); // Cycle to plan - modeService.switchMode("plan"); - expect(modeService.getCurrentMode()).toBe("plan"); + toolPermissionService.switchMode("plan"); + expect(toolPermissionService.getCurrentMode()).toBe("plan"); // Cycle to auto - modeService.switchMode("auto"); - expect(modeService.getCurrentMode()).toBe("auto"); + toolPermissionService.switchMode("auto"); + expect(toolPermissionService.getCurrentMode()).toBe("auto"); // Cycle back to normal - modeService.switchMode("normal"); - expect(modeService.getCurrentMode()).toBe("normal"); + toolPermissionService.switchMode("normal"); + expect(toolPermissionService.getCurrentMode()).toBe("normal"); }); it("should cycle through all modes sequentially", () => { @@ -32,8 +32,8 @@ describe("UserInput Keyboard Shortcuts", () => { // Test cycling through all modes for (let i = 0; i < modes.length * 2; i++) { const expectedMode = modes[i % modes.length]; - modeService.switchMode(expectedMode); - expect(modeService.getCurrentMode()).toBe(expectedMode); + toolPermissionService.switchMode(expectedMode); + expect(toolPermissionService.getCurrentMode()).toBe(expectedMode); } }); }); diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index f1726f457..834bd68e4 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -7,8 +7,11 @@ import { getAllSlashCommands } from "../commands/commands.js"; import { useServices } from "../hooks/useService.js"; import type { PermissionMode } from "../permissions/types.js"; import type { FileIndexServiceState } from "../services/FileIndexService.js"; -import { SERVICE_NAMES, serviceContainer } from "../services/index.js"; -import { modeService } from "../services/ModeService.js"; +import { + SERVICE_NAMES, + serviceContainer, + services, +} from "../services/index.js"; import { messageQueue } from "../stream/messageQueue.js"; import { InputHistory } from "../util/inputHistory.js"; @@ -190,17 +193,17 @@ const UserInput: React.FC = ({ // Cycle through permission modes const cycleModes = async () => { const modes: PermissionMode[] = ["normal", "plan", "auto"]; - const currentMode = modeService.getCurrentMode(); + const currentMode = services.toolPermissions.getCurrentMode(); const currentIndex = modes.indexOf(currentMode); const nextIndex = (currentIndex + 1) % modes.length; const nextMode = modes[nextIndex]; - modeService.switchMode(nextMode); + services.toolPermissions.switchMode(nextMode); // Update the service container with the new tool permissions state // Since TOOL_PERMISSIONS was registered with registerValue(), we need to // update its value directly rather than reloading from a factory - const updatedState = modeService.getToolPermissionService().getState(); + const updatedState = services.toolPermissions.getState(); serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); // Show a brief indicator of the mode change diff --git a/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx index 1b60203c9..f46bab262 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx @@ -1,21 +1,6 @@ -import { vi, beforeEach, describe, it, expect } from "vitest"; - -// Mock the services -const mockToolPermissionService = { - reloadPermissions: vi.fn(), - getState: vi.fn(), - getCurrentMode: vi.fn(() => "normal"), -}; - -const mockServices = { - mode: { - getToolPermissionService: vi.fn(() => mockToolPermissionService), - }, -}; - -vi.mock("../../services/index.js", () => ({ - services: mockServices, -})); +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { services } from "../../services/index.js"; +vi.mock("../../services/index.js"); // Mock the permission system vi.mock("../../permissions/policyWriter.js", () => ({ @@ -63,7 +48,7 @@ describe("Permission Policy Reload Workflow", () => { await addPolicyToYaml(policyRule); // This is the key part we're testing - reload should be called - await services.mode.getToolPermissionService().reloadPermissions(); + await services.toolPermissions.reloadPermissions(); } catch (error) { // Handle errors gracefully } @@ -76,7 +61,7 @@ describe("Permission Policy Reload Workflow", () => { expect(addPolicyToYaml).toHaveBeenCalledWith( "tool: Edit\npermission: allow", ); - expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled(); + expect(services.toolPermissions.reloadPermissions).toHaveBeenCalled(); }); it("should handle permission reload failure gracefully", async () => { @@ -90,7 +75,7 @@ describe("Permission Policy Reload Workflow", () => { vi.mocked(addPolicyToYaml).mockResolvedValue(undefined); // Mock reloadPermissions to fail - mockToolPermissionService.reloadPermissions.mockRejectedValue( + vi.mocked(services.toolPermissions.reloadPermissions).mockRejectedValue( new Error("Reload failed"), ); @@ -118,7 +103,7 @@ describe("Permission Policy Reload Workflow", () => { await addPolicyToYaml(policyRule); // This should fail but not break the flow - await services.mode.getToolPermissionService().reloadPermissions(); + await services.toolPermissions.reloadPermissions(); } catch (error) { // Error should be caught and handled gracefully errorCaught = true; @@ -127,7 +112,7 @@ describe("Permission Policy Reload Workflow", () => { // Verify that despite the reload failure, the policy was still created expect(addPolicyToYaml).toHaveBeenCalled(); - expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled(); + expect(services.toolPermissions.reloadPermissions).toHaveBeenCalled(); expect(errorCaught).toBe(true); }); @@ -142,7 +127,9 @@ describe("Permission Policy Reload Workflow", () => { vi.mocked(addPolicyToYaml).mockResolvedValue(undefined); // Mock successful reload - mockToolPermissionService.reloadPermissions.mockResolvedValue(undefined); + vi.mocked(services.toolPermissions.reloadPermissions).mockResolvedValue( + undefined, + ); const mockActiveRequest = { toolName: "Edit", @@ -167,13 +154,13 @@ describe("Permission Policy Reload Workflow", () => { ); await addPolicyToYaml(policyRule); - await services.mode.getToolPermissionService().reloadPermissions(); + await services.toolPermissions.reloadPermissions(); } // AFTER: Policy is now active without restart // Next time user tries to edit a file, it should be automatically allowed - expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled(); + expect(services.toolPermissions.reloadPermissions).toHaveBeenCalled(); // This represents the improvement: the new policy takes effect immediately // without requiring the user to restart the Continue CLI diff --git a/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx index 77b8161ba..c7ab739e5 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx @@ -4,11 +4,14 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { getAllTools } from "src/stream/handleToolCalls.js"; -import { SERVICE_NAMES, serviceContainer } from "../../services/index.js"; -import { modeService } from "../../services/ModeService.js"; +import { + SERVICE_NAMES, + serviceContainer, + services, +} from "../../services/index.js"; import { createUITestContext } from "../../test-helpers/ui-test-context.js"; import { AppRoot } from "../AppRoot.js"; - +const toolPermissionService = services.toolPermissions; describe("TUIChat - Plan Mode Bug Reproduction", () => { let context: any; @@ -20,7 +23,9 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => { }); // Ensure mode service is properly initialized in normal mode - await modeService.initialize({}); + await toolPermissionService.doInitialize({ + mode: "normal", + }); }); afterEach(() => { @@ -142,10 +147,10 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => { // that causes the actual bug in production // First, set up a realistic service state (not mocked) - await modeService.initialize({ isHeadless: false }); + await toolPermissionService.initialize({ isHeadless: false }); // Register the tool permissions service like the real app does - const initialState = modeService.getToolPermissionService().getState(); + const initialState = toolPermissionService.getState(); serviceContainer.registerValue( SERVICE_NAMES.TOOL_PERMISSIONS, initialState, @@ -155,7 +160,7 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => { expect(() => getAllTools()).not.toThrow(); // Switch modes WITHOUT updating the service container (this simulates the bug) - modeService.switchMode("plan"); + toolPermissionService.switchMode("plan"); // The service container still has the old state, so getAllTools() should not find // the updated state with plan mode permissions. However, since the ToolPermissionService @@ -172,9 +177,5 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => { const tools = getAllTools(); expect(tools).toBeDefined(); expect(Array.isArray(tools)).toBe(true); - - // But the tools returned will be for "normal" mode, not "plan" mode - // In plan mode, many tools should be excluded, but with stale normal state, all tools are available - const planModeState = modeService.getToolPermissionService().getState(); }); }); diff --git a/extensions/cli/src/ui/components/ModeIndicator.test.tsx b/extensions/cli/src/ui/components/ModeIndicator.test.tsx index a341e826f..7e1af759a 100644 --- a/extensions/cli/src/ui/components/ModeIndicator.test.tsx +++ b/extensions/cli/src/ui/components/ModeIndicator.test.tsx @@ -1,15 +1,20 @@ import { render } from "ink-testing-library"; import React from "react"; -import { describe, expect, it, beforeEach } from "vitest"; - -import { modeService } from "../../services/ModeService.js"; +import { beforeEach, describe, expect, it } from "vitest"; +import { initializeServices, services } from "src/services/index.js"; import { ModeIndicator } from "./ModeIndicator.js"; describe("ModeIndicator", () => { - beforeEach(() => { + const toolPermissionService = services.toolPermissions; + beforeEach(async () => { // Reset to normal mode for each test - modeService.initialize({}); + await initializeServices({ + headless: true, + toolPermissionOverrides: { + mode: "normal", + }, + }); }); describe("mode display", () => { @@ -29,13 +34,13 @@ describe("ModeIndicator", () => { }); it("should use current mode from service when no mode prop provided", () => { - modeService.switchMode("plan"); + toolPermissionService.switchMode("plan"); const { lastFrame } = render(); expect(lastFrame()).toContain("plan]"); }); it("should prioritize mode prop over service mode", () => { - modeService.switchMode("plan"); + toolPermissionService.switchMode("plan"); const { lastFrame } = render(); expect(lastFrame()).toContain("auto]"); }); @@ -49,17 +54,17 @@ describe("ModeIndicator", () => { expect(lastFrame()).toBe(""); // Switch to plan - modeService.switchMode("plan"); + toolPermissionService.switchMode("plan"); rerender(); expect(lastFrame()).toContain("plan]"); // Switch to auto - modeService.switchMode("auto"); + toolPermissionService.switchMode("auto"); rerender(); expect(lastFrame()).toContain("auto]"); // Switch back to normal - modeService.switchMode("normal"); + toolPermissionService.switchMode("normal"); rerender(); expect(lastFrame()).toBe(""); }); diff --git a/extensions/cli/src/ui/components/ModeIndicator.tsx b/extensions/cli/src/ui/components/ModeIndicator.tsx index 05833df68..506237e08 100644 --- a/extensions/cli/src/ui/components/ModeIndicator.tsx +++ b/extensions/cli/src/ui/components/ModeIndicator.tsx @@ -1,38 +1,20 @@ import { Text } from "ink"; -import React, { useEffect, useState } from "react"; +import React from "react"; +import { useServices } from "src/hooks/useService.js"; +import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; +import { SERVICE_NAMES } from "src/services/types.js"; import type { PermissionMode } from "../../permissions/types.js"; -import { modeService } from "../../services/ModeService.js"; interface ModeIndicatorProps { mode?: PermissionMode; } const ModeIndicator: React.FC = ({ mode }) => { - const [currentMode, setCurrentMode] = useState( - mode || modeService.getCurrentMode(), - ); - - // Update mode when it changes (for cases where mode prop is not provided) - useEffect(() => { - if (!mode) { - // Listen for immediate mode changes - const handleModeChange = (newMode: PermissionMode) => { - setCurrentMode(newMode); - }; - - modeService.on("modeChanged", handleModeChange); - - // Set initial mode - setCurrentMode(modeService.getCurrentMode()); - - return () => { - modeService.off("modeChanged", handleModeChange); - }; - } else if (mode !== currentMode) { - setCurrentMode(mode); - } - }, [mode]); + const { services } = useServices<{ + toolPermissions: ToolPermissionServiceState; + }>([SERVICE_NAMES.TOOL_PERMISSIONS]); + const currentMode = mode ?? services.toolPermissions?.currentMode ?? "normal"; // Don't show indicator for normal mode to keep it clean if (currentMode === "normal") { diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 5cb661333..4503bae53 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -749,7 +749,7 @@ export function useChat({ logger.debug(`Policy created: ${policyRule}`); // Reload permissions to pick up the new policy without requiring restart - await services.mode.getToolPermissionService().reloadPermissions(); + await services.toolPermissions.reloadPermissions(); } catch (error) { logger.error("Failed to create policy or reload permissions", { error, diff --git a/extensions/cli/src/ui/hooks/useTUIChatHooks.ts b/extensions/cli/src/ui/hooks/useTUIChatHooks.ts index 6025496f5..b4b55fa4a 100644 --- a/extensions/cli/src/ui/hooks/useTUIChatHooks.ts +++ b/extensions/cli/src/ui/hooks/useTUIChatHooks.ts @@ -1,7 +1,5 @@ import { useCallback, useEffect, useState } from "react"; -import type { PermissionMode } from "../../permissions/types.js"; -import { modeService } from "../../services/ModeService.js"; import { getGitBranch, getGitRemoteUrl, isGitRepo } from "../../util/git.js"; import type { ConfigOption, ModelOption } from "../types/selectorTypes.js"; @@ -150,26 +148,6 @@ export function useLoginHandlers( return { handleLoginPrompt, handleLoginTokenSubmit }; } -// Custom hook for mode tracking -export function useCurrentMode() { - const [currentMode, setCurrentMode] = useState( - modeService.getCurrentMode(), - ); - - useEffect(() => { - const handleModeChange = (newMode: PermissionMode) => { - setCurrentMode(newMode); - }; - - modeService.on("modeChanged", handleModeChange); - return () => { - modeService.off("modeChanged", handleModeChange); - }; - }, []); - - return currentMode; -} - // Custom hook to combine all selector logic export function useSelectors( configPath: string | undefined,