diff --git a/src/common.ts b/src/common.ts index 4c2f2b9c..d3c537ff 100644 --- a/src/common.ts +++ b/src/common.ts @@ -11,6 +11,7 @@ import "./utils/path" // necessary to have access to String.prototype.toPosix import { HostProvider } from "@/hosts/host-provider" import { FileContextTracker } from "./core/context/context-tracking/FileContextTracker" +import { StateManager } from "./core/storage/StateManager" import { ExtensionRegistryInfo } from "./registry" import { audioRecordingService } from "./services/dictation/AudioRecordingService" import { ErrorService } from "./services/error" @@ -27,6 +28,16 @@ import { getLatestAnnouncementId } from "./utils/announcements" * @returns The webview provider */ export async function initialize(context: vscode.ExtensionContext): Promise { + try { + await StateManager.initialize(context) + } catch (error) { + console.error("[Controller] CRITICAL: Failed to initialize StateManager - extension may not function properly:", error) + HostProvider.window.showMessage({ + type: ShowMessageType.ERROR, + message: "Failed to initialize Cline's application state. Please restart the extension.", + }) + } + // Set the distinct ID for logging and telemetry await initializeDistinctId(context) diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index 49d5d6df..c3a6941c 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -68,50 +68,34 @@ export class Controller { constructor(readonly context: vscode.ExtensionContext) { PromptRegistry.getInstance() // Ensure prompts and tools are registered HostProvider.get().logToChannel("ClineProvider instantiated") - this.stateManager = new StateManager(context) + this.stateManager = StateManager.get() this.authService = AuthService.getInstance(this) this.ocaAuthService = OcaAuthService.initialize(this) this.accountService = ClineAccountService.getInstance() + this.authService.restoreRefreshTokenAndRetrieveAuthInfo() - // Initialize cache service asynchronously - critical for extension functionality - this.stateManager - .initialize() - .then(() => { - this.authService.restoreRefreshTokenAndRetrieveAuthInfo() - }) - .catch((error) => { - console.error( - "[Controller] CRITICAL: Failed to initialize StateManager - extension may not function properly:", - error, - ) - HostProvider.window.showMessage({ - type: ShowMessageType.ERROR, - message: "Failed to initialize Cline's application state. Please restart the extension.", - }) - }) - - // Set up persistence error recovery - this.stateManager.onPersistenceError = async ({ error }: PersistenceErrorEvent) => { - console.error("[Controller] Cache persistence failed, recovering:", error) - try { - await this.stateManager.reInitialize(this.task?.taskId) + StateManager.get().registerCallbacks({ + onPersistenceError: async ({ error }: PersistenceErrorEvent) => { + console.error("[Controller] Cache persistence failed, recovering:", error) + try { + await StateManager.get().reInitialize(this.task?.taskId) + await this.postStateToWebview() + HostProvider.window.showMessage({ + type: ShowMessageType.WARNING, + message: "Saving settings to storage failed.", + }) + } catch (recoveryError) { + console.error("[Controller] Cache recovery failed:", recoveryError) + HostProvider.window.showMessage({ + type: ShowMessageType.ERROR, + message: "Failed to save settings. Please restart the extension.", + }) + } + }, + onSyncExternalChange: async () => { await this.postStateToWebview() - HostProvider.window.showMessage({ - type: ShowMessageType.WARNING, - message: "Saving settings to storage failed.", - }) - } catch (recoveryError) { - console.error("[Controller] Cache recovery failed:", recoveryError) - HostProvider.window.showMessage({ - type: ShowMessageType.ERROR, - message: "Failed to save settings. Please restart the extension.", - }) - } - } - - this.stateManager.onSyncExternalChange = async () => { - await this.postStateToWebview() - } + }, + }) this.mcpHub = new McpHub( () => ensureMcpServersDirectoryExists(), diff --git a/src/core/storage/StateManager.ts b/src/core/storage/StateManager.ts index b9136db3..b963fdc6 100644 --- a/src/core/storage/StateManager.ts +++ b/src/core/storage/StateManager.ts @@ -33,6 +33,8 @@ export interface PersistenceErrorEvent { * Provides immediate reads/writes with async disk persistence */ export class StateManager { + private static instance: StateManager | null = null + private globalStateCache: GlobalStateAndSettings = {} as GlobalStateAndSettings private taskStateCache: Partial = {} private secretsCache: Secrets = {} as Secrets @@ -55,32 +57,64 @@ export class StateManager { // Callback to sync external state changes with the UI client onSyncExternalChange?: () => void | Promise - constructor(context: ExtensionContext) { + private constructor(context: ExtensionContext) { this.context = context } /** * Initialize the cache by loading data from disk */ - async initialize(): Promise { + public static async initialize(context: ExtensionContext): Promise { + if (!StateManager.instance) { + StateManager.instance = new StateManager(context) + } + + if (StateManager.instance.isInitialized) { + throw new Error("StateManager has already been initialized.") + } + try { // Load all extension state from disk - const globalState = await readGlobalStateFromDisk(this.context) - const secrets = await readSecretsFromDisk(this.context) - const workspaceState = await readWorkspaceStateFromDisk(this.context) + const globalState = await readGlobalStateFromDisk(StateManager.instance.context) + const secrets = await readSecretsFromDisk(StateManager.instance.context) + const workspaceState = await readWorkspaceStateFromDisk(StateManager.instance.context) // Populate the cache with all extension state and secrets fields // Use populate method to avoid triggering persistence during initialization - this.populateCache(globalState, secrets, workspaceState) - - this.isInitialized = true + StateManager.instance.populateCache(globalState, secrets, workspaceState) // Start watcher for taskHistory.json so external edits update cache (no persist loop) - await this.setupTaskHistoryWatcher() + await StateManager.instance.setupTaskHistoryWatcher() + + StateManager.instance.isInitialized = true } catch (error) { console.error("[StateManager] Failed to initialize:", error) throw error } + + return StateManager.instance + } + + public static get(): StateManager { + if (!StateManager.instance) { + throw new Error("StateManager has not been initialized") + } + return StateManager.instance + } + + /** + * Register callbacks for state manager events + */ + public registerCallbacks(callbacks: { + onPersistenceError?: (event: PersistenceErrorEvent) => void | Promise + onSyncExternalChange?: () => void | Promise + }): void { + if (callbacks.onPersistenceError) { + this.onPersistenceError = callbacks.onPersistenceError + } + if (callbacks.onSyncExternalChange) { + this.onSyncExternalChange = callbacks.onSyncExternalChange + } } /** @@ -691,7 +725,7 @@ export class StateManager { this.dispose() // Reinitialize from disk - await this.initialize() + await StateManager.initialize(this.context) // If there's an active task, reload its settings if (currentTaskId) {