Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions packages/types/src/__tests__/global-settings.test.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions packages/types/src/__tests__/index.test.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions packages/types/src/global-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,17 @@ export const MAX_CHECKPOINT_TIMEOUT_SECONDS = 60
*/
export const DEFAULT_CHECKPOINT_TIMEOUT_SECONDS = 15

/**
* Persisted non-secret selections for a stable webview instance.
*/
export const viewStateSchema = z.object({
mode: z.string().optional(),
currentApiConfigName: z.string().optional(),
updatedAt: z.number().optional(),
/** Host-minted token binding this entry to the webview that wrote it. */
claimToken: z.string().optional(),
})

/**
* GlobalSettings
*/
Expand All @@ -125,6 +136,7 @@ export const globalSettingsSchema = z.object({
currentApiConfigName: z.string().optional(),
listApiConfigMeta: z.array(providerSettingsEntrySchema).optional(),
pinnedApiConfigs: z.record(z.string(), z.boolean()).optional(),
viewStates: z.record(z.string(), viewStateSchema).optional(),

lastShownAnnouncementId: z.string().optional(),
customInstructions: z.string().optional(),
Expand Down
11 changes: 11 additions & 0 deletions packages/types/src/vscode-extension-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ export interface ExtensionMessage {
| "originalContent"
| "rooHistoryImportProgress"
| "themeFixtureProbeRequest"
| "viewStateClaim"
| "diagnosticsRequest"
text?: string
/** For fileContent: { path, content, error? } */
Expand Down Expand Up @@ -203,6 +204,13 @@ export interface ExtensionMessage {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
values?: Record<string, any>
requestId?: string
/**
* For `viewStateClaim`: the durable `viewStates` key the delivered claim governs. The
* message is only ever sent to the webview that key belongs to.
*/
viewStateId?: string
/** For `viewStateClaim`: the host-minted token the webview stores and echoes on launch. */
viewStateClaim?: string
themeFixture?: WebviewThemeFixture
diagnostics?: WebviewDiagnosticsSnapshot
promptText?: string
Expand Down Expand Up @@ -759,6 +767,9 @@ export interface WebviewMessage {
| "themeFixtureProbeResponse"
| "diagnosticsResponse"
text?: string
viewStateId?: string
/** For `webviewDidLaunch`: the claim delivered for `viewStateId`, enforced by setViewStateId. */
viewStateClaim?: string
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
taskId?: string
editedMessageContent?: string
tab?: "settings" | "history" | "mcp" | "modes" | "chat" | "marketplace" | "cloud"
Expand Down
89 changes: 77 additions & 12 deletions src/core/config/ContextProxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ const globalSettingsExportSchema = globalSettingsSchema.omit({
taskHistory: true,
listApiConfigMeta: true,
currentApiConfigName: true,
// Per-view selection state is machine-local: it keeps flowing through the
// normal runtime and pruning paths but must not transfer between settings.
viewStates: true,
})

export class ContextProxy {
Expand All @@ -78,6 +81,7 @@ export class ContextProxy {

constructor(context: vscode.ExtensionContext) {
this.originalContext = context

this.stateCache = {}
this.secretCache = {}
this._isInitialized = false
Expand Down Expand Up @@ -397,6 +401,18 @@ export class ContextProxy {
*/
private readonly stateWriteOwner = new Map<string, object>()
private readonly secretWriteOwner = new Map<string, object>()
/**
* The secret writes that are still in flight, each paired with the claim it took,
* so a reset can wait for them to settle before it deletes the keys. Without the
* pairing a reset cannot tell a settled-but-orphaned write from a live one.
*/
private readonly pendingSecretWrites = new Map<string, Set<{ settle: Promise<void> }>>()
// A reset is in progress: the caches are meaningless mid-reset, and a secret write begun
// inside it would commit after the delete pass and survive the erase.
private resetting = false
// The reset pass currently in flight, if any: single-flight so that two callers cannot each run a
// delete pass and have whichever finishes first lower the guard under the other.
private resetInFlight: Promise<void> | null = null
/** How many writes of each secret were started. Unlike the owners, it is not cleared when a write is over. */
private readonly secretWriteCount = new Map<string, number>()

Expand Down Expand Up @@ -443,6 +459,13 @@ export class ContextProxy {
}

storeSecret(key: SecretStateKey, value?: string) {
if (this.resetting) {
// Refused rather than deferred: a deferred secret write would re-store exactly the
// value the user asked to erase, and a silently dropped one would lose the save.
return Promise.reject(
new SettingsWriteError([], [key], new Error("secret writes are refused while state is being reset")),
)
}
// Update cache.
const owner = {}
this.secretWriteOwner.set(key, owner)
Expand All @@ -454,7 +477,19 @@ export class ContextProxy {
// cache (it stays empty until the next write, `refreshSecrets` or a restart) rather than being served.
// The entry of the key is removed when the write and its read-back are over (if it is still the latest). A store
// that throws at once is turned into a rejection, so it is handled the same.
const pending = this.pendingSecretWrites.get(key) ?? new Set<{ settle: Promise<void> }>()
let settleWrite: () => void = () => {}
const entry: { settle: Promise<void> } = {
settle: new Promise<void>((resolve) => {
settleWrite = resolve
}),
}
pending.add(entry)
this.pendingSecretWrites.set(key, pending)
const release = () => {
pending.delete(entry)
if (pending.size === 0) this.pendingSecretWrites.delete(key)
settleWrite()
if (this.secretWriteOwner.get(key) === owner) this.secretWriteOwner.delete(key)
}
const stored = (async () =>
Expand Down Expand Up @@ -715,18 +750,48 @@ export class ContextProxy {
* This clears all data from both the in-memory caches and the VSCode storage.
* @returns A promise that resolves when all reset operations are complete
*/
public async resetAllState() {
// Clear in-memory caches
this.stateCache = {}
this.secretCache = {}

await Promise.all([
...GLOBAL_STATE_KEYS.map((key) => this.originalContext.globalState.update(key, undefined)),
...SECRET_STATE_KEYS.map((key) => this.originalContext.secrets.delete(key)),
...GLOBAL_SECRET_KEYS.map((key) => this.originalContext.secrets.delete(key)),
])

await this.initialize()
public resetAllState(): Promise<void> {
if (this.resetInFlight) {
// A caller that arrives mid-reset joins the pass already running rather than starting a
// second delete pass whose end could lower the guard while the first was still writing.
return this.resetInFlight
}
this.resetting = true
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const pass = (async () => {
try {
// A secret write that is in flight at this moment has already committed nothing, but it will
// commit as soon as it settles, and the deletes below cannot un-commit a write that lands
// after them. Wait for the pending writes first, then end the claims, then delete, so the
// cleared copy is the last one to land in storage and the cache stays empty afterwards.
const inFlight = [...this.pendingSecretWrites.values()].flatMap((writes) =>
[...writes].map((w) => w.settle),
)
await Promise.allSettled(inFlight)

// Clear in-memory caches
this.stateCache = {}
this.secretCache = {}
// A reset also ends write ownership: a write that is still in flight reads the Memento back
// into the cache it just lost, so clearing the caches is not enough to keep pre-reset state
// out. Ownership is what the rejection handlers gate on.
this.stateWriteOwner.clear()
this.secretWriteOwner.clear()

await Promise.all([
...GLOBAL_STATE_KEYS.map((key) => this.originalContext.globalState.update(key, undefined)),
...SECRET_STATE_KEYS.map((key) => this.originalContext.secrets.delete(key)),
...GLOBAL_SECRET_KEYS.map((key) => this.originalContext.secrets.delete(key)),
])

await this.initialize()
this.resetting = false
} finally {
this.resetting = false
this.resetInFlight = null
}
})()
this.resetInFlight = pass
return pass
}

private static _instance: ContextProxy | null = null
Expand Down
15 changes: 14 additions & 1 deletion src/core/config/ProviderSettingsManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,14 @@ export const providerProfilesSchema = z.object({

export type ProviderProfiles = z.infer<typeof providerProfilesSchema>

/** Already-deleted profile: callers branch on this type instead of matching message text. */
export class ProviderSettingsNotFoundError extends Error {
constructor(message: string) {
super(message)
this.name = "ProviderSettingsNotFoundError"
}
}

export class ProviderSettingsManager {
private static readonly SCOPE_PREFIX = "roo_cline_config_"
private readonly defaultConfigId = this.generateId()
Expand Down Expand Up @@ -514,7 +522,7 @@ export class ProviderSettingsManager {
const providerProfiles = await this.load()

if (!providerProfiles.apiConfigs[name]) {
throw new Error(`Config '${name}' not found`)
throw new ProviderSettingsNotFoundError(`Config '${name}' not found`)
}

if (Object.keys(providerProfiles.apiConfigs).length === 1) {
Expand All @@ -525,6 +533,11 @@ export class ProviderSettingsManager {
await this.store(providerProfiles)
})
} catch (error) {
// A missing config is a caller-meaningful signal, not a failure: rethrow it
// unwrapped so callers can branch on the type instead of message text.
if (error instanceof ProviderSettingsNotFoundError) {
throw error
}
throw new Error(`Failed to delete config: ${error}`)
}
}
Expand Down
Loading
Loading