Make statemanager global singleton (#6619)

* do not initialize duplicate statemanager in migration; use vscode api directly

* make state manager a singleton

* move statemanager init to common.ts
This commit is contained in:
celestial-vault authored and GitHub committed 2025-10-02 21:18:57 -07:00
1 parent 1cee9f33a7
commit a5699e883d
3 files changed
+78 -49

No files matched your search

+11
View File
@@ -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<WebviewProvider> {
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)
+23 -39
View File
@@ -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(),
+44 -10
View File
@@ -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<Settings> = {}
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<void>
constructor(context: ExtensionContext) {
private constructor(context: ExtensionContext) {
this.context = context
}
/**
* Initialize the cache by loading data from disk
*/
async initialize(): Promise<void> {
public static async initialize(context: ExtensionContext): Promise<StateManager> {
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<void>
onSyncExternalChange?: () => void | Promise<void>
}): 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) {